Home > Back-end >  How to access files and variables from different directory in Terraform?
How to access files and variables from different directory in Terraform?

Time:06-17

We have the below directory structure on the Linux system.

 /root
   ├─dirA
   │  ├─main.tf
   │  ├─terraform.tfvars
   │  └─variables.tf
   └─dirB
      └─main.tf

==FIRST==

We used the below snippet in main.tf file of dirA to create a local kubeconfig file.

resource "local_file" "kubeconfig" {
  content  = module.gke_auth.kubeconfig_raw
  filename = "./kubeconfig"
}

Now we would like to access this kubeconfig file in the main.tf file of dirB inside the following snippet. Please suggest how to do that?

provider "kubernetes" {
  config_path    = "<PATH_TO_KUBECONFIG_FILE>"
}

==SECOND==

We have defined some variables inside the terraform.tfvars file of dirA and we would like to access those variables inside the main.tf file of dirB. Please suggest how to do this.

CodePudding user response:

We have solved both the issues with the setup below.

File dirA/main.tf contains something similar to

resource "local_file" "kubeconfig" {
  content  = module.gke_auth.kubeconfig_raw
  filename = "${path.module}/kubeconfig"
}

output "kubeconfig_file" {
  value = "${path.cwd}/kubeconfig"
}

File dirB/main.tf contains something similar to

data "terraform_remote_state" "kubeconfig_file" {
  backend = "local"

  config = {
    path = "${path.module}/../dirA/terraform.tfstate"
  }
}

provider "kubernetes" {
  config_path = "${data.terraform_remote_state.kubeconfig_file.outputs.kubeconfig_file}"
}

Finally:

cd dirA
terraform apply
cd ../dirB
terraform apply

Note: In a similar way we can access variables from the stack in the different directory

  • Related