share facebook facebook facebook twitter twitter menu hatena pocket slack

2021.08.11 WED

TerraformでVPC Peering 実装

Shimpei Chiba

WRITTEN BY Shimpei Chiba

これは何

TerraformでVPC Peering 実装してみた。のメモです。

今回は、同一AWSアカウント間でのPeeringを行なっています。

早速やってみた

vpc.tf

resource "aws_vpc_peering_connection" "peer-1-2" {
  peer_owner_id = Your_AWS_Account_Id
  peer_vpc_id   = aws_vpc.peer-1.id
  vpc_id        = aws_vpc.peer-2.id
  auto_accept   = true

  tags = {
    Name = "VPC Peering between peer-1 and peer-2"
  }
}

resource "aws_vpc" "peer-1" {
  cidr_block = "10.1.0.0/16"
}

resource "aws_vpc" "peer-2" {
  cidr_block = "10.2.0.0/16"
}

resource "aws_route_table" "vpc-peer-1-route-table" {
  vpc_id = aws_vpc.peer-1.id

  route {
    cidr_block                = aws_vpc.peer-2.cidr_block
    vpc_peering_connection_id = aws_vpc_peering_connection.peer-1-2.id
  }

  tags = {
    Name = "vpc-peer-1-route-table"
  }
}


resource "aws_route_table" "vpc-peer-2-route-table" {
  vpc_id = aws_vpc.peer-2.id

  route {
    cidr_block                = aws_vpc.peer-1.cidr_block
    vpc_peering_connection_id = aws_vpc_peering_connection.peer-1-2.id
  }

  tags = {
    Name = "vpc-peer-2-route-table"
  }
}

各パラメータ解説

vpc.tf

resource "aws_vpc_peering_connection" "peer-1-2" {
  peer_owner_id = Your_AWS_Account_Id

    # アクセプターのVPC
    peer_vpc_id   = aws_vpc.peer-1.id

    # リクエスターのVPC
  vpc_id        = aws_vpc.peer-2.id

  # 同じAWSアカウント内でPeeringを行う場合、自動承認をするかどうか
  auto_accept   = true

  tags = {
    Name = "VPC Peering between peer-1 and peer-2"
  }
}

resource "aws_vpc" "peer-1" {
  cidr_block = "10.1.0.0/16"
}

resource "aws_vpc" "peer-2" {
  cidr_block = "10.2.0.0/16"
}

    # 各VPCにルートテーブルを定義して相互通信可能にする。
resource "aws_route_table" "vpc-peer-1-route-table" {
  vpc_id = aws_vpc.peer-1.id

  route {
    cidr_block                = aws_vpc.peer-2.cidr_block
    vpc_peering_connection_id = aws_vpc_peering_connection.peer-1-2.id
  }

  tags = {
    Name = "vpc-peer-1-route-table"
  }
}


resource "aws_route_table" "vpc-peer-2-route-table" {
  vpc_id = aws_vpc.peer-2.id

  route {
    cidr_block                = aws_vpc.peer-1.cidr_block
    vpc_peering_connection_id = aws_vpc_peering_connection.peer-1-2.id
  }

  tags = {
    Name = "vpc-peer-2-route-table"
  }
}

参考

https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/vpc_peering_connection
https://docs.aws.amazon.com/vpc/latest/peering/what-is-vpc-peering.html

元記事はこちら

https://qiita.com/namely_/items/505636b80aeba6c0ab83

cloudpack

cloudpackは、Amazon EC2やAmazon S3をはじめとするAWSの各種プロダクトを利用する際の、導入・設計から運用保守を含んだフルマネージドのサービスを提供し、バックアップや24時間365日の監視/障害対応、技術的な問い合わせに対するサポートなどを行っております。
AWS上のインフラ構築およびAWSを活用したシステム開発など、案件のご相談はcloudpack.jpよりご連絡ください。