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】【初心者向け】Terraform で EC2 を構築し、UserData で初期セットアップまで自動化する

Posted at

本記事では、Terraform を使って AWS EC2 を構築し、UserData によって初期セットアップ(パッケージ導入・設定)まで自動化する方法を、 実務でよく使われる構成・考え方を交えて丁寧に解説します。


🎯 対象読者

  • Terraform で EC2 を管理している/これから使う方
  • EC2 作成後の手作業を減らしたい方
  • IaC を「構築だけ」で終わらせたくないエンジニア

🧩 なぜ UserData を使うのか

EC2 を起動した直後、毎回 SSH でログインして設定する運用には以下の課題があります。

  • 手順が属人化する
  • 作業履歴が残らない
  • 再作成時に同じ状態を保証できない

UserData を使うことで、EC2 起動時に自動で初期設定を行い、
再現性のあるインフラ構築が可能になります。


🛠 今回作成する構成

  • EC2(Amazon Linux 2)
  • Security Group(SSH / HTTP)
  • UserData
    • yum update
    • nginx インストール
    • 自動起動設定

📁 ディレクトリ構成例

ec2-userdata/
 ├─ main.tf
 ├─ variables.tf
 ├─ userdata.sh

📜 UserData スクリプト

#!/bin/bash
yum update -y
yum install -y nginx

systemctl start nginx
systemctl enable nginx

ログは /var/log/cloud-init-output.log で確認できます。


🔐 Security Group 定義

resource "aws_security_group" "web" {
  name = "allow-ssh-http"

  ingress {
    from_port   = 22
    to_port     = 22
    protocol    = "tcp"
    cidr_blocks = ["YOUR_IP/32"]
  }

  ingress {
    from_port   = 80
    to_port     = 80
    protocol    = "tcp"
    cidr_blocks = ["YOUR_IP/32"]
  }

  egress {
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }
}

🖥 EC2 定義

resource "aws_instance" "example" {
  ami           = "ami-0abcdef1234567890"
  instance_type = "t3.micro"
  key_name      = var.key_name

  vpc_security_group_ids = [
    aws_security_group.web.id
  ]

  user_data = file("userdata.sh")

  tags = {
    Name = "terraform-userdata-example"
  }
}

🚀 Terraform 実行

terraform init
terraform plan
terraform apply

🌐 動作確認

http://<EC2_PUBLIC_IP>

nginx のデフォルト画面が表示されれば成功です。


🚨 よくあるトラブル

  • UserData は EC2 再起動では再実行されない
  • 修正後は EC2 を作り直す必要がある

📦 実務でのポイント

  • UserData は最小限に
  • 複雑な構成は Ansible / SSM へ分離
  • module 化で再利用

✅ まとめ

Terraform + UserData により、
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?