How do I apply a map of tags to aws_autoscaling_group?

red*_*888 2 terraform terraform-provider-aws

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"
    )
  )}"
Run Code Online (Sandbox Code Playgroud)

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?

viv*_*d4v 5

我使用null资源进行处理,并将其输出作为标签,示例如下-

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
      }
    ]
}
Run Code Online (Sandbox Code Playgroud)

您可以替换var.tagslocal.common_tags

Terraform 0.12+的重要更新。现在,它支持动态嵌套块和for-each。如果您使用的是0.12+版本,请使用以下代码-

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

}
Run Code Online (Sandbox Code Playgroud)

  • 更新+1。如果找到空资源方法[此处(锁定)](https://github.com/hashicorp/terraform/issues/15226#),它甚至不适用于 Terraform 12,而且动态方法更具可读性和不那么老套。 (2认同)