Terraform

HashiCorp の IaC ツールで、マルチクラウドのインフラをコードで宣言的に管理する

IaCインフラ

Terraform とは

Terraform は、HashiCorp が開発した IaC (Infrastructure as Code) ツールで、AWS、Azure、GCP などマルチクラウドのインフラを HCL (HashiCorp Configuration Language) で宣言的に管理する。

SAM / CloudFormation との比較

観点 Terraform SAM / CloudFormation
対象 マルチクラウド AWS のみ
言語 HCL YAML / JSON
状態管理 tfstate ファイル CloudFormation が管理
サーバーレス 汎用 Lambda に特化
ドリフト検出 terraform plan CloudFormation ドリフト検出

基本的な使い方

# main.tf
provider "aws" {
  region = "ap-northeast-1"
}

resource "aws_s3_bucket" "data" {
  bucket = "my-data-bucket"
}

resource "aws_dynamodb_table" "users" {
  name         = "users"
  billing_mode = "PAY_PER_REQUEST"
  hash_key     = "id"

  attribute {
    name = "id"
    type = "S"
  }
}

コマンド

terraform init      # プロバイダーのダウンロード
terraform plan      # 変更内容のプレビュー
terraform apply     # インフラの作成・更新
terraform destroy   # インフラの削除

State (状態管理)

Terraform は terraform.tfstate ファイルで現在のインフラの状態を管理する。チーム開発では S3 + DynamoDB でリモートステートを共有する。

terraform {
  backend "s3" {
    bucket         = "my-terraform-state"
    key            = "prod/terraform.tfstate"
    region         = "ap-northeast-1"
    dynamodb_table = "terraform-locks"
    encrypt        = true
  }
}

モジュール

module "vpc" {
  source  = "terraform-aws-modules/vpc/aws"
  version = "5.0.0"

  name = "my-vpc"
  cidr = "10.0.0.0/16"
  azs  = ["ap-northeast-1a", "ap-northeast-1c"]
}

AWS での使い分け

ケース 推奨
Lambda + API Gateway SAM (サーバーレスに特化)
VPC + RDS + ECS Terraform (汎用)
マルチクラウド Terraform
AWS のみ、シンプル CloudFormation / SAM

Terraform の関連書籍も参考になる。

関連用語