はじめに
今回は、Terraformで記述したコードを使って、EC2を使った簡単なWebサーバーを公開するまでの手順をまとめてみました。
少しでもご参考になれば幸いです。
Terraformの基礎知識に関しては、ぜひこちらの記事をご参照ください。
今回のゴール
以下の構成を、Terraformで構築できるようにします。
さっそく実装してみた
※今回は単一の.tfファイルで実装しています。
以下のコマンドを順に実行します。
mkdir test-terraform
cd test-terraform
touch test.tf
test.tfの内容を、以下で書き換えます。
test.tf
# provider設定
provider "aws" {
profile = "project-a-dev"
}
# 最新AMI取得(Amazon Linux 2023)
data "aws_ami" "amazon_linux" {
most_recent = true
owners = ["amazon"]
filter {
name = "name"
values = ["al2023-ami-*-x86_64"]
}
}
# VPC
resource "aws_vpc" "main" {
cidr_block = "10.0.0.0/16"
tags = {
Name = "test-vpc"
}
}
# Internet Gateway
resource "aws_internet_gateway" "igw" {
vpc_id = aws_vpc.main.id
tags = {
Name = "test-igw"
}
}
# Subnet
resource "aws_subnet" "public_a" {
vpc_id = aws_vpc.main.id
cidr_block = "10.0.1.0/24"
availability_zone = "ap-northeast-1a"
map_public_ip_on_launch = true
tags = {
Name = "public-subnet-a"
}
}
# Route Table
resource "aws_route_table" "public_rt" {
vpc_id = aws_vpc.main.id
tags = {
Name = "public-rt-a"
}
}
# Route(0.0.0.0/0 → IGW)
resource "aws_route" "public_route" {
route_table_id = aws_route_table.public_rt.id
destination_cidr_block = "0.0.0.0/0"
gateway_id = aws_internet_gateway.igw.id
}
# Subnet と RouteTable の関連付け
resource "aws_route_table_association" "public_assoc" {
subnet_id = aws_subnet.public_a.id
route_table_id = aws_route_table.public_rt.id
}
# Security Group
resource "aws_security_group" "public_sg" {
name = "public-sg"
description = "Allow HTTP from anywhere"
vpc_id = aws_vpc.main.id
ingress {
from_port = 80
to_port = 80
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
egress {
from_port = 0
to_port = 0
protocol = "-1"
cidr_blocks = ["0.0.0.0/0"]
}
tags = {
Name = "public-sg"
}
}
# EC2インスタンス
resource "aws_instance" "ec2_instance" {
ami = data.aws_ami.amazon_linux.id
instance_type = "t3.micro"
subnet_id = aws_subnet.public_a.id
vpc_security_group_ids = [aws_security_group.public_sg.id]
user_data = <<-EOF
#!/bin/bash
dnf update -y
dnf install -y httpd
systemctl start httpd
systemctl enable httpd
echo "<h1>Hello from EC2!!!!!</h1>" > /var/www/html/index.html
EOF
tags = {
Name = "test-ec2"
}
}
初期化
以下のコマンドを実行し、現在のディレクトリを「Terraformとして実行可能な状態」にセットアップします。
zsh
terraform init
デプロイ
以下のコマンドを実行し、実際にインフラへ反映します。
zsh
terraform apply
作成したEC2(test-ec2)インスタンスの「パブリック IPv4 アドレス」へアクセスしたら、無事にWebサイトが表示されました。
削除
以下のコマンドを実行し、terraformを使用して作成したすべてのリソースを削除(クリーンアップ)します。
zsh
terraform destroy

