Infrastructure as Code(IaC)は現代のクラウドインフラ管理の標準となっています。Terraformを使うことで、AWSやGCPのインフラをコードで定義・バージョン管理・自動化できます。本記事ではTerraformの基礎から実践的な使い方まで解説します。
Terraformとは?IaCのメリット
- 再現性:同じ設定から同じインフラを何度でも構築できる
- バージョン管理:インフラの変更履歴をGitで管理できる
- 自動化:手動操作ミスをなくしCI/CDに組み込める
- マルチクラウド対応:AWS・GCP・Azure・Kubernetes等に対応
- チーム開発:コードレビューでインフラ変更を確認できる
Terraformのインストールと初期設定
# macOSでインストール
brew install terraform
# バージョン確認
terraform version
# AWSproviderの設定(main.tf)
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
}
# リモートステートの設定(推奨)
backend "s3" {
bucket = "my-terraform-state"
key = "prod/terraform.tfstate"
region = "ap-northeast-1"
}
}
provider "aws" {
region = "ap-northeast-1"
}
基本的なAWSリソースの定義
# EC2インスタンスの作成
resource "aws_instance" "web_server" {
ami = "ami-0d52744d6551d851e"
instance_type = "t3.micro"
vpc_security_group_ids = [aws_security_group.web_sg.id]
subnet_id = aws_subnet.public_subnet.id
tags = {
Name = "web-server"
Environment = var.environment
Project = "tech-athletes"
}
}
# セキュリティグループ
resource "aws_security_group" "web_sg" {
name_prefix = "web-sg-"
vpc_id = aws_vpc.main.id
ingress {
from_port = 80
to_port = 80
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
ingress {
from_port = 443
to_port = 443
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"]
}
}
変数・出力の定義
# variables.tf
variable "environment" {
type = string
description = "デプロイ環境(dev/staging/prod)"
default = "dev"
validation {
condition = contains(["dev", "staging", "prod"], var.environment)
error_message = "環境はdev/staging/prodのいずれかを指定してください。"
}
}
variable "instance_type" {
type = string
default = "t3.micro"
}
# outputs.tf
output "instance_public_ip" {
description = "EC2インスタンスのパブリックIP"
value = aws_instance.web_server.public_ip
}
output "instance_id" {
description = "EC2インスタンスID"
value = aws_instance.web_server.id
}
Terraformのワークフロー
# 初期化(プロバイダーをダウンロード)
terraform init
# 実行計画の確認
terraform plan
terraform plan -var="environment=prod"
# インフラを適用
terraform apply
terraform apply -auto-approve # 確認をスキップ
# 特定リソースのみ適用
terraform apply -target=aws_instance.web_server
# インフラの削除
terraform destroy
# 状態の確認
terraform show
terraform state list
まとめ
Terraformを使ったIaCは、現代のクラウドインフラ管理において必須スキルです。コードによるインフラ定義・バージョン管理・自動化を習得することで、インフラエンジニアとしての市場価値が大幅に向上します。まずはAWSの簡単なリソース定義から始めて、徐々に複雑なアーキテクチャに挑戦してみてください。