带 Terraform 的 Cloudwatch 警报维度的条件属性

Conditional attribue for Dimensions of Cloudwatch Alarm with Terraform

嗨,我正在为 cloudwatch 警报创建一个可以被其他服务使用的通用模块。在这种情况下,尺寸必须是动态的,并且也必须接受没有尺寸的情况。如何使其成为条件属性,以便仅在值不为 null 时才执行。 我当前的代码如下。

resource "aws_cloudwatch_metric_alarm" "cloudwatch_metric_alarm" {
  alarm_name                = var.alarm_name
  comparison_operator       = var.comparison_operator
  evaluation_periods        = var.evaluation_periods
  alarm_description         = var.alarm_description
  insufficient_data_actions = var.insufficient_data_actions
  alarm_actions             = var.alarm_actions
  metric_name               = var.metric_name
  namespace                 = var.namespace
  period                    = var.period
  statistic                 = var.statistic
  threshold                 = var.threshold
  datapoints_to_alarm       = var.datapoints_to_alarm
  dimensions = {
    "${var.dimensions_name}" = "${var.dimensions_value}"
  }
  tags = var.tags
}

假设其他一切都正确,你可以使用null:

  dimensions = (var.dimensions_value != null ? {
    "${var.dimensions_name}" = "${var.dimensions_value}"
  } : null)