Search code examples
terraformcloudflare

Attributes as Blocks with dynamic key and value in Terraform


I would like to create Terraform module for Cloudflare and I stuck with cloudflare_zone_settings_override settings block. I am unable to create it dynamically based on input variable containing map.

Goal is to have input variable settings_override which is gonna have variable number of settings inside. Example:

  settings_override = {
    always_use_https = "on"
    ssl              = "flexible"
  }

What I would like to achieve is something like this, where I can have variable number of settings on input (it is module, so it can be variable per environment) .

resource "cloudflare_zone_settings_override" "this" {
  zone_id   = cloudflare_zone.this.id
  for_each  = var.settings_override

  settings {
    always_use_https = "on"
    ssl              = "flexible"
  }
}

however I am always receiving the same error:

Error: Argument or block definition required

  on main.tf line 72, in resource "cloudflare_zone_settings_override" "this":
  72:     each.key = each.value

An argument or block definition is required here. To set an argument, use
the equals sign "=" to introduce the argument value.

Not working code. I have also tried way with dynamic, however settings block can be only one so I do not think that's the right way to do it...

variable "settings_override" {
  description = "Override Cloudflare configuration"
  type        = map(string)
  default     = {}
}

resource "cloudflare_zone_settings_override" "this" {
  zone_id   = cloudflare_zone.this.id
  for_each  = var.settings_override

  settings {
    each.key = each.value
  }
}

Is this even possible using Terraform? Or I have to specify all possible options and replace them using for_each?

Terraform version v1.0.6
Cloudflare provider version: 2.10.1


Solution

  • You would have to explicitly provide all options. For example:

    resource "cloudflare_zone_settings_override" "this" {
      zone_id   = cloudflare_zone.this.id
    
      settings {
        always_use_https = lookup(var.settings_override, "always_use_https", null)
        ssl = lookup(var.settings_override, "ssl", null)
        mirage = lookup(var.settings_override, "mirage", null)
        # ... and so on
      }
    }