AWS - using (referencing) a VPC ARN from context X into a context Y

Hi,

So I have been studying Terraform this last few weeks and I got this question in my head:

Is it possible to make reference to an Resource from another completely separated context?

Example:

Assume that I have a small terraform module that define:

  • 1 VPC
  • 2 Subnets

and it also defines output variables as well:

  • x_vpc_arn
  • x_subnet_a
  • x_subnet_b

and the context is currently stored in an AWS Bucket named: tf-context-x

It’s all fine and dandy. VPC and Subnets were created properly.

But now I was to spin another resource: AWS AppRunner.

For that I will create a reusable terraform module that only “exposes” (requires) the Application Engineer to pass the AppRunner name and Container Image, because I want the Network aspect is the same to any app using it.

Since we are going to have a variable number of Applications using this base terraform module I would assume each of those Could (not sure about should) live in their on AWS Bucket (for context storage)

So our new Application named Foo could consume the terraform module and store at the bucket: tf-context-y-foo-app

Ok. So now the actual question:

While trying to “terraform apply” the App Foo can the (reusable) module make reference to tf-context-x/x_vpc_arn from context tf-context-y-foo?

Yes, you should use the build-in data “terraform_remote_state” in context Y to pull outputs (like VPC ARN) from context X’s state file.

Ensure you have a output block for VPC’s ARN x_vpc_arn in state X file.

In context Y, use terraform_remote_state to get the x_vpc_arn output from the state of context X.

Set the backend to point to the S3 bucket and key where context X keeps its tfstate.

Then, in your AppRunner module, just use the output as data.

Terraform_remote_state.vpc.outputs.x_vpc_arn. Also, make sure that the IAM role for context Y has permission to read from context X’s bucket. If it doesn’t, terraform apply will fail.