Skip to content

Ability to iterate over a list/map and create resources #8573

@garo

Description

@garo

Currently Terraform and HCL can do iteration using count and then the lookup() and element() functions. These work for simple cases, but they fail if there's a need to do a more complex iterations and nested definitions.

Consider this example what I would want to do:

variable "topics" {
  default = ["new_users", "deleted_users"]
}

variable "environments" {
  default = ["prod", "staging", "testing", "development]
}

for $topic in topics {
  # Define SNS topics which are shared between all environments
  resource "aws_sns_topic" "$topic.$env" { ... }

  for $env in environments {
    # Then for each topic define a queue for each env
    resource "aws_sqs_queue" "$topic.$env-processors" { ... }

    # And bind the created queue to its sns topic
    resource "aws_sns_topic_subscription" "$topic.$env-to-$topic.$env-processors" {
      topic_arn = "${aws_sns_topic.${topic.$env}.arn}"
      endpoint = "${aws_sqs_queue.{$topic.$env-processors}.arn}"
    }
  }
}

The especially problematic parts are the topic_arn and endpoint properties in this example, where I want to reference an ARN for another resource, which name is created based on iterating two different lists.

There has been similar suggestions like #4410 and #58

The best what I've come up so far is this:


variable "foo" {
    default = ["1", "2", "3"]
}

variable "bar" {
    default = ["a", "b"]
}

resource "aws_sns_topic" "test" {
    name = "${element(var.foo, count.index / length(var.bar))}-${element(var.bar, count.index)}"
    count = "${length(var.foo) * length(var.bar)}"
}

but this doesn't solve the aws_sns_topic_subscription problem, it's error prone to mistakes as it requires complex expression in the name and count fields.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions