yamldecode in terraform for multiple list

Viewed 20

I am using the following yaml to get tag information for my outputs.tf.

yaml file:

---
common_tags:
   TAG:type: lab
   TAG:bu: crm
  
account_list: 
    friendly_name: 
        TAG:name: salesforce
        TAG:aws_regions: eu-central-1
    workload_accounts:
        TAG:account_name: some-sf-acc
        TAG:acc-no: 1234567890
        TAG:environment: development
    resource_tags:
      - vpc_name: mgmt
        TAG:name: mgmt-vpc
        TAG:owner: AutoScaling
        TAG:role: pipeline
        TAG:product: sf1
        TAG:app-id: app-id
      - vpc_name: app
        TAG:name: conftest
        TAG:owner: devops-cloud@test.com
        TAG:role: development
        TAG:product: sf2
        TAG:app-id: vcob
      - vpc_name: app
        TAG:name: app-vpc
        TAG:owner: devops-cloud@test.com
        TAG:role: automation
        TAG:product: sf3
        TAG:app-id: ser2
      - vpc_name: app
        TAG:name: conftest
        TAG:owner: devops-cloud@test.com
        TAG:role: build
        TAG:product: sf4
        TAG:app-id: entdb

My outputs.tf is as below:

output "product" {
    value = [yamldecode(file("resource/rnd/amc.yaml"))["account_list"]["resource_tags"][0]["TAG:product"]
}

output "bu" {
    value = yamldecode(file("resource/rnd/amc.yaml"))["common_tags"]["TAG:bu"]
}

output "acc-no" {
    value = yamldecode(file("resource/rnd/amc.yaml"))["account_list"]["workload_accounts"]["TAG:acc-no"]
}

output "role" {
    value = yamldecode(file("resource/rnd/amc.yaml"))["account_list"]["resource_tags"][0]["TAG:role"]
}

output "environment" {
    value = yamldecode(file("resource/rnd/amc.yaml"))["account_list"]["workload_accounts"]["TAG:environment"]
}

output "type" {
    value = yamldecode(file("resource/rnd/amc.yaml"))["common_tags"]["TAG:type"]
}

The plan gives this output:

Plan: 1 to add, 0 to change, 0 to destroy.

Changes to Outputs:

  • acc-no = 1234567890
  • bu = "crm"
  • environment = "development"
  • product = "sf1"
  • role = "pipeline"
  • type = "lab"

I want to display all the products and roles in my output as below.

Expected output:

Changes to Outputs:

  • acc-no = 1234567890
  • bu = "crm"
  • environment = "development"
  • product = "sf1","sf2","sf3"
  • role = "pipeline","development","automation","build"
  • type = "lab"

Please tell me how can I do it using yamldecode.

1 Answers

You have to use splat (i.e. *):

output "product" {
    value = yamldecode(file("resource/rnd/amc.yaml"))["account_list"]["resource_tags"][*]["TAG:product"]
}

output "role" {
    value = yamldecode(file("resource/rnd/amc.yaml"))["account_list"]["resource_tags"][*]["TAG:role"]
}
Related