LESSON 40分

ネットワークのIaC化

ストーリー

「ネットワークはインフラの土台だ。 VPC、サブネット、ルーティング、ゲートウェイ...... これらを全てコードで管理できれば、 どんな環境でも同じネットワーク構成を一瞬で再現できる」

木村先輩がネットワーク構成図を描いた。

「先月AWSコンソールで構築したVPCと同じ構成を、 今度はTerraformで作ってみよう」


VPCネットワーク全体像

Terraform で構築するネットワーク

                  Internet
                    │
              ┌─────┴─────┐
              │ Internet   │
              │ Gateway    │
              └─────┬─────┘
                    │
    ┌───────── VPC (10.0.0.0/16) ─────────┐
    │               │                       │
    │  ┌──── Public Subnets ────┐          │
    │  │  10.0.1.0/24 (AZ-a)    │          │
    │  │  10.0.2.0/24 (AZ-c)    │          │
    │  └────────────────────────┘          │
    │               │                       │
    │         ┌─────┴─────┐                │
    │         │ NAT        │                │
    │         │ Gateway    │                │
    │         └─────┬─────┘                │
    │               │                       │
    │  ┌──── Private Subnets ───┐          │
    │  │  10.0.101.0/24 (AZ-a)  │          │
    │  │  10.0.102.0/24 (AZ-c)  │          │
    │  └────────────────────────┘          │
    │                                       │
    └───────────────────────────────────────┘

VPCモジュールの実装

VPC本体

hcl
# modules/vpc/main.tf

# VPC
resource "aws_vpc" "this" {
  cidr_block           = var.cidr_block
  enable_dns_hostnames = true
  enable_dns_support   = true

  tags = {
    Name = var.name
  }
}

# Internet Gateway
resource "aws_internet_gateway" "this" {
  vpc_id = aws_vpc.this.id

  tags = {
    Name = "${var.name}-igw"
  }
}

パブリックサブネット

hcl
# Availability Zones
data "aws_availability_zones" "available" {
  state = "available"
}

# Public Subnets
resource "aws_subnet" "public" {
  count = length(var.public_subnets)

  vpc_id                  = aws_vpc.this.id
  cidr_block              = var.public_subnets[count.index]
  availability_zone       = data.aws_availability_zones.available.names[count.index]
  map_public_ip_on_launch = true

  tags = {
    Name = "${var.name}-public-${count.index + 1}"
    Tier = "public"
  }
}

# Public Route Table
resource "aws_route_table" "public" {
  vpc_id = aws_vpc.this.id

  route {
    cidr_block = "0.0.0.0/0"
    gateway_id = aws_internet_gateway.this.id
  }

  tags = {
    Name = "${var.name}-public-rt"
  }
}

# Public Route Table Association
resource "aws_route_table_association" "public" {
  count = length(var.public_subnets)

  subnet_id      = aws_subnet.public[count.index].id
  route_table_id = aws_route_table.public.id
}

プライベートサブネット

hcl
# Elastic IP for NAT Gateway
resource "aws_eip" "nat" {
  count  = var.enable_nat_gateway ? 1 : 0
  domain = "vpc"

  tags = {
    Name = "${var.name}-nat-eip"
  }
}

# NAT Gateway
resource "aws_nat_gateway" "this" {
  count = var.enable_nat_gateway ? 1 : 0

  allocation_id = aws_eip.nat[0].id
  subnet_id     = aws_subnet.public[0].id

  tags = {
    Name = "${var.name}-nat"
  }

  depends_on = [aws_internet_gateway.this]
}

# Private Subnets
resource "aws_subnet" "private" {
  count = length(var.private_subnets)

  vpc_id            = aws_vpc.this.id
  cidr_block        = var.private_subnets[count.index]
  availability_zone = data.aws_availability_zones.available.names[count.index]

  tags = {
    Name = "${var.name}-private-${count.index + 1}"
    Tier = "private"
  }
}

# Private Route Table
resource "aws_route_table" "private" {
  vpc_id = aws_vpc.this.id

  dynamic "route" {
    for_each = var.enable_nat_gateway ? [1] : []
    content {
      cidr_block     = "0.0.0.0/0"
      nat_gateway_id = aws_nat_gateway.this[0].id
    }
  }

  tags = {
    Name = "${var.name}-private-rt"
  }
}

# Private Route Table Association
resource "aws_route_table_association" "private" {
  count = length(var.private_subnets)

  subnet_id      = aws_subnet.private[count.index].id
  route_table_id = aws_route_table.private.id
}

セキュリティグループ

hcl
# Web Server Security Group
resource "aws_security_group" "web" {
  name        = "${var.name}-web-sg"
  description = "Security group for web servers"
  vpc_id      = aws_vpc.this.id

  ingress {
    description = "HTTP from anywhere"
    from_port   = 80
    to_port     = 80
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }

  ingress {
    description = "HTTPS from anywhere"
    from_port   = 443
    to_port     = 443
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }

  egress {
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }

  tags = {
    Name = "${var.name}-web-sg"
  }
}

# Database Security Group
resource "aws_security_group" "db" {
  name        = "${var.name}-db-sg"
  description = "Security group for database"
  vpc_id      = aws_vpc.this.id

  ingress {
    description     = "MySQL from web servers"
    from_port       = 3306
    to_port         = 3306
    protocol        = "tcp"
    security_groups = [aws_security_group.web.id]
  }

  egress {
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }

  tags = {
    Name = "${var.name}-db-sg"
  }
}

モジュールの変数と出力

hcl
# modules/vpc/variables.tf
variable "name" {
  description = "VPC名"
  type        = string
}

variable "cidr_block" {
  description = "VPC CIDR block"
  type        = string
  default     = "10.0.0.0/16"
}

variable "public_subnets" {
  description = "パブリックサブネットのCIDRリスト"
  type        = list(string)
  default     = ["10.0.1.0/24", "10.0.2.0/24"]
}

variable "private_subnets" {
  description = "プライベートサブネットのCIDRリスト"
  type        = list(string)
  default     = ["10.0.101.0/24", "10.0.102.0/24"]
}

variable "enable_nat_gateway" {
  description = "NATゲートウェイを作成するか"
  type        = bool
  default     = true
}
hcl
# modules/vpc/outputs.tf
output "vpc_id" {
  value = aws_vpc.this.id
}

output "public_subnet_ids" {
  value = aws_subnet.public[*].id
}

output "private_subnet_ids" {
  value = aws_subnet.private[*].id
}

output "web_security_group_id" {
  value = aws_security_group.web.id
}

output "db_security_group_id" {
  value = aws_security_group.db.id
}

環境ごとのネットワーク設計

設定項目stagingproduction
VPC CIDR10.0.0.0/1610.1.0.0/16
パブリックサブネット2つ3つ
プライベートサブネット2つ3つ
NAT Gateway1つ(コスト削減)AZごとに1つ
セキュリティグループ開発者IPからSSH許可SSH不可(SSM経由のみ)
hcl
# environments/staging/terraform.tfvars
environment         = "staging"
vpc_cidr            = "10.0.0.0/16"
public_subnet_cidrs = ["10.0.1.0/24", "10.0.2.0/24"]
private_subnet_cidrs = ["10.0.101.0/24", "10.0.102.0/24"]
enable_nat_gateway  = true
hcl
# environments/production/terraform.tfvars
environment         = "production"
vpc_cidr            = "10.1.0.0/16"
public_subnet_cidrs = ["10.1.1.0/24", "10.1.2.0/24", "10.1.3.0/24"]
private_subnet_cidrs = ["10.1.101.0/24", "10.1.102.0/24", "10.1.103.0/24"]
enable_nat_gateway  = true

まとめ

ポイント内容
VPCモジュールVPC + IGW + サブネット + ルートテーブルをパッケージ化
NAT Gatewayプライベートサブネットのインターネットアクセス
セキュリティグループWeb層とDB層で分離、最小権限
環境分離tfvars で環境ごとの設定を管理

チェックリスト

  • VPC全体をTerraformで構築するコードを書ける
  • パブリック/プライベートサブネットの設定を理解した
  • セキュリティグループの階層的な設計をコード化できる
  • 環境ごとのネットワーク差異をtfvarsで管理できる

次のステップへ

次のセクションでは、TerraformとGitHub Actionsを連携させ、インフラの変更もCI/CDパイプラインで自動化する方法を学びます。


推定読了時間: 40分