Using terraform, how to create multiple resources of same type with unique and unidentical names using list/count for azure?

Viewed 15896

Here is a basic example for what I am trying to achieve. I have two files (main.tf) and (variable.tf), I want to create two resource groups and in the variables file is a list of names which I want the resource groups to occupy. First name of the first resource group and similarly going forward. So help me out on how to achieve it. I am using terraform v0.13.

main.tf file:

provider "azurerm" {
 features {}
}


resource "azurerm_resource_group" "test" {
  count    = 2
  name     = var.resource_group_name
  location = var.location
}

variable.tf file:

  variable "resource_group_name" {
  description = "Default resource group name that the network will be created in."
  type        = list
  default     = ["asd-rg","asd2-rg"]

}



variable "location" {
  description = "The location/region where the core network will be created.
  default     = "westus"
}
3 Answers

You just need to change the resource group block like this:

resource "azurerm_resource_group" "test" {
  count    = 2
  name     = element(var.resource_group_name, count.index)
  location = var.location
}

You can use the for_each syntax to create multiple resource of similar type. It requires a set (of unique values) to iterate over, hence convert your variable resource_group_name to set.

variable.tf

 variable "resource_group_name" {
  description = "Default resource group name that the network will be created in."
  type        = list(string)
  default     = ["asd-rg","asd2-rg"]

}



variable "location" {
  description = "The location/region where the core network will be created.
  default     = "westus"
}

main.tf

provider "azurerm" {
 features {}
}


resource "azurerm_resource_group" "test" {
  name     = each.value                       // value from iteration
  location = var.location
  for_each = toset(var.resource_group_name)   // convert list to set and iterate over it
}

Edit: variable can be of type string, list or map. This needs to be converted to set to be used with for_each

for you can use the combination of length and count to create multiple resources of the same type with unique and unidentical names.

You just need to change the resource group block like this:

resource "azurerm_resource_group" "test" {
  count    = length(var.resource_group_name)
  name     = element(concat(var.resource_group_name, [""]), count.index)
  location = var.location
}
Related