Read locals from another folder

Hello,

I’m trying to find a way to read locals from another project in my directory.

I know that this is not natively supported, and tried something similar to this topic without success…

My directory looks like this :

  • Folder_AAA
    ---- AAA.tf
  • Folder_BBB
    ---- BBB.tf

Content of AAA.tf :

locals {
  AAA_test = "AAA"
}

resource "foo" "myresource" {
  # some code
}

module "mymodule" {
  # some code
}

I would like to read the value of local.AAA_test from my BBB.tf with something like this :

Content of BBB.tf :

locals {
  BBB_test = "BBB"
}

output "AAA_test" {
  value = local.AAA_test
}

output "BBB_test" {
  value = local.BBB_test
}

What would be the best and easiest way to do it ?

Thx for your help !

What are those two folders? Are they each separate root modules (ie there are two state files)? If so, you probably want to look at using the remote state data source.

Terraform does not support what you want to do.

The closest alternative I can think of, would be to move your common data to YAML and access it in both Terraform code directories using yamldecode(file("${path.module}/../mycommondata.yaml"))

Hi,

Thx for your answers/solutions, they both work !

Here are the config files for each method if anyone else needs it.


1st Method : terraform_remote_state

Directory structure :

  • Folder_AAA
    — AAA.tf
    — outputs.tf
  • Folder_BBB
    — BBB.tf

Folder_AAA/AAA.tf =

locals {
  mylocals = {
    AAA_test = "AAA"
    AAA2_test = "AAA2"
    AAA3_test = ["1.1.1.1", "8.8.8.8"]
  }
}

Folder_AAA/outputs.tf =

output "AAA_locals" {
  value = local.mylocals
}

Folder_BBB/BBB.tf =

data "terraform_remote_state" "AAA_Project" {
  backend = "local"

  config = {
    path = "../Folder_AAA/terraform.tfstate"
  }
}

output "AAA" {
  value = data.terraform_remote_state.AAA_Project.outputs.AAA_locals.AAA_test
}

2nd Method : yamldecode

Directory structure :

  • Folder_AAA
    — AAA.tf
  • Folder_BBB
    — BBB.tf
  • shared_locals.yml

shared_locals.yml =

AAA_test: "AAA"
AAA2_test: "AAA2"
AAA3_test:
   - "1.1.1.1"
   - "8.8.8.8"

Folder_BBB/BBB.tf =

locals {
  shared_locals = yamldecode(file("../shared_locals.yml"))
}

output "AAA" {
  value = local.shared_locals.AAA_test
}
1 Like