🗂
TerraformでSite-to-Site VPNの設定を行う
やること
Site-to-Site VPN
を使って手軽にオンプレとAWSをVPN接続します。
実装
事前準備
VPCの作成
vpc.tf
# VPC
resource "aws_vpc" "this" {
cidr_block = var.vpc_cidr_block
enable_dns_support = true
enable_dns_hostnames = true
tags = {
Name = "${var.env}-vpc"
}
}
# Private subnet
resource "aws_subnet" "private_app_1a" {
vpc_id = aws_vpc.this.id
cidr_block = var.private_app_subnets[0]
map_public_ip_on_launch = false
availability_zone = var.azs[0]
tags = {
Name = "${var.env}-subnet-private-app-1a"
}
}
resource "aws_subnet" "private_app_1c" {
vpc_id = aws_vpc.this.id
cidr_block = var.private_app_subnets[1]
map_public_ip_on_launch = false
availability_zone = var.azs[1]
tags = {
Name = "${var.env}-subnet-private-app-1c"
}
}
# Route table for private subnets
resource "aws_route_table" "private" {
vpc_id = aws_vpc.this.id
tags = {
Name = "${var.env}-route-table-private"
}
}
resource "aws_route_table_association" "private_1a" {
subnet_id = aws_subnet.private_app_1a.id
route_table_id = aws_route_table.private.id
}
resource "aws_route_table_association" "private_1c" {
subnet_id = aws_subnet.private_app_1c.id
route_table_id = aws_route_table.private.id
}
variables.tf
variable "vpc_cidr_block" {
type = string
default = "10.0.0.0/16"
}
variable "azs" {
type = list(string)
default = ["ap-northeast-1a", "ap-northeast-1c"]
}
variable "private_app_subnets" {
type = list(string)
default = ["10.0.8.0/24", "10.0.9.0/24"]
}
オンプレ側のグローバルIPアドレス、およびCIDRの設定
variables.tf
variable "onpre_ip_address" {
type = string
default = "input on-premise global ip address here"
}
variable "local_ipv4_network_cidr" {
type = string
default = "input on-premise cidr here"
}
Site-to-Site VPN
vpn.tf
# Virtual private gateway
resource "aws_vpn_gateway" "vgw" {
tags = {
Name = "${var.env}-vgw"
}
}
resource "aws_vpn_gateway_attachment" "vpn_attachment" {
vpc_id = aws_vpc.this.id
vpn_gateway_id = aws_vpn_gateway.vgw.id
}
# Propagation of route table (private)
resource "aws_vpn_gateway_route_propagation" "vgw_propagate_private" {
vpn_gateway_id = aws_vpn_gateway.vgw.id
route_table_id = aws_route_table.private.id
}
# Customer gateway
resource "aws_customer_gateway" "cgw" {
bgp_asn = 65000 # default
ip_address = var.onpre_ip_address
type = "ipsec.1"
tags = {
Name = "${var.env}-cgw"
}
}
# Site-to-site connection
resource "aws_vpn_connection" "vpnc" {
vpn_gateway_id = aws_vpn_gateway.vgw.id
customer_gateway_id = aws_customer_gateway.cgw.id
type = "ipsec.1"
local_ipv4_network_cidr = var.local_ipv4_network_cidr
remote_ipv4_network_cidr = aws_vpc.this.cidr_block
tags = {
Name = "${var.env}-vpn-connection"
}
}
オンプレ側の設定
コンソールにて、[VPC]>[サイト間のVPN接続]>[ファイルのダウンロード] より、対象ルータの設定ファイルをダウンロードしオンプレ側のルータ設定する。
参考
Discussion