简体   繁体   中英

Reference variables from another Terraform plan

I have created a set-up with main and disaster recovery website architecture in AWS using Terraform.

The main website is in region1 and disaster recovery is in region2. This script is created as different plans or different directories.

For region1, I created one directory which contains only the main website Terraform script to launch the main website infrastructure.

For region2, I created another directory which contains only the disaster recovery website Terraform script to launch the disaster recovery website infrastructure.

In my main website script, I need some values of the disaster recovery website such as VPC peering connection ID, DMS endpoint ARNs etc.

How can I reference these variables from the disaster recovery website directory to the main website directory?

One option is to use the terraform_remote_state data source to fetch outputs from the other state file like this:

vpc/main.tf

resource "aws_vpc" "foo" {
  cidr_block = "10.0.0.0/16"
}

output "vpc_id" {
  value = "${aws_vpc.foo.id}"
}

route/main.tf

data "terraform_remote_state" "vpc" {
  backend = "s3"
  config {
    bucket = "mybucket"
    key    = "path/to/my/key"
    region = "us-east-1"
  }
}

resource "aws_route_table" "rt" {
  vpc_id = "${data.terraform_remote_state.vpc.vpc_id}"
}

However, it's nearly always better to just use the native data sources of the provider as long as they exist for the resource you need.

So in your case you will need to use data sources such as the aws_vpc_peering_connection data source to be able to establish cross VPC routing with something like this:

data "aws_vpc_peering_connection" "pc" {
  vpc_id          = "${data.aws_vpc.foo.id}"
  peer_cidr_block = "10.0.0.0/16"
}

resource "aws_route_table" "rt" {
  vpc_id = "${aws_vpc.foo.id}"
}

resource "aws_route" "r" {
  route_table_id            = "${aws_route_table.rt.id}"
  destination_cidr_block    = "${data.aws_vpc_peering_connection.pc.peer_cidr_block}"
  vpc_peering_connection_id = "${data.aws_vpc_peering_connection.pc.id}"
}

You'll need to do similar things for any other IDs or things you need to reference in your DR region.

It's worth noting that there's not any data sources for the DMS resources so you would either need to use the terraform_remote_state data source to fetch any IDs (such as the source and target endpoint ARNs to setup the aws_dms_replication_task or you could structure things so that all of the DMS stuff happens in the DR region and then you only need to refer to the other region's VPC ID , database names and potentially KMS key IDs which can all be done via data sources.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM