Create multiple resources terraform

terraform

First time asking a question so if I've left anything important out let me know!

Terraform v0.11.1
provider.aws v0.1.4

I'm trying to create multiple cloudwatch alarms for multiple instances. I was wondering if there was a way to have the config iterating though a list. I have tried using the following code, but I get "Error: variable "instances": default may not contain interpolations".

variable "instances" {
  description = "Run the EC2 Instances in these Availability Zones"
  type = "list"
  default = ["${aws_instance.my_instance1.id}", "${aws_instance.my_instance2.id}", "${aws_instance.my_instance3.id}", "${aws_instance.my_instance4.id}", "${aws_instance.my_instance5.id}"]
}

############ Cloudwatch monitoring 
resource "aws_cloudwatch_metric_alarm" "cpu" {
  count                     = 5
  alarm_name                = "terraform-cpu-high-test"
  comparison_operator       = "GreaterThanOrEqualToThreshold"
  evaluation_periods        = "2"
  metric_name               = "CPUUtilization"
  namespace                 = "AWS/EC2"
  period                    = "180"
  statistic                 = "Average"
  threshold                 = "80"
  alarm_description         = "This metric monitors ec2 cpu utilization"
  insufficient_data_actions = []
  dimensions {
    InstanceId = "${element(var.instances, count.index)}"
  }
} 

Is something like this even possible with terraform and if so what's the best way to do it?

Thanks!

Best Answer

Your issue is

default = ["${aws_instance.my_instance1.id}", "${aws_instance.my_instance2.id}", "${aws_instance.my_instance3.id}", "${aws_instance.my_instance4.id}", "${aws_instance.my_instance5.id}"]

That either has to be passed in or set statically.

If my_instance1-5 are the same and can be set with a count in them like above. Then its better to do

InstanceId = "${element(aws_instance.my_instance.*.id, count.index)}"