Reputation: 16267
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?
Upvotes: 0
Views: 806
Reputation: 28204
You can use for_each and count meta_arguments in the module. Especially, module support for for_each
and 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
}
Upvotes: 1