0
votes

Using terraform 0.14 and the azurerm provider 2.52.0.

I need to create 10+ public/static IPs in the same resource group.

I have created a module that can create one IP and tested that it works:

modules/public-ip/main.tf

provider "azurerm" {
  features {}
}

resource "azurerm_resource_group" "ip-rg" {
  name = var.resource_group
  location = var.location
}

resource azurerm_public_ip "public_ip" {
  name                = var.public_ip_name

  resource_group_name = azurerm_resource_group.ip-rg.name
  location = azurerm_resource_group.ip-rg.location
  allocation_method   = "Static"
  ip_version          = "IPv4"
  sku                 = "standard"
}

configurations/dev/main.tf

terraform {
  backend "azurerm" {
    key = "dev.tfstate"
  }
}

module "public_ip_01" {
  source = "../modules/public-ip/"
  resource_group = "public_ip_rg"
  location = "westeurope"  
  public_ip_name="my_public_001"
}

module "public_ip_02" {
  source = "../modules/public-ip/"
  resource_group = "public_ip_rg"
  location = "westeurope"  
  public_ip_name="my_public_002"
}

....

But that will quickly get messy - even though I use the same module there will be 10+ of those blocks.

I assume I am missing some better way to do this in terraform?

1
Are loops what you are missing?! terraform.io/docs/language/expressions/for.htmlsilent
Hm yes looks like it. could be great with an example , as simple as a string list as inputu123

1 Answers

1
votes

You can use for_each and count meta_arguments in the module. Especially, module support for for_eachand count was added in Terraform 0.13, and previous versions can only use it with resources.

For example, you can use a for_each argument whose value is a map or a set of strings in that module block, Terraform will create one instance for each member of that map or set.

To create two public IP address like this:

provider "azurerm" {
  features {}
}

module "public_ip_01" {
  for_each = toset(["my_public_001","my_public_002"])
  source = "../modules/public-ip/"
  resource_group = "public_ip_rg"
  location = "westeurope"  
  public_ip_name= each.key
}