Home > Net >  How to handle unsupported attribute in Terraform
How to handle unsupported attribute in Terraform

Time:01-18

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"

CodePudding user response:

You can use try:

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

CodePudding user response:

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
  • Related