Good morning all, I am using terraform to manage ...
# terraform
d
Good morning all, I am using terraform to manage some cloudwatch alarms, and when TF destroys the alarms I want it to also delete the anomaly detection on the underlying metrics. As far as I can tell, I cannot manage the metrics themselves directly in terraform (see https://github.com/hashicorp/terraform-provider-aws/issues/18344). I am using a local-exec provisioner block and I think my problem is the command I'm trying to run involves some json. I was also trying to leave some newlines in the command itself for readability sake. I am really struggling with the way TF handles string literals. I've tried EOT, EOF, using a variable but I just can't get it to work. Here's the command I'm trying to get TF to execute (this command works from my terminal)
Copy code
aws cloudwatch delete-anomaly-detector \
    --single-metric-anomaly-detector 
    '{
    "Namespace": "AWS/ApplicationELB",
    "AccountId": "redacted",
    "MetricName": "RequestCountPerTarget",
    "Dimensions": [
        {
            "Name": "TargetGroup",
            "Value": "redacted"
        }
    ],
    "Stat": "Average"
    }'
Here's my TF configuration (truncated for brevity
Copy code
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"
    }
    ))
  }
}
I also created some gists if that's easier to read. AWS command I'm trying to get TF to run Terraform config (truncated)
t
I HATE HATE HATE trying to get code to work in hcl for many of the reasons you're coming to understand. Instead I much rather prefer to use a null resource call a literal script file. See this example in stack over flow https://stackoverflow.com/questions/73317112/how-to-execute-a-bash-script-from-null-resource-terraform-azure
Keep in mind that you can script it in such a way that it takes arguments, or you can use terraform's file template function to actually build the script itself
d
Ok, that's good to know. Does that mean I can't use a local provisioner? I actually have the null_resource pattern working elsewhere in my codebase, but I liked the local provisioner option because it felt more tidy.
t
Yes you can. It should use the same api as the null resource IIRC
just make your command call the file
doing it as a separate bash script or whatever makes it SO MUCH EASIER to debug
d
Ok, thank you!