How to declare undeclared local value in

Could someone prompt me, please? How I can declare environment?

Error: Reference to undeclared local value

on 00-init.tf line 11, in data “terraform_remote_state” “state_iam_policy_admin”:
11: key = “${local.environment}/us-west-2/01-pre-setup/iam-policy-admin/terraform.tfstate”

A local value with the name “environment” has not been declared.

terragrunt.hcl

locals {
  environment_vars = read_terragrunt_config(find_in_parent_folders("env.hcl"))
  environment = local.environment_vars.locals.environment
}

include {
  path = find_in_parent_folders()
}

00-init.tf

data "terraform_remote_state" "state_iam_policy_admin" {
  backend = "s3"
  config = {
    region = "us-west-2"
    bucket = "terragrunt-terraform-state-stage-us-west-2/"
    key = "${local.environment}/us-west-2/01-pre-setup/iam-policy-admin/terraform.tfstate"
  }
}

env.hcl
locals {
environment = “stage”
}
.
├── stage
│ ├── account.hcl
│ ├── env.hcl
│ └── us-west-2
│ ├── 01-pre-setup
│ │ └── iam-users-admin
│ │ ├── 00-init.tf
│ │ ├── 01-main.tf
│ │ ├── 99-outputs.tf
│ │ ├── backend.tf
│ │ ├── provider.tf
│ │ ├── README.md
│ │ ├── terragrunt.hcl
│ │ ├── variables.tf
│ │ └── versions.tf
│ └── region.hcl
└── terragrunt.hcl

Hi @rmalenko,

This is similar to the issue in Problems with getting inputs from dependent module outputs - is it a syntax problem? Typing?, and the solution should be the same.

You want to expose environment as a variable in 00-init.tf, and then use inputs in terragrunt.hcl to set it for terraform:

terragrunt.hcl

locals {
  environment_vars = read_terragrunt_config(find_in_parent_folders("env.hcl"))
}

include {
  path = find_in_parent_folders()
}

inputs = {
  environment = local.environment_vars.locals.environment
}

00-init.tf

variable "environment" {
  type = string
  # This is passed in from terragrunt inputs attribute
}

data "terraform_remote_state" "state_iam_policy_admin" {
  backend = "s3"
  config = {
    region = "us-west-2"
    bucket = "terragrunt-terraform-state-stage-us-west-2/"
    key = "${var.environment}/us-west-2/01-pre-setup/iam-policy-admin/terraform.tfstate"
  }
}

Best regards,
Yori

1 Like

Thank you @yoriy

You have clarified me and I go to get for another Terragrunt challenge :slight_smile:

Best wishes,
Rostyslav