Terraform / OpenTofu チート集
Terraform / OpenTofu の init/plan/apply、workspace、state、backend、import、module、provider、式、dynamic block、デバッグ運用をまとめたチート集。
- 更新日
- 2026-05-29
- 参照範囲
- 公式ドキュメント / man page / 主要ベンダーCLI
- 対象実装
- 主要 Linux / BSD / ネットワーク機器 CLI の一般的な実装
- 免責
- OS とバージョン差分は実環境で確認してください。
このチートシートの使いどころ
Terraform / OpenTofu チート集は、Terraform / OpenTofu の init/plan/apply、workspace、state、backend、import、module、provider、式、dynamic block、デバッグ運用をまとめたチート集。 対象は公式ドキュメント、man page、主要ベンダー CLI で確認できる現行の一般的な実装です。カテゴリはinit-plan-apply、state、modules、provider、workspacesを中心に、40件のコマンドや値を用途別に引けます。障害調査、設定変更前の確認、作業メモ作成で、Terraform、OpenTofu、IaC、state、backendに関連する操作を短時間で探すために使います。
40 / 40
terraform initbackend と provider を初期化する。
terraform initterraform init -upgradeprovider/module を制約内で更新する。
terraform init -upgradeterraform getmodule を取得・更新する。
terraform get -updateterraform fmtHCL を整形する。
terraform fmt -recursiveterraform validate構成を検証する。
terraform validateterraform plan変更計画を表示する。
terraform plan -var-file=prod.tfvarsterraform plan -outplan ファイルを保存する。
terraform plan -out=tfplan -var-file=prod.tfvarsterraform apply tfplan保存済み plan を適用する。
terraform apply tfplanterraform destroy管理対象を削除する。
terraform destroy -var-file=dev.tfvarsterraform outputoutput を確認する。
terraform output -json | jq .vpc_id.valueterraform apply -refresh-only実リソースとの差分を state に反映する。terraform refresh は Terraform 0.15.4 以降で非推奨のため、変更内容を確認できる refresh-only plan/apply を使う。
terraform plan -refresh-only -var-file=prod.tfvars
terraform apply -refresh-only -var-file=prod.tfvarsterraform workspace newworkspace を作成する。
terraform workspace new stgterraform workspace selectworkspace を切り替える。
terraform workspace select prodterraform workspace listworkspace 一覧を表示する。
terraform workspace listterraform state liststate 内のアドレスを一覧する。
terraform state listterraform state show特定リソースの state を表示する。
terraform state show aws_instance.webterraform state mvstate 上でリソース名を移動する。
terraform state mv aws_instance.old aws_instance.webterraform state rmstate から管理対象を外す。
terraform state rm aws_s3_bucket.legacyterraform state pullremote state を取得する。
terraform state pull > state.jsonterraform state pushstate を手動 push する。
terraform state push state.jsonbackend s3S3 backend の設定例。
terraform { backend "s3" { bucket = "tfstate-prod" key = "network/terraform.tfstate" region = "ap-northeast-1" dynamodb_table = "tf-lock" } }backend gcsGCS backend の設定例。
terraform { backend "gcs" { bucket = "tfstate-prod" prefix = "network" } }backend azurermAzure Storage backend の設定例。
terraform { backend "azurerm" { resource_group_name = "rg-tfstate" storage_account_name = "tfstateprod" container_name = "tfstate" key = "prod.tfstate" } }terraform import既存リソースを state に取り込む。
terraform import aws_instance.web i-1234567890abcdef0module source localローカル module を呼び出す。
module "vpc" { source = "../../modules/vpc" cidr = "10.0.0.0/16" }module source registryregistry module を使う。
module "vpc" { source = "terraform-aws-modules/vpc/aws" version = "5.21.0" name = "prod" cidr = "10.0.0.0/16" }for_eachmap/set の各要素でリソースを作る。
resource "aws_iam_user" "user" { for_each = toset(["alice", "bob"]) name = each.key }count個数指定でリソースを作る。
resource "aws_instance" "web" { count = 2 ami = var.ami instance_type = "t3.micro" }depends_on暗黙依存がない場合に依存を明示する。
resource "aws_instance" "web" { depends_on = [aws_iam_role_policy_attachment.web] }sensitive output機微値を output で隠す。
output "db_password" { value = random_password.db.result sensitive = true }provider alias複数 region/account の provider を使う。
provider "aws" { alias = "use1" region = "us-east-1" }required_providersprovider source と version を固定する。
terraform { required_providers { aws = { source = "hashicorp/aws" version = "~> 5.0" } } }for expressionfor 式で map を変換する。
locals { subnet_ids_by_name = { for s in aws_subnet.private : s.tags.Name => s.id } }dynamic block可変数のネストブロックを生成する。
dynamic "ingress" { for_each = var.ingress_rules content { from_port = ingress.value.port to_port = ingress.value.port protocol = "tcp" cidr_blocks = ingress.value.cidrs } }try coalesce欠損や null に安全な既定値を使う。
locals { name = coalesce(try(var.tags.Name, null), "default-name") }templatefileテンプレートをレンダリングする。
user_data = templatefile("cloud-init.yml.tftpl", { hostname = "web-1" })TF_LOG=DEBUG詳細ログを出して調査する。
TF_LOG=DEBUG TF_LOG_PATH=/tmp/terraform.log terraform plan-target対象を絞って plan/apply する。
terraform plan -target=module.vpc.aws_subnet.private[0]-replace特定リソースを作り直す。
terraform apply -replace=aws_instance.web[0]OpenTofu compatibilityOpenTofu は多くのコマンドと tfstate が互換。
tofu plan -var-file=prod.tfvars| Command | Description | Example | Copy |
|---|---|---|---|
terraform init | backend と provider を初期化する。 | terraform init | |
terraform init -upgrade | provider/module を制約内で更新する。 | terraform init -upgrade | |
terraform get | module を取得・更新する。 | terraform get -update | |
terraform fmt | HCL を整形する。 | terraform fmt -recursive | |
terraform validate | 構成を検証する。 | terraform validate | |
terraform plan | 変更計画を表示する。 | terraform plan -var-file=prod.tfvars | |
terraform plan -out | plan ファイルを保存する。 | terraform plan -out=tfplan -var-file=prod.tfvars | |
terraform apply tfplan | 保存済み plan を適用する。 | terraform apply tfplan | |
terraform destroy | 管理対象を削除する。 | terraform destroy -var-file=dev.tfvars | |
terraform output | output を確認する。 | terraform output -json | jq .vpc_id.value | |
terraform apply -refresh-only | 実リソースとの差分を state に反映する。terraform refresh は Terraform 0.15.4 以降で非推奨のため、変更内容を確認できる refresh-only plan/apply を使う。 | terraform plan -refresh-only -var-file=prod.tfvars
terraform apply -refresh-only -var-file=prod.tfvars | |
terraform workspace new | workspace を作成する。 | terraform workspace new stg | |
terraform workspace select | workspace を切り替える。 | terraform workspace select prod | |
terraform workspace list | workspace 一覧を表示する。 | terraform workspace list | |
terraform state list | state 内のアドレスを一覧する。 | terraform state list | |
terraform state show | 特定リソースの state を表示する。 | terraform state show aws_instance.web | |
terraform state mv | state 上でリソース名を移動する。 | terraform state mv aws_instance.old aws_instance.web | |
terraform state rm | state から管理対象を外す。 | terraform state rm aws_s3_bucket.legacy | |
terraform state pull | remote state を取得する。 | terraform state pull > state.json | |
terraform state push | state を手動 push する。 | terraform state push state.json | |
backend s3 | S3 backend の設定例。 | terraform { backend "s3" { bucket = "tfstate-prod" key = "network/terraform.tfstate" region = "ap-northeast-1" dynamodb_table = "tf-lock" } } | |
backend gcs | GCS backend の設定例。 | terraform { backend "gcs" { bucket = "tfstate-prod" prefix = "network" } } | |
backend azurerm | Azure Storage backend の設定例。 | terraform { backend "azurerm" { resource_group_name = "rg-tfstate" storage_account_name = "tfstateprod" container_name = "tfstate" key = "prod.tfstate" } } | |
terraform import | 既存リソースを state に取り込む。 | terraform import aws_instance.web i-1234567890abcdef0 | |
module source local | ローカル module を呼び出す。 | module "vpc" { source = "../../modules/vpc" cidr = "10.0.0.0/16" } | |
module source registry | registry module を使う。 | module "vpc" { source = "terraform-aws-modules/vpc/aws" version = "5.21.0" name = "prod" cidr = "10.0.0.0/16" } | |
for_each | map/set の各要素でリソースを作る。 | resource "aws_iam_user" "user" { for_each = toset(["alice", "bob"]) name = each.key } | |
count | 個数指定でリソースを作る。 | resource "aws_instance" "web" { count = 2 ami = var.ami instance_type = "t3.micro" } | |
depends_on | 暗黙依存がない場合に依存を明示する。 | resource "aws_instance" "web" { depends_on = [aws_iam_role_policy_attachment.web] } | |
sensitive output | 機微値を output で隠す。 | output "db_password" { value = random_password.db.result sensitive = true } | |
provider alias | 複数 region/account の provider を使う。 | provider "aws" { alias = "use1" region = "us-east-1" } | |
required_providers | provider source と version を固定する。 | terraform { required_providers { aws = { source = "hashicorp/aws" version = "~> 5.0" } } } | |
for expression | for 式で map を変換する。 | locals { subnet_ids_by_name = { for s in aws_subnet.private : s.tags.Name => s.id } } | |
dynamic block | 可変数のネストブロックを生成する。 | dynamic "ingress" { for_each = var.ingress_rules content { from_port = ingress.value.port to_port = ingress.value.port protocol = "tcp" cidr_blocks = ingress.value.cidrs } } | |
try coalesce | 欠損や null に安全な既定値を使う。 | locals { name = coalesce(try(var.tags.Name, null), "default-name") } | |
templatefile | テンプレートをレンダリングする。 | user_data = templatefile("cloud-init.yml.tftpl", { hostname = "web-1" }) | |
TF_LOG=DEBUG | 詳細ログを出して調査する。 | TF_LOG=DEBUG TF_LOG_PATH=/tmp/terraform.log terraform plan | |
-target | 対象を絞って plan/apply する。 | terraform plan -target=module.vpc.aws_subnet.private[0] | |
-replace | 特定リソースを作り直す。 | terraform apply -replace=aws_instance.web[0] | |
OpenTofu compatibility | OpenTofu は多くのコマンドと tfstate が互換。 | tofu plan -var-file=prod.tfvars |