在使用terraform的不同实例中添加不同的阈值



我试图在tf中为不同的实例id添加不同的阈值。但是我无法在terraform中找到if循环。

是否有任何方法可以为同一块内的这些实例提供不同的阈值?例如,一个阈值=100。实例b threshold=150, instancecthreshold=200.

这是我的片段。

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 = []
} 

您可能需要使用for_each而不是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             = []
}  

最新更新