1
votes

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

2 Answers

2
votes

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
}
1
votes

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        = lisst(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