Search code examples
azureterraformterraform-provider-azure

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


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"
}

Solution

  • 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
    }