简体   繁体   中英

How to handle unsupported attribute in Terraform

I have a terraform code as given below

   locals {
    file_path = format("%s-%s", var.test1, var.test2)
    test_decode  =  yamldecode((data.github_repository_file.test.content))
   }
    data "github_repository_file" "test" {
     repository = "test-repo"
     branch     = "develop"
    file       = "${local.file_path}/local/test.yaml"
    }
  test_encode = ${yamlencode(local.test_decode.spec.names)}

This is working fine when a " .spec.names " attribute present in the test.yaml file. Since we are selecting the test.yaml based on local.file_path some times attribute.spec.names might not present in the test.yaml and the plan failing with "Error: Unsupported attribute" . How to check " .spec.names " attribute present in the test.yaml?

Updating the question to add yaml example

Yaml with names attribute

apiVersion: helm.toolkit.gitops.io/v2beta1
kind: HelmRelease
metadata:
  name: "test"
  namespace: "test-system"
spec:
  chart:
    spec:
      chart: "test-environment"
      version: "0.1.10"
  names:
    key1: "value1"
    key2: "value2"
    key3: "value3"
    key4: "value4"

YAML without names attribute

apiVersion: helm.toolkit.gitops.io/v2beta1
kind: HelmRelease
metadata:
  name: "test"
  namespace: "test-system"
spec:
  chart:
    spec:
      chart: "test-environment"
      version: "0.1.10"

You can use try :

  test_encode = yamlencode(try(local.test_decode.spec.names, "some_default_value"))

I don't know if a more elegant way exists, but you can check if a property exists like this:

contains([for k, v in local.test_decode : k], "spec")

chaining this to check if the spec and the names exists like this did not work for me as the second condition was still evaluated even if the first condition failed:

contains([for k, v in local.test_decode : k], "spec") && contains([for k, v in local.test_decode.spec : k], "names")

this does the trick, but I don't like it, because I consider it to be quite hacky:

contains([for k, v in local.test_decode : k], "spec") ? contains([for k, v in local.test_decode.spec : k], "names") : false

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM