0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

🌎 Terraform で AWS Internet Gateway を作成するシンプルな手順

Last updated at Posted at 2025-02-09

📌 概要

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
}

[参考リポジトリ]

📌 実行

準備ができたらコマンド実行しましょう!

  1. terraform init
  2. terraform plan
  3. terraform apply

Terraform関連のコマンドについては以下の記事を参考にしてください ☺️

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?