How to use dynamic block for resource argument

i want to specify data for argument ‘data’ with dynamic block. Is it possible? why this code doesn’t work? i receive Error: “Missing required argument. The argument “data” is required, but no definition was found”. I have variables.tf file with all necessary variables.

resource "aws_prometheus_rule_group_namespace" "alert-rules" {
  name         = var.prometheus_rule_group

  dynamic "data" {
    for_each = var.alert-rules
    content {
      data = <<EOF
groups:
  - name: alerts
    rules:
    - alert: data.value["alert-name"]
      expr: data.value["expr"]
      for: data.value["period"]
      labels:
        severity: data.value["severity"]
      annotations:
        summary: data.value["summary"]
EOF
    }
  }
}

data is a single argument for that resource. You can’t use a dynamic block for that (it would create multiple data blocks inside the resource definition)

You have to pass the data argument as a single string or variable in this case.

Check out the documentation.

You can use the yamlencode function though, once you’ve built the terraform object with the values you need.

1 Like