Search code examples
amazon-web-servicesterraformdevopsinfrastructure-as-codeterragrunt

How do you read yaml environment variables in Terragrunt


I have an envrionment.yaml inside my repo as config for terragrunt, which looks like something like this:

sandpit:
  vpc_id: vpc-123456
  acc_id: "acc123456"

nonprod:
  vpc_id: vpc-78910
  acc_id: "acc78910"

now in my terragrunt files (terragrunt.hcl) I load/read this yaml and try to do this:

...

locals {
  function_name = "my fun"
  env_vars      = yamldecode(file("${find_in_parent_folders("environment.yaml")}"))
}

....

sg_description = "Security group for ${local.function_name} in ${get_env("TF_VAR_ENV_NAME")}"
vpc_id = "${local.env_vars.${get_env("TF_VAR_ENV_NAME")}.vpc_id}"
ingress = ....

Note that this input variable is coming from GitHub action, and the line starting with sg_description which created a string with this variable works fine. This ${get_env('TF_VAR_ENV_NAME')} is our env name (sandpit or nonprod).

However, the next line vpc_id = "${local.env_vars.${get_env('TF_VAR_ENV_NAME')}.vpc_id}" does not work. I have tested this post but couldn't help.

What I want to achieve is this:

vpc_id = "${local.env_vars.sandpit.vpc_id}"

So I can use relevant variables. (if I hardcord the above, the whole thing works)

The error from Action is this: enter image description here


Solution

  • I finally used this "${local.env_vars[get_env("TF_VAR_ENV_NAME")]["vpc_id"]}" and it worked. So in my example it would be:

    ...
    
    locals {
      function_name = "my fun"
      env_vars      = yamldecode(file("${find_in_parent_folders("environment.yaml")}"))
    }
    
    ....
    
    sg_description = "Security group for ${local.function_name} in ${get_env("TF_VAR_ENV_NAME")}"
    vpc_id = "${local.env_vars[get_env("TF_VAR_ENV_NAME")]["vpc_id"]}"
    ingress = ....
    

    Seams simple now I see it :)