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?

20日目:AWS無料枠使い倒し「TerraformでAWS構成を自動化」

Last updated at Posted at 2025-12-19

TerraformでAWS構成を自動化(VPC/EC2/S3をIaC化)

予定コスト: $0.00(計画のみ)


✅ この記事でやること

VPC/EC2/S3の最小構成をTerraformで宣言的に展開。


✅ 前提(準備)

Terraform v1.6+、AWS認証、AMI IDとバケット名。


図解:Terraformによる構成要素

CLI→Provider→各リソースのイメージ。

Terraform CLI
  → AWS Provider
    → VPC / Subnet / IGW / Route / SG
      → EC2
      → S3

main.tf(最小構成)

VPC〜S3までの最小構成。

terraform {
  required_version = ">= 1.6.0"
}

provider "aws" {
  region = var.region
}

resource "aws_vpc" "main" { cidr_block = "10.2.0.0/16" }
resource "aws_subnet" "public" { vpc_id = aws_vpc.main.id, cidr_block = "10.2.1.0/24", availability_zone = var.az }
resource "aws_internet_gateway" "igw" { vpc_id = aws_vpc.main.id }
resource "aws_route_table" "rt" { vpc_id = aws_vpc.main.id }
resource "aws_route" "default" { route_table_id = aws_route_table.rt.id, destination_cidr_block = "0.0.0.0/0", gateway_id = aws_internet_gateway.igw.id }
resource "aws_route_table_association" "assoc" { subnet_id = aws_subnet.public.id, route_table_id = aws_route_table.rt.id }
resource "aws_security_group" "ssh" { name="advent-sg", vpc_id=aws_vpc.main.id, ingress{from_port=22,to_port=22,protocol="tcp",cidr_blocks=[var.myip]}, egress{from_port=0,to_port=0,protocol="-1",cidr_blocks=["0.0.0.0/0"]}}
resource "aws_instance" "ec2" { ami=var.ami_id, instance_type="t3.micro", subnet_id=aws_subnet.public.id, vpc_security_group_ids=[aws_security_group.ssh.id], tags={ Name="advent-ec2" } }
resource "aws_s3_bucket" "site" { bucket = var.bucket_name }

variables.tf

外部から渡す変数を定義。

variable "region" { type = string }
variable "az" { type = string }
variable "myip" { type = string }
variable "ami_id" { type = string }
variable "bucket_name" { type = string }

実行コマンド

初期化と適用。AMIはDay 5で取得したIDを利用。

terraform init
terraform apply -auto-approve -var region=ap-northeast-1 -var az=ap-northeast-1a -var myip=$(curl -s https://checkip.amazonaws.com)/32 -var ami_id=$AMI_ID -var bucket_name=my-tf-bucket-$RANDOM

💡 豆知識 (Tips)

  • stateはS3/DynamoDBで保護(ロック/バージョン管理)
  • Workspaceで環境分離(dev/stg/prod)

⚠️ 落とし穴

  • 手動変更のドリフト(Plan差分に表れない資産)
  • 秘密値の平文定義(tfvarsの保護不足)

🧾 今日のコスト

$0.00(Plan/Applyのみ。無料枠の範囲で)


✅ まとめ

  • 本日のゴールを確認
  • 無料枠を意識して運用
  • 次回に繋がるポイントを整理

✅ 次回予告(21日目)

「障害対応シミュレーション:EC2停止時の復旧」

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?