Terraform v1.5.4 dynamic items failing on coalesce options

113 views Asked by At

I'm new to Terraform. I'm tying to utilize a local yaml file as data source for a dynamic list for a slew of redirects in Cloudflare. I can get it to work by not using the coalesce default option and having every entry in the yaml file include a value, in this case status_code. But, I only want to have to enter a status code if it differs from the 301 default. When I set the coalesce it gives me the error:

Error: Unsupported attribute This object does not have an attribute named "status_code".

I assume this is because it no longer sees the status_code value in my yaml file. Is there a way to do this?

Here is my main.tf:

locals {
  redirects = yamldecode(file("${path.module}/redirects.yaml"))
}

resource "cloudflare_list" "redirect_list" {
  account_id  = var.cloudflare_account_id
  name        = "redirect_list"
  description = "List of domains to redirect"
  kind        = "redirect"

  dynamic "item" {
    for_each = local.redirects

    content {
      value {
        redirect {
          source_url  = item.value.source_url
          target_url  = item.value.target_url
          status_code = coalesce(item.value.status_code, 301) # Set default to 301
        }
      }
    }
  }
}

And here is a sample from my redirects.yaml:

- source_url: "https://support.example.com"
  target_url: "https://example.com"

- source_url: "https://help.example.com"
  target_url: "https://example.com"

What I expect is for terraform, using the coalesce function, to look and see if the item.value.status_code exists and if it doesn't stick 301 in there. Like I said before, this does work if I put the status_code key in there, but I'm hoping I don't have to do that.

1

There are 1 answers

0
Marcin On BEST ANSWER

Use lookup instead:

status_code = lookup(item.value, "status_code", 301)