Using terraform_remote_state for getting data from another terraform state

2 min read

On terraform, besides returning some information to the user, returning data as output can be used as an input for terraform code that needs to use a resource created by another team.

On the terraform code that creates the resource, we will have to set the variable and it's value:

output endpoint {
    vpc_id = aws_vpc.databases.id
}

Then, on the code that uses this resource we will have to declare the tfstate as a data source using terraform_remote_state

Assuming the terraform state resides on an S3 bucket we would have to define it as follows:

data "terraform_remote_state" "network" {
  backend = "s3"

  config = {
    bucket = var.terraform_remote_state_s3_bucket
    key    = var.terraform_remote_state_s3_network_tfstate
    region = "eu-west-1"
  }
}

Once it is defined we will be able to use it as any other resource:

module "demo-service" {
(...)
  vpc_id = data.terraform_remote_state.network.outputs.vpc_id
}

Posted on 11/03/2021