Home > database >  Terraform map from files in a directory
Terraform map from files in a directory

Time:10-11

guys!

My goal is to gather (merge) configs from YAML files into single Terraform map. E.g. I have the following 2 YAMLs:

  • config/file1.yml
    section1:
       property11: value11
       property12: value12
    
  • config/file2.yml
    section2:
       property21: value21
       property22: value22
    

What I need is the resulting config as follows (expressed as YAML below for readability, but of course it should be terraform map):

 section1:
   property11: value11
   property12: value12

 section2:
   property21: value21
   property22: value22

What I came up with at the moment is the following:

locals {
  config = { for yaml_file in fileset("${path.module}/config/", "*.yml"):
    yaml_file => file("${path.module}/config/${yaml_file}"
  }
}

But I am not sure with how to proceed further. Could you, please, point me in the right direction.

CodePudding user response:

You can use the merge function to combine the yaml maps into a single terraform map.

locals {
  base_path     = "${path.module}/config"
  files         = fileset(local.base_path, "*.yml")
  file_content  = [for f in local.files : yamldecode(file("${local.base_path}/${f}"))]
  terraform_map = merge(local.file_content...)
  yaml_output   = yamlencode(local.terraform_map)
}

output "result" {
  value = local.file_content
}
  • Related