dagda1
dagda1

Reputation: 28950

accessing variable in terragrunt that is in terraform.tfvars

I have this terraform.tfvars file in the following location:

root
|_prod
  |_eu-west-2
    |_dev
      |_terraform.tfvars
      |_cognito
        |_terragrunt.hcl

it has these values:

terragrunt = {
  terraform {
    extra_arguments "custom_vars" {
      commands = [
        "apply",
        "plan",
        "import",
        "push",
        "refresh"
      ]

      # With the get_tfvars_dir() function, you can use relative paths!
      arguments = [
        "-var-file=terraform.tfvars"
      ]
    }
  }
}

reply_to_email_address = "[email protected]"

I can't find in the docs how to access this. I've tried get_env:

include {
  path = find_in_parent_folders()
}

terraform {
  // double `//` before module are important!
  source = "../../../../../terraform-modules//cognito"
}

inputs = {
  name                    = "pvg-online-${local.env}"
  reply_to_email_address  = get_env("reply_to_email_address", "")
}

But it gets set to the default ""

Upvotes: 2

Views: 1893

Answers (1)

Ben Whaley
Ben Whaley

Reputation: 34456

This is actually such a common use case that terragrunt has built-in functionality for it.

In your terragrunt.hcl, include a terraform{} block like the following:

terraform {
  # Note that the double-slash (//) syntax is not needed for local relative paths
  source = "../../../../../terraform-modules/cognito"

  extra_arguments "common_var" {
    commands  = get_terraform_commands_that_need_vars()
    arguments = ["-var-file=${get_terragrunt_dir()}/../terraform.tfvars"]
  }
}

inputs = {
  name = "pvg-online-${local.env}"
  # Since reply_to_email_address is provided in the parent terraform.tfvars file,
  # it is not needed as an input
}

Note the use of get_terraform_commands_that_need_vars() so you can avoid listing out all the arguments, as well as get_terragrunt_dir() for finding the directory of terragrunt.hcl.

Upvotes: 6

Related Questions