Terraform - Define variables using terraform_remote_state

Let's say you have a directory for your Amazon Web Services (AWS) EC2 Instances and Virtual Private Clouds (VPC), perhaps something like this.

/usr/local/terraform/ec2
/usr/local/terraform/vpc

 

There will certainly be a situation where your Terraform EC2 main.tf file will need to get the ID of a Virtual Private Clouds (VPC), and vice versa. This is where terraform_remote_state comes into play.

Let's say /usr/local/terraform/vpc/terraform.tfstate contains the following.

{
  "version": 4,
  "terraform_version": "1.2.6",
  "serial": 90,
  "lineage": "10e7c02c-ce6a-0ace-c0d5-57a516c6d706",
  "outputs": {
    "vpc": {
      "value": "vpc-014d2fcfa335d3c01",
      "type": "string"
    }
  }
}

 

Here is what you could have in /usr/local/terraform/ec2/main.tf to get the ID of the Virtual Private Cloud (VPC) from the vpc/terraform.tfstate file.

data "terraform_remote_state" "aws-terraform-tfstate" {
  backend = "local"
  config = {
    path = "../vpc/terraform.tfstate"
  }
}

output "vpc" {
  value = data.terraform_remote_state.aws-terraform-tfstate.outputs.vpc
}

 

The terraform refresh command should output something like this.

vpc = "vpc-014d2fcfa335d3c01"

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee

Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.





Please enter 6cea9 in the box below so that we can be sure you are a human.




Comments

Web design by yours truely - me, myself, and I   |   jeremy.canfield@freekb.net   |