3-commerce
3-commerce

Reputation: 159

Terraform empty and non-empty block map variables

I want to make backend-service by using Terraform. I use resource_type google_compute_backend_service

Now, i have 2 backend-services created by gcloud command. The one is using cdn_policy block and another one doesn't use cdn_policy.

The first backend-services tfstate is like

...
"cdn_policy": [
  {
    "cache_key_policy": [],
    "signed_url_cache_max_age_sec": 3600
  }
]
...

And the second backend-services is like

"cdn_policy": []

How to create the terraform script works for both of them ? So, terraform script can run for backend-services who has cdn_policy include with its block map and can also run for backend-services without cdn_policy.

In my idea, i can create 2 terraform scripts. First for cdn_policy and second without cdn_policy. But, i think this is not best practice.

If i put cdn_policy = [], it would result error An argument named "cdn_policy" is not expected here

Upvotes: 0

Views: 4266

Answers (1)

mariux
mariux

Reputation: 3127

You can use dynamic blocks to create a set of blocks based on a list of objects in an input variable: Dynamic Blocks

resource "google_compute_backend_service" "service" {

  ...

  dynamic "cdn_policy" {
    for_each = var.cdn_policy

    content {
      cache_key_policy             = cdn_policy.value.cache_key_policy
      signed_url_cache_max_age_sec = cdn_policy.value.signed_url_cache_max_age_sec
    }
  }
}

Upvotes: 2

Related Questions