[TF 0.12.x] Syntax for resource creation by non-numeric index For-loop - Can this be done in current version of Terraform?

I am trying do dynamically create a resource from an indexed map.

Example

# terraform.tfvars
repo_collection = {
  test = {
    name = "test"
    description = "test"
    repo_privacy = false
  }
}

# main.tf
variable "repos" {
    type = map(map(string))
}

resource "github_repository" "collection" {
  for_each = var.repos

  name        = each.value["name"]
  description = each.value["description"]
  private     = each.value["repo_privacy"]
}

My understanding that currenly “for_each” as a main attribute for a resource is for future version Terraform.

My question, is there another workaround for me to achieve above that is valid in Terraform 0.12.2?
My current workaround is to just fallback to statically defining each resource.

Hi @mechastorm,

This feature is not complete in 0.12.2 and is therefore disabled. There isn’t any equivalent approach available in the current language. However, continued work on that feature is underway and planned for a future 0.12.x minor release.

2 Likes

I was just about to create a post asking the status of this :slight_smile: . I’m glad to hear it is still being worked on.
@mechastorm Here is the link describing the functionality, and that it isn’t implemented yet.

You can use count and then do lookups and element function calls on your var.repos variable. It isn’t clean, and if you remove elements in the middle, it will cause the state to rebuild a lot of stuff that doesn’t need to be rebuilt.

– tfvars

users = {
  "user1" = {
    "name" = "tom"
  }
  "user2" = {
    "name" = "dick"
  }
  "user3" = {
    "name" = "harry"
  }
}

– tf file

variable "users" {
  type = map(map(string))
  description = "your standard users"
}

resource "local_file" "file_test" {
  count    = length(keys(var.users))
  content  = "foo"
  filename = "./${var.users[element(keys(var.users), count.index)].name}.txt"
}