Terraform完全入門【2026年版】Infrastructure as Codeでインフラを自動化する実践ガイド

Terraformとは?なぜInfrastructure as Codeが重要なのか

TerraformはHashiCorpが開発したInfrastructure as Code(IaC)ツールです。AWS・GCP・Azureなど主要クラウドプロバイダーのインフラをコードで定義・管理できます。2026年現在、クラウドインフラの管理にTerraformを採用する企業が急増しており、インフラエンジニアの必須スキルとなっています。

IaCのメリット

  • インフラの状態をGitで管理できる
  • 同じ設定を何度でも再現できる
  • チームでのレビュー・変更履歴の追跡が可能
  • 手動ミスを大幅に削減できる

Terraformのインストールと初期設定

# macOSの場合(Homebrew)
brew tap hashicorp/tap
brew install hashicorp/tap/terraform

# バージョン確認
terraform version

# AWS認証情報の設定
export AWS_ACCESS_KEY_ID='your-access-key'
export AWS_SECRET_ACCESS_KEY='your-secret-key'
export AWS_DEFAULT_REGION='ap-northeast-1'

Terraformの基本ファイル構成

project/
  main.tf          # メインの設定
  variables.tf     # 変数定義
  outputs.tf       # 出力値の定義
  terraform.tfvars # 変数の実際の値
  versions.tf      # Terraform・プロバイダーのバージョン固定
  modules/         # 再利用可能なモジュール

基本的なAWSリソースの作成

# versions.tf
terraform {
  required_version = ">= 1.6"
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.0"
    }
  }
  backend "s3" {
    bucket = "my-terraform-state"
    key    = "production/terraform.tfstate"
    region = "ap-northeast-1"
  }
}

provider "aws" {
  region = var.aws_region
}

# variables.tf
variable "aws_region" {
  description = "AWSリージョン"
  type        = string
  default     = "ap-northeast-1"
}

variable "environment" {
  description = "環境名"
  type        = string
  validation {
    condition     = contains(["production", "staging", "development"], var.environment)
    error_message = "environmentはproduction・staging・developmentのいずれかです"
  }
}

variable "instance_type" {
  description = "EC2インスタンスタイプ"
  type        = string
  default     = "t3.micro"
}

# main.tf - VPCとネットワーク
resource "aws_vpc" "main" {
  cidr_block           = "10.0.0.0/16"
  enable_dns_hostnames = true
  enable_dns_support   = true

  tags = {
    Name        = "${var.environment}-vpc"
    Environment = var.environment
    ManagedBy   = "terraform"
  }
}

resource "aws_subnet" "public" {
  count             = 2
  vpc_id            = aws_vpc.main.id
  cidr_block        = "10.0.${count.index}.0/24"
  availability_zone = data.aws_availability_zones.available.names[count.index]

  tags = {
    Name = "${var.environment}-public-subnet-${count.index + 1}"
  }
}

# EC2インスタンス
resource "aws_instance" "web" {
  ami           = data.aws_ami.amazon_linux.id
  instance_type = var.instance_type
  subnet_id     = aws_subnet.public[0].id

  tags = {
    Name        = "${var.environment}-web"
    Environment = var.environment
  }
}

モジュールで再利用可能なコードを書く

# modules/rds/main.tf
resource "aws_db_instance" "main" {
  identifier     = var.identifier
  engine         = "postgres"
  engine_version = "16.1"
  instance_class = var.instance_class

  allocated_storage     = var.allocated_storage
  max_allocated_storage = var.max_allocated_storage

  db_name  = var.db_name
  username = var.db_username
  password = var.db_password

  multi_az               = var.multi_az
  backup_retention_period = 7
  deletion_protection    = true
  skip_final_snapshot    = false

  tags = var.tags
}

# modules/rds/variables.tf
variable "identifier" { type = string }
variable "instance_class" { type = string; default = "db.t3.micro" }
variable "db_name" { type = string }
variable "db_username" { type = string }
variable "db_password" { type = string; sensitive = true }
variable "multi_az" { type = bool; default = false }
variable "allocated_storage" { type = number; default = 20 }
variable "max_allocated_storage" { type = number; default = 100 }
variable "tags" { type = map(string); default = {} }

# ルートモジュールからの呼び出し
module "database" {
  source = "./modules/rds"

  identifier   = "${var.environment}-db"
  db_name      = "myapp"
  db_username  = "admin"
  db_password  = var.db_password
  multi_az     = var.environment == "production"

  tags = {
    Environment = var.environment
    ManagedBy   = "terraform"
  }
}

Terraformのワークフロー

# 初期化(プロバイダーのダウンロード)
terraform init

# 実行計画の確認(変更内容のプレビュー)
terraform plan
terraform plan -out=tfplan

# 変更の適用
terraform apply
terraform apply tfplan

# 状態の確認
terraform show
terraform state list

# 特定リソースのインポート
terraform import aws_instance.web i-1234567890abcdef0

# リソースの削除
terraform destroy -target=aws_instance.web
terraform destroy

まとめ:Terraformでインフラ管理を次のレベルへ

  • ✅ HCL記法でインフラをコードとして管理
  • ✅ リモートステートでチーム開発に対応
  • ✅ モジュール化で再利用可能なコードを書く
  • ✅ plan/applyワークフローで安全に変更を適用

投稿者 kasata

IT企業でエンジニアとして勤務後、テクノロジー情報メディア「Tech Athletes(テック・アスリート)」を運営。プログラミング、クラウドインフラ(AWS/GCP/Azure)、AI活用、Webサービス開発を専門とする。エンジニア・ビジネスパーソン向けに、実際に使ってみた経験をもとに信頼できる技術情報を発信中。資格:AWS認定ソリューションアーキテクト、Python 3 エンジニア認定試験合格。

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です