Adding dynamic tags to amazon resources

This message is extracted from a ticket originally emailed to support@gruntwork.io. Names and URLs have been removed where appropriate.

I am trying to add tags on resources as EC2 instances. I work in infrastructure-modules/services/ecs-cluster in main.tf file of the ecs-cluster I can have:

custom_tags_ec2_instances = "${var.custom_tags_ec2_instances}"

In the var.tf I can have:

variable "custom_tags_ec2_instances" {
  description = "A list of custom tags to apply to the EC2 Instances in this ASG. Each item in this list should be a map with the parameters key, value, and propagate_at_launch."
   type = "list"
   default = [{
        key = "environment"
        value = "some-value"
        propagate_at_launch = true
      }]
 }

The above configuration works and the tags appear under the resources. But I cannot change the value to a variables, the terraform returns:

Variable 'custom_tags_ec2_instances': cannot contain interpolations

The output looks expected, I read on the internet when interpolation is allowed. How can I set this value to be showing the content of "${var.cluster_name}" for example? Thank you.

As you saw, Terraform does not allow interpolations in the default parameter of a variable. Two alternatives for you to try:

  1. As of Terraform 0.10.3, you can define local values, which do support interpolation. If your team has upgraded to at least 0.10.3, this is your best option.

  2. You can set the value inline (rather than in a variable) with the list function and map function and use interpolations in that. See the example below. Obviously, this is an uglier workaround, so use local values if possible!

    custom_tags_ec2_instances = "${list(
      map(
        "key", "foo",
        "value", "${var.service_name}",
        "propagate_at_launch", true
      )
    )}"