前提条件
学習のため細かく分けて作成していきます。
VPCは以前作成したVPCを使用します。(AWSにVPCを作成してみる)
バージョン情報
- Terraform:
Terraform v1.10.5
- AWS CLI:
aws-cli/2.24.11 Python/3.12.9 Windows/11 exe/AMD64
Terraform ファイル
03_routetable.tf
以下の Terraform ファイルを作成しました。
provider "aws" {
region = "us-west-2"
}
# 既存の VPC を取得
data "aws_vpc" "terraform-vpc" {
filter {
name = "tag:Name"
values = ["terraform"]
}
}
# Internet Gateway の作成
resource "aws_internet_gateway" "terraform-igw" {
vpc_id = data.aws_vpc.terraform-vpc.id
tags = {
Name = "terraform-igw"
}
}
# パブリックルートテーブルの作成
resource "aws_route_table" "terraform-public-routetable" {
vpc_id = data.aws_vpc.terraform-vpc.id
route {
cidr_block = "0.0.0.0/0" # すべてのトラフィックを IGW にルーティング
gateway_id = aws_internet_gateway.terraform-igw.id
}
tags = {
Name = "terraform-public-routetable"
}
}
# プライベートルートテーブルの作成、S3 Endpointは次回作成するためここでは空のルートテーブル
resource "aws_route_table" "terraform-private-routetable" {
vpc_id = data.aws_vpc.terraform-vpc.id
tags = {
Name = "terraform-private-routetable"
}
}
実行コマンド (init, plan, apply)
terraform init
Terraform を初期化します。
PS C:\work\Terraform\01_basic\03-routetable> terraform init
出力結果:
Terraform has been successfully initialized!
terraform plan
Terraform の適用計画を確認します。
PS C:\work\Terraform\01_basic\03-routetable> terraform plan
出力結果:
Terraform will perform the following actions:
+ aws_route_table.terraform-private-routetable
+ aws_route_table.terraform-public-routetable
Plan: 2 to add, 0 to change, 0 to destroy.
terraform apply
ルートテーブルを作成します。
PS C:\work\Terraform\01_basic\03-routetable> terraform apply
出力結果:
aws_route_table.terraform-private-routetable: Creating...
aws_route_table.terraform-public-routetable: Creating...
aws_route_table.terraform-private-routetable: Creation complete after 1s [id=rtb-xxxxxxxxxxxxxxxxxxx]
aws_route_table.terraform-public-routetable: Creation complete after 2s [id=rtb-xxxxxxxxxxxxxxxxxxx]
Apply complete! Resources: 2 added, 0 changed, 0 destroyed.
作成したAWSリソース情報
- InternetGateway
- Publicサブネット用ルートテーブル
- Privateサブネット用ルートテーブル
※Privateサブネット用ルートテーブルにはVPC内のルートしか定義されていないです。
作成したリソースの詳細 (パラメータ一覧)
パラメータ一覧
参考:https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/route_tableパラメータ名 | 説明 |
---|---|
vpc_id |
ルートテーブルを作成する VPC の ID |
route |
ルートテーブルに設定するルート情報 |
cidr_block |
ルーティングの宛先CIDR(例: 0.0.0.0/0 は全トラフィック) |
gateway_id |
インターネットゲートウェイ (IGW) の ID |
tags |
ルートテーブルのタグ情報 |
気づいたこと・勘違いしていたこと
- InternetGatewayはルートテーブルを作成する前に作ること
前に作成しておけば、ルートテーブル作成する時点でルートを設定できる - S3エンドポイントはルートテーブル作成後に作ってアタッチしたほうがよさそう
S3エンドポイント作成時にルートテーブル情報が必要なので先に作るべきだと思う。。。
まとめ
- 既存の VPC を参照してパブリックルートテーブルとプライベートルートテーブルを作成しました。
次回は S3 Gateway Endpoint の追加 を行います。