前提
- terraform v0.10.3
- tfstateファイルはS3に配置
同じtfstateファイルのリソースを参照する場合
- ディレクトリ構成
sample/
 ├ config.tf
 ├ subnet.tf
 └ vpc.tf
- tfstateファイルをS3で管理
sample/config.tf
terraform {
  backend "s3" {
    bucket = "[バケット名]"
    key = "sample/terraform.tfstate"
    region = "ap-northeast-1"
  }
}
- VPC作成
sample/vpc.tf
resource "aws_vpc" "main" {
  cidr_block       = "10.0.0.0/16"
  instance_tenancy = "dedicated"
  tags {
    Name = "main_vpc"
  }
}
- Subnet作成時、sample/subnet.tfからsample/vpc.tfで作成するVPCのIDを"${aws_vpc.main.id}"で参照できる
sample/subnet.tf
resource "aws_subnet" "1a" {
  vpc_id     = "${aws_vpc.main.id}"
  cidr_block = "10.0.1.0/24"
  tags {
    Name = "1a_subnet"
  }
}
異なるtfstateファイルのリソースを参照する場合
参照元のリソース情報をtfstateファイルにoutput
- ディレクトリ構成
sample/
 ├ config.tf
 ├ output.tf ←追加
 ├ subnet.tf
 └ vpc.tf
- 必要なリソース情報のoutputしておく
- ここでは作成したVPCのIDをvpc_idという名前でoutputしておく
 
- ここでは作成したVPCのIDを
sample/output.tf
output "vpc_id" {
  value = "${aws_vpc.main.id}"
}
- terraform applyしてtfstateファイルにoutputする
terraform apply
aws_vpc.main: Refreshing state... (ID: vpc-xxxxxxxx)
aws_subnet.1a: Refreshing state... (ID: subnet-xxxxxxx)
Apply complete! Resources: 0 added, 0 changed, 0 destroyed.
Outputs:
vpc_id = vpc-xxxxxxxx
- S3のtfstateファイル上ではこんな感じでoutputされる(outputs部分)
S3のterraform.tfstate
{
    "version": 3,
    "terraform_version": "0.10.3",
    "serial": 6,
    "lineage": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
    "modules": [
        {
            "path": [
                "root"
            ],
            "outputs": {
                "vpc_id": {
                    "sensitive": false,
                    "type": "string",
                    "value": "vpc-xxxxxxxx"
                }
            },
            "resources": {
                "aws_subnet.1a": {
...
tfstateファイルからoutputしたリソース情報を参照
- ディレクトリ構成(other/で作業)
sample/
 ├ other/ ←追加
 │ ├ config.tf ←追加
 │ ├ remote_state.tf ←追加
 │ └ subnet.tf ←追加
 ├ config.tf
 ├ subnet.tf
 └ vpc.tf
- sample/other/配下のtfstateファイルをS3で管理
sample/other/config.tf
terraform {
  backend "s3" {
    bucket = "[バケット名]"
    key = "sample/other/terraform.tfstate"
    region = "ap-northeast-1"
  }
}
- S3にあるtfstateファイルを取得する
sample/other/remote_state.tf
data "terraform_remote_state" "vpc" {
  backend = "s3"
  config {
    bucket = "[バケット名]"
    key    = "sample/terraform.tfstate"
    region = "ap-northeast-1"
  }
}
- tfstateファイルから、リソース情報を参照する
sample/other/subnet.tf
resource "aws_subnet" "1c" {
  vpc_id     = "${data.terraform_remote_state.vpc.vpc_id}"
  cidr_block = "10.0.2.0/24"
  tags {
    Name = "1c_subnet"
  }
}
- 
sample/output.tfで定義したvpc_idという変数名で参照することができる