Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I apply a map of tags to aws_autoscaling_group?

https://www.terraform.io/docs/providers/aws/r/autoscaling_group.html#propagate_at_launch

I do this to apply tags to aws resources:

  tags = "${merge(
    local.common_tags, // reused in many resources
    map(
      "Name", "awesome-app-server",
      "Role", "server"
    )
  )}"

But the asg requires propagate_at_launch field.

I already have my map of tags in use in many other resources and I'd like to reuse it for the asg resources to. Pretty sure I'll always be setting propagate_at_launch to true. How can I add that to every element of the map and use it for the tags field?

like image 316
red888 Avatar asked Dec 10 '18 02:12

red888


1 Answers

I do it using a null resource and take it's output as a tag, sample below -

data "null_data_source" "tags" {
  count = "${length(keys(var.tags))}"

  inputs = {
    key                 = "${element(keys(var.tags), count.index)}"
    value               = "${element(values(var.tags), count.index)}"
    propagate_at_launch = true
  }
}


resource "aws_autoscaling_group" "asg_ec2" {
    ..........
    ..........

    lifecycle {
    create_before_destroy = true
    }

    tags = ["${data.null_data_source.tags.*.outputs}"]
    tags = [
      {
      key                 = "Name"
      value               = "awesome-app-server"
      propagate_at_launch = true
       },
      {
      key                 = "Role"
      value               = "server"
      propagate_at_launch = true
      }
    ]
}

You can replace var.tags with local.common_tags.

IMPORTANT UPDATE for Terraform 0.12+. It now supports dynamic nested blocks and for-each. If you are on 0.12+ version, use below code -

resource "aws_autoscaling_group" "asg_ec2" {
    ..........
    ..........

    lifecycle {
    create_before_destroy = true
    }

  tag {
    key                 = "Name"
    value               = "awesome-app-server"
    propagate_at_launch = true
  }

  tag {
    key                 = "Role"
    value               = "server"
    propagate_at_launch = true
  }

  dynamic "tag" {
    for_each = var.tags

    content {
      key    =  tag.key
      value   =  tag.value
      propagate_at_launch =  true
    }
  }

}
like image 195
vivekyad4v Avatar answered Sep 22 '22 02:09

vivekyad4v