terraform について
Terraform のインフラ構成を扱う開発ガイドです。プロジェクト構成、プロバイダー、変数、リソース、モジュール、作業手順を取り上げます。Terraform 構成を作成・整理する開発者向けです。
主な機能
- 01Terraform プロジェクトのファイル構成
- 02プロバイダーのバージョンと設定
- 03変数と入力値の検証
- 04リソース、データソース、モジュール
- 05init、fmt、validate のワークフロー
- 06リモート状態と環境整理の指針
活用シーン
- 01Terraform プロジェクトのディレクトリ構成
- 02プロバイダー、変数、インフラリソースの設定
- 03再利用可能な構成のモジュール化
- 04構成の初期化、フォーマット、検証
インストール
コマンドをコピーしてターミナルで実行します。
$
npx skills add https:/ / github.com/ dralgorhythm/ claude-agentic-framework --skill terraformインストール後、Claude Code で/terraformを入力して読み込まれたか確認します。
詳細
Terraform 開発
プロジェクト構成
terraform/
├── main.tf # Main resources
├── variables.tf # Input variables
├── outputs.tf # Output values
├── providers.tf # Provider config
├── versions.tf # Version constraints
├── terraform.tfvars # Variable values
└── modules/
└── vpc/
├── main.tf
├── variables.tf
└── outputs.tf
プロバイダーの設定
# versions.tf
terraform {
required_version = ">= 1.5"
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
}
backend "s3" {
bucket = "terraform-state"
key = "prod/terraform.tfstate"
region = "us-east-1"
dynamodb_table = "terraform-locks"
encrypt = true
}
}
provider "aws" {
region = var.aws_region
default_tags {
tags = {
Environment = var.environment
ManagedBy = "terraform"
}
}
}
変数
# variables.tf
variable "environment" {
description = "Environment name"
type = string
validation {
condition = contains(["dev", "staging", "prod"], var.environment)
error_message = "Environment must be dev, staging, or prod."
}
}
variable "instance_config" {
description = "EC2 instance configuration"
type = object({
instance_type = string
ami_id = string
volume_size = number
})
default = {
instance_type = "t3.micro"
ami_id = "ami-12345678"
volume_size = 20
}
}
リソース
# main.tf
resource "aws_vpc" "main" {
cidr_block = var.vpc_cidr
enable_dns_hostnames = true
tags = {
Name = "${var.project}-vpc"
}
}
resource "aws_subnet" "private" {
count = length(var.availability_zones)
vpc_id = aws_vpc.main.id
cidr_block = cidrsubnet(var.vpc_cidr, 8, count.index)
availability_zone = var.availability_zones[count.index]
tags = {
Name = "${var.project}-private-${count.index + 1}"
}
}
モジュール
# Using a module
module "vpc" {
source = "./modules/vpc"
project = var.project
environment = var.environment
cidr_block = "10.0.0.0/16"
}
# Module outputs
output "vpc_id" {
value = module.vpc.vpc_id
}
データソース
data "aws_ami" "amazon_linux" {
most_recent = true
owners = ["amazon"]
filter {
name = "name"
values = ["amzn2-ami-hvm-*-x86_64-gp2"]
}
}
resource "aws_instance" "web" {
ami = data.aws_ami.amazon_linux.id
instance_type = var.instance_type
}
ワークフロー
# Initialize
terraform init
# Format
terraform fmt -recursive
# Validate
terraform validate
# Plan
terraform plan -out=tfplan
# Apply
terraform apply tfplan
# Destroy
terraform destroy
ベストプラクティス
- ロック機能付きのリモートステートを使用します
- 再利用性を高めるためにモジュールを使用します
- 設定可能な値にはすべて変数を使用します
- 既存のリソースにはデータソースを使用します
- すべてのリソースにタグを付けます
- 環境ごとにワークスペースまたはディレクトリを使用します
コメント
Markdown 対応