0
votes

I want to create AWS CloudWatch dashboard with some metrics via Terraform. All my infrastructure are described in Terraform and I understand how to create AWS CloudWatch dashboard (Terraform + json template). The stuck is in AWS AutoScaling Group. When I want to display some metrics on dashboard, I just use constructions like

some_monitored_instance_id = "${aws_instance.some_instance.id}"

which then puts to json template like

    "metrics": [
      ["AWS/EC2", "CPUUtilization", "InstanceId", "${some_monitored_instance_id}"]
    ],

All fine when instances are started via

     resource "aws_instance" "some_instance" {}

But I can not use such method when instances are started via AutoScaling Group. How can I extract instance ids when instances launched via AutoScaling Group (and Launch Configuration) for future use in Terraform?

1
Generally you shouldn't need to do this. Instances in ASG can be replaced at anytime. If you create such dashboard now, dashboard will be useless once the instances get replaced due to AZ rebalance, scaling in/out activities and more. - Marcin

1 Answers

0
votes

First, you really shouldn't. ASGs change out instances and those IDs will change. Cloudwatch offers metrics for ASGs. So you can see metrics for instances made by the ASG. You can also create a resource group and have metrics by resource group.

But, if you really wanted to do this:

data "aws_instances" "test" {
  instance_tags = {
    SomeTag = "SomeValue"
  }

  instance_state_names = ["running", "stopped"]
}

output ids {
    value = data.aws_instances.test.ids
}

This will work if you put a tag in your launch config that is set on EC2s at launch.

This works because:

instance_tags - (Optional) A map of tags, each pair of which must exactly match a pair on desired instances