今回はVPCを2つ作って、サブネット、ルートテーブル、ピアリングまで実施する。
グローバルIPを使ってしまっているが、サンプルということで…
## 1つ目のVPCの設定とIGW
resource "aws_vpc" "vpc01" {
cidr_block = "192.165.0.0/16"
tags = {
Name = "vpc01"
}
}
resource "aws_subnet" "subnet-vpc01-public" {
vpc_id = aws_vpc.vpc01.id
cidr_block = "192.165.0.0/24"
availability_zone = "ap-northeast-1a"
tags = {
Name = "subnet-vpc01-public"
}
}
resource "aws_internet_gateway" "igw-vpc01" {
vpc_id = aws_vpc.vpc01.id
tags = {
Name = "igw-vpc01"
}
}
## 2つ目のVPCの設定とIGW
resource "aws_vpc" "vpc02" {
cidr_block = "192.164.0.0/16"
tags = {
Name = "vpc02"
}
}
resource "aws_subnet" "subnet-vpc02-public" {
vpc_id = aws_vpc.vpc02.id
cidr_block = "192.164.0.0/24"
availability_zone = "ap-northeast-1a"
tags = {
Name = "subnet-vpc02-public"
}
}
resource "aws_internet_gateway" "igw-vpc02" {
vpc_id = aws_vpc.vpc02.id
tags = {
Name = "igw-vpc02"
}
}
## peering settings
resource "aws_vpc_peering_connection" "peer-vpc02" {
peer_vpc_id = "${aws_vpc.vpc01.id}"
vpc_id = "${aws_vpc.vpc02.id}"
tags = {
Name = "VPC Peering between vpc01 and vpc02"
}
auto_accept = true
}
## route table
## ルートテーブルの紐付けを行う
resource "aws_route_table_association" "rtb-a-vpc01-public" {
subnet_id = aws_subnet.subnet-vpc01-public.id
route_table_id = aws_route_table.rtb-vpc01.id
}
resource "aws_route_table_association" "rtb-a-vpc02-public" {
subnet_id = aws_subnet.subnet-vpc02-public.id
route_table_id = aws_route_table.rtb-vpc02.id
}
# vpc01からvpc02に向かう設定を入れるルートテーブル
resource "aws_route_table" "rtb-vpc01" {
vpc_id = "${aws_vpc.vpc01.id}"
route {
cidr_block = "0.0.0.0/0"
gateway_id = aws_internet_gateway.igw-vpc01.id
}
route {
cidr_block = "192.164.0.0/16"
vpc_peering_connection_id = "${aws_vpc_peering_connection.peer-vpc02.id}"
}
tags = {
Name = "rtb-vpc01"
}
}
# vpc02からvpc01に向かう設定を入れたルートテーブル
resource "aws_route_table" "rtb-vpc02" {
vpc_id = "${aws_vpc.vpc02.id}"
route {
cidr_block = "0.0.0.0/0"
gateway_id = aws_internet_gateway.igw-vpc02.id
}
route {
cidr_block = "192.165.0.0/16"
vpc_peering_connection_id = "${aws_vpc_peering_connection.peer-vpc02.id}"
}
tags = {
Name = "rtb-vpc02"
}
}
terraformでsubnet作ると、private、publicを意識せず作ってしまい全て外にアクセスできないprivateサブネットになってしまうので、 パブリックサブネットを作るならインターネットゲートウェイを明示的に作成、紐付けし、ルーティングテーブルも作成してやる必要がある。