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インスタンスを構築し、SSH接続するまでの完全ガイド

Posted at

本記事では、Terraform を使って AWS EC2 インスタンスを構築し、SSH 接続できるようになるまでの手順を、
Key Pair(鍵ペア)の仕組み・設定方法を含めて、実務目線で丁寧に解説します。

AWS コンソール操作に頼らず、IaC(Infrastructure as Code)で EC2 を再現可能に構築したい方向けの記事です。


🎯 対象読者

  • Terraform を使って EC2 を立ち上げたい方
  • EC2 の SSH 接続で毎回つまずく方
  • 手動構築から IaC 管理へ移行したいエンジニア

🧩 なぜ Terraform で EC2 を構築するのか

EC2 をコンソールで作成すると、以下の問題が起こりがちです。

  • 設定内容が人によってバラバラ
  • 同じ環境を再現できない
  • 手順書ベースで属人化する

Terraform を使うことで、

  • EC2 構成をコードで管理
  • 環境差分を明確化
  • 削除・再作成も安全

が可能になります。


🛠 全体構成と事前準備

今回作成する構成

  • EC2 インスタンス(Amazon Linux)
  • Key Pair(SSH 鍵)
  • Security Group(SSH 接続許可)

ディレクトリ構成例

ec2/
 ├─ main.tf
 ├─ variables.tf
 ├─ outputs.tf

🔑 Key Pair(鍵ペア)とは

EC2 では パスワード認証は使わず、公開鍵認証(SSH Key)を利用します。

  • 秘密鍵(.pem):手元で保管(絶対に公開しない)
  • 公開鍵:EC2 側に登録

Terraform では 既存 Key Pair を利用するのが一般的です。


🔐 Key Pair の作成(事前作業)

ssh-keygen -t rsa -b 4096 -f ~/.ssh/ec2-terraform

生成されるファイル:

  • ec2-terraform(秘密鍵)
  • ec2-terraform.pub(公開鍵)

✍️ Terraform で Key Pair を定義

resource "aws_key_pair" "example" {
  key_name   = "ec2-terraform-key"
  public_key = file("~/.ssh/ec2-terraform.pub")
}

🖥 EC2 インスタンスを Terraform で作成

resource "aws_instance" "example" {
  ami           = "ami-0abcdef1234567890" # Amazon Linux
  instance_type = "t3.micro"
  key_name      = aws_key_pair.example.key_name

  vpc_security_group_ids = [
    aws_security_group.ssh.id
  ]

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

🔓 SSH 用 Security Group 設定

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

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

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

📌 注意
0.0.0.0/0 は避け、必ず自分の IP に限定しましょう。


🚀 Terraform 実行手順

terraform init
terraform plan
terraform apply

🔗 EC2 へ SSH 接続

chmod 400 ~/.ssh/ec2-terraform
ssh -i ~/.ssh/ec2-terraform ec2-user@<EC2_PUBLIC_IP>

接続できれば成功です 🎉


🚨 よくあるトラブル

❌ Permission denied (publickey)

  • 秘密鍵の権限が緩い
  • Key Pair 名が EC2 と一致していない

❌ タイムアウト

  • Security Group で 22 番ポート未開放
  • 接続元 IP が違う

📦 実務での運用ポイント

  • Key Pair は Git 管理しない
  • 環境別に instance_type を変数化
  • module 化して再利用

✅ まとめ

Terraform を使えば、

  • 🧱 EC2 構築をコードで再現
  • 🔐 SSH 接続設定も明確化
  • 🔁 安全な運用が可能

まずは 1 台の EC2 を Terraform 管理するところから始めてみましょう。


🔗 参考リンク

  • Terraform AWS Provider EC2 Docs
  • AWS EC2 Key Pair ドキュメント
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?