Akhil K
Akhil K

Reputation: 31

Adding different threshold values to in different instances using terraform

I am trying to add different threshold values to different instances ids in tf. But i am not able to find if loop in terraform.

Is there any way to give different threshold values to those instances within an same block? LIKE for instance a threshold=100. instance b threshold=150, instancecthreshold=200.

Here is my snippet.

variable "instances" {
    default = ["instancea", "instanceb","instancec","instanced"]
}

    resource "aws_cloudwatch_metric_alarm" "cpu_credits" {
         count = "${length(var.instances)}"
   ## alarm names must be unique in an AWS account
         alarm_name = "test-${count.index} - Low CPU Credits
      comparison_operator = "LessThanOrEqualToThreshold"
      #dimensions { InstanceId = "${var.instID}" }
      dimensions { InstanceId = "${element(var.instances, count.index)}"
      evaluation_periods = "10"
      metric_name = "CPUCreditBalance"
      namespace = "AWS/EC2"
      period = "120"
      statistic = "Average"
      threshold = "200"
      alarm_description = "This metric monitors low ec2 cpu credits for T2 instances"
      insufficient_data_actions = []
      alarm_actions = []
} 

Upvotes: 0

Views: 314

Answers (1)

Ervin Szilagyi
Ervin Szilagyi

Reputation: 16775

You may want to use for_each instead of count.

# We create a list of tuples to store the instance id mapped to a threshold
variable "instances" {
  default = [
    {
      name      = "instancea",
      threshold = 100
    },
    { name      = "instancea=b",
      threshold = 150
    },
    {
      name      = "instancec",
      threshold = 200
    },
    {
      name      = "instanced",
      threshold = 100
    },
  ]
}

resource "aws_cloudwatch_metric_alarm" "cpu_credits" {
  # Iterate through the list. The inner for is used to maintain the index required for your alarm_name. Probably you could use instanceId instead an index there
  for_each = { for index, value in var.instances: index => value}
  ## alarm names must be unique in an AWS account
  alarm_name          = "test-${each.key} - Low CPU Credits"
  comparison_operator = "LessThanOrEqualToThreshold"
  dimensions = {
    InstanceId = each.value.name
  }
  evaluation_periods        = "10"
  metric_name               = "CPUCreditBalance"
  namespace                 = "AWS/EC2"
  period                    = "120"
  statistic                 = "Average"
  threshold                 = each.value.threshold
  alarm_description         = "This metric monitors low ec2 cpu credits for T2 instances"
  insufficient_data_actions = []
  alarm_actions             = []
}  

Upvotes: 1

Related Questions