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にVPC+EC2を構築してみた

Posted at

【入門】TerraformでAWSにVPC+EC2を構築してみた Part1(初心者でも動かせた)

🔰 はじめに

AWS初心者でもインフラをコードで管理できる「Terraform」を使って、VPC+EC2構成を構築してみました。

今回は macOS(またはWSL)ローカルから、GitHub連携とTerraform apply までを完了する手順 を記録しています。

💡 ハマったポイント → こちらで解説


📌 ゴール(作るもの)

Terraformで以下のAWS構成を自動作成


🧩 前提環境

項目 内容
OS macOS または WSL
Terraform v1.x 以降
AWS CLI v2 以降、IAMユーザー設定済
EC2キーペア 作成済(例: your-key.pem
Git インストール済、GitHubアカウントあり

📁 ディレクトリ構成

aws-vpc-ec2/
├── main.tf
├── variables.tf
├── terraform.tfvars
└── .gitignore

## 🧪 実行環境の確認

uname -s  # Darwin (Mac)
uname -r  # 24.5.0
uname -m  # x86_64

cd ~/Downloads/aws-vpc-ec2

# Git初期化
git init
git add .
git commit -m "Initial commit"

# GitHubリモート登録
git remote add origin git@github.com:tanisi0131/terraform-aws-vpc-ec2-v2.git

# ブランチ名をmainに変更
git branch -M main

# プッシュ
git push -u origin main

💥 Repository not found が出る場合は → ハマったポイント

🧾 Terraformファイルの例

main.tf

provider "aws" {
  region = "ap-northeast-1"
}

resource "aws_vpc" "main" {
  cidr_block = "10.0.0.0/16"
}

resource "aws_subnet" "public" {
  vpc_id            = aws_vpc.main.id
  cidr_block        = "10.0.1.0/24"
  map_public_ip_on_launch = true
}

resource "aws_instance" "web" {
  ami                    = "ami-xxxxxxxx"  # Amazon Linux 2 (リージョンに注意)
  instance_type          = "t2.micro"
  subnet_id              = aws_subnet.public.id
  key_name               = var.key_name
  vpc_security_group_ids = [aws_security_group.ssh.id]
}

variables.tf

variable "key_name" {
  description = "EC2に使うキーペア名"
  type        = string
}

terraform.tfvars

key_name = "your-key"

✅ デプロイ手順

terraform init
terraform plan
terraform apply

💥 ハマったポイント

ハマりポイント 対応策
terraform apply でキーペア名が違って失敗 key_name 変数が正しいか確認(管理コンソールと一致させる)
AMI IDが正しくない Amazon Linux 2はリージョンごとにAMI IDが違う
最新AMI IDを取得する方法
security_groupsvpc_security_group_idsを併用して警告 どちらか一方のみ使う(推奨は vpc_security_group_ids
GitHub Push時に Repository not found エラー git remote -v でリモートURL確認。HTTPS/SSH間違いや、スペルミスに注意。

📘 学びとまとめ

  • Terraformを使ってAWS構成の自動化ができた
  • GitとGitHubの連携により再利用性も向上
  • エラーは焦らず原因を分解して調べるのがコツ

次回(Part2)は以下に挑戦予定

  • Terraformのremote backend(S3 + DynamoDB)
  • ステートファイルの安全な管理
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?