Accessing a file from outside .terraform

Hey there,

I’ve created a module that exists within a github repo. However, instead of passing all the variables within that module block I’m trying to do something in the form of the following within the variables.tf that exists within the module that’s initalized

# Variable for directory on where to find yaml files
  tfsettingsfile = "../../../environments/${terraform.workspace}.yaml"
  # Loads yaml file of workspace. If none found it just sets the contents to a default content
  tfsettingsfilecontent = "${fileexists(local.tfsettingsfile) ? file(local.tfsettingsfile) : "NoTFSettingsFileFound: true"}"
  # decodes the yaml file
  tfworkspacesettings = "${yamldecode(local.tfsettingsfilecontent)}"
  vars = "${merge(local.default, local.tfworkspacesettings)}"

The goal is that the module will be able to read all the values from the local yaml file and use that instead of passing the variables 1 by 1 Is this possible does anyone have insight on how to do this?

When I do the terraform init and apply. I Keep getting the NoTFSettingsFileFound

Hi @MPersaud38704,

When working with files that are distributed as part of the Terraform configuration, it’s best to use path.module so that you can be sure the rest of the path will be interpreted relative to the module, regardless of what is the current working directory when you run Terraform:

  tfsettingsfile = "${path.module}/../../../environments/${terraform.workspace}.yaml"

You’ll need to make sure the rest of the path makes sense as a relative path from the directory containing the module where this path.module expression appears.

To help debug this, it might help to temporarily remove the fallback to default content and let Terraform generate an error if the file doesn’t exist, because then the error message will tell you which filename Terraform was looking for. Once you have it working with a file that exists, then you can re-introduce the fileexists conditional to handle the situation where it doesn’t exist.

1 Like