📌 概要
Terraform を使って AWS の Internet Gateway (IGW) を作成する方法 を解説します🚀
Internet Gateway を使うと、VPC 内のリソース(EC2 など)がインターネットと通信できるようになります ✨
📌 事前に準備するもの
main.tf
main.tf の作成がまだの方は以下の記事を参考にファイルを作成してください。
VPC
VPCを作成していない場合は以下を参考に作成します
📌 ディレクトリ構成
以下のようなディレクトリ構造でファイルを配置してください。
terraform-project/
│── main.tf # ルートディレクトリのメイン設定
│── modules/
│ ├── vpc/
│ │ ├── main.tf # VPCを定義
│ ├── internet_gateway/
│ │ ├── main.tf # インターネットゲートウェイを定義
📌 コード
main.tf
Terraform のプロバイダー設定とモジュールの読み込み を行います。
# AWS プロバイダーの設定
# 利用するリージョンを "ap-northeast-1"(東京)に指定
provider "aws" {
region = "ap-northeast-1"
}
# VPC モジュールの読み込み
# "./vpc" ディレクトリにある VPC モジュールを利用
module "vpc" {
source = "./vpc"
}
# インターネットゲートウェイのモジュールを読み込み
# VPC モジュールで作成された VPC の ID を渡して関連付ける
module "internet_gateway" {
source = "./internet_gateway"
vpc_id = module.vpc.vpc_id
}
vpc/main.tf
VPC(Virtual Private Cloud)を作成し、VPC の ID を出力します。
# AWSプロバイダーの設定
provider "aws" {
region = "ap-northeast-1"
}
# VPCの作成
resource "aws_vpc" "main" {
cidr_block = "192.168.250.0/24"
tags = {
Name = "sandbox-terraform"
}
}
output "vpc_id" {
value = aws_vpc.main.id
}
internet_gateway/main.tf
Internet Gateway(IGW) を作成し、指定した VPC にアタッチします。
# VPC の ID を受け取る変数を定義
# この Internet Gateway を関連付ける VPC の ID を指定する
variable "vpc_id" {
description = "Internet Gateway を関連付ける VPC の ID"
type = string
}
# Internet Gateway を作成
# 指定された VPC にアタッチされる
resource "aws_internet_gateway" "main" {
vpc_id = var.vpc_id
tags = {
# Internet Gateway に "sandbox-terraform" という名前タグを付与
Name = "sandbox-terraform"
}
}
# 作成した Internet Gateway の ID を出力
# 他のリソースで参照できるようにするため
output "internet_gateway_id" {
value = aws_internet_gateway.main.id
}
[参考リポジトリ]
📌 実行
準備ができたらコマンド実行しましょう!
terraform init
terraform plan
terraform apply
Terraform関連のコマンドについては以下の記事を参考にしてください ☺️