当字符串包含 JSON 时,如何修改 Terraform 中的字符串文字?

问题描述 投票:0回答:1

我正在使用 Terraform 来管理一些 cloudwatch 警报,当 Terraform 销毁警报时,我希望它也删除对底层指标的异常检测。据我所知,我无法直接在 Terraform 中管理指标本身(请参阅 https://github.com/hashicorp/terraform-provider-aws/issues/18344)。

我正在使用本地执行配置程序块,我认为我的问题是我尝试运行的命令涉及一些 JSON。为了便于阅读,我还尝试在命令本身中留下一些换行符。我真的很困惑 Terraform 处理字符串文字的方式。我尝试过 EOT、EOF、使用变量,但我就是无法让它工作。

这是我试图让 Terraform 执行的命令(该命令在我的终端上运行)

    aws cloudwatch delete-anomaly-detector \
        --single-metric-anomaly-detector 
        '{
        "Namespace": "AWS/ApplicationELB",
        "AccountId": "redacted",
        "MetricName": "RequestCountPerTarget",
        "Dimensions": [
            {
                "Name": "TargetGroup",
                "Value": "redacted"
            }
        ],
        "Stat": "Average"
        }'

这是我的 Terraform 配置(为简洁起见,已截断)

resource "aws_cloudwatch_metric_alarm" "example" {
  alarm_name            = "example"
  #....
  #redacted for brevity
  #....
  provisioner "local-exec" {
    when = destroy
    command = format("aws cloudwatch delete-anomaly-detector --single-metric-anomoly-detector '%s'", jsonencode({
        Namespace   = "AWS\\ApplicationELB"
        AccountId   = "redacted"
        MetricName  = "RequestCountPerTarget"
        Dimensions  = [{
          Name  = "TargetGroup"
          Value = "redacted"
         }]
         Stat        = "Average"
       }
    ))
  }
}

当我运行

terraform apply
时,它确实执行了,但解释器未正确执行该命令。

module.example.aws_cloudwatch_metric_alarm.example[0] (local-exec): 执行: ["/bin/sh" "-c" "aws cloudwatch delete-anomaly- detector --single-metric-anomoly- detector '{"AccountId":"redacted","Dimensions":[{"Name":"TargetGroup","Value":"redacted"}],"MetricName":"RequestCountPerTarget","Namespace":"AWS\ApplicationELB ","Stat":"平均"}'"]

module.example.aws_cloudwatch_metric_alarm.example[0] (local-exec): 用法: aws [选项] [ ...] [参数] (local-exec): 用法: aws [选项] [ ...] [参数]

我还创建了一些要点,如果这样更容易阅读。

AWS 命令我正在尝试让 Terraform 运行

Terraform 配置(已截断)

amazon-web-services terraform terraform-provider-aws amazon-cloudwatch
1个回答
0
投票

<

resource "aws_cloudwatch_metric_alarm" "example" {
      alarm_name = "example"
      # Other configurations...
    
      provisioner "local-exec" {
        when    = destroy
        command = <<EOT
    aws cloudwatch delete-anomaly-detector --single-metric-anomaly-detector '{
      "Namespace": "AWS/ApplicationELB",
      "AccountId": "redacted",
      "MetricName": "RequestCountPerTarget",
      "Dimensions": [
        {
          "Name": "TargetGroup",
          "Value": "redacted"
        }
      ],
      "Stat": "Average"
    }'
    EOT
      }
    }

我还更新了命名空间以直接使用 AWS/ApplicationELB,无需使用双反斜杠 (\),因为双反斜杠可能会被误解。

© www.soinside.com 2019 - 2024. All rights reserved.