Terraform Cloud - How to Access State from a Different Workspace (Sharing output between workspaces )

Terraform Cloud - How to Access State from a Different Workspace (Sharing output between workspaces )
Ankit Tripathi
Terraform Cloud - How to Access State from a Different Workspace (Sharing output between workspaces )

Use Case : I have created two differentworkspaces for staging and production . Now I have create VPC peering betweenstaging and production VPC . These are in different workspaces and I need tohave the vpc id of the of staging VPC created in staging workspace in theproduction workspace for aws_vpc_peering_connection resource.

Solution : Terraform's built-in terraform_remote_state datasource lets you share arbitrary information between configurations via rootmodule outputs. The terraform_remote_state data source retrieves the rootmodule output values from some other Terraform configuration, using the lateststate snapshot from the remote backend.

in our case we terrformcloud was used to configure the remote backed . this is howterraform_remote_state data source was configured

data "terraform_remote_state" "test" {
   backend = "remote"
   config = {
     organization = "scaleworx"
     workspaces = {
     name = "test-eks-spot"

named the data source as testa and provided the information of the backedn configured in the staging workspace. (test-eks-spot is the staging workspace )

This data source is created in production workspace because we want the state information from staging workspace to be available in production workspace.

Now we have to ensure the outputs we want are defined in the root module. In our case the VPC module was being used and thus the output had to be defined in the root module like the following

output "staging-vpc-id" {
   value = module.staging-vpc.vpc-id

Note: vpc-id is the output defined in the vpc module

The terraform_remote_state data source exports the outputs from the remote state under an attribute called outputs.In our case the the vpc-id from the staging workspace can be obtained using the following attribute-


Thus the VPC Peering block in the production workspace goes like this -

resource "aws_vpc_peering_connection" "test-peering" {
 peer_vpc_id   = data.terraform_remote_state.test.outputs.staging-vpc-id
 vpc_id        = module.prod-vpc.vpc-id
 peer_region   = "us-east-1"

As the last step , we have to ensure that we have remote access controls modified so that the production workspace has access to the staging workspace for accessing the state . In this case test-eks-prod-peering is the name of the production work space which will be accessing the state of the test-eks-spot staging workspace . Thus in the test-eks-spot workspace we go to Setting->General and enable Remote State Sharing for test-eks-prod-peering work space.

Once done , plan and apply gives us the desired result and vpc-id from the staging workspace was dynamically accessible in the production workspace.

Back to blog