Terraform 基础设施即代码

精选 Terraform 基础设施即代码 常用指令与核心速查备忘单,涵盖高频用法、配置参数与实用技巧。

#Terraform CLI 命令行工具

#项目初始化 (Initialization)

terraform init [options]

    -upgrade            # Install latest module & provider versions
    -reconfigure        # reconfigure backend, ignoring any saved config
    -backend=false      # Disable backend & use previous Initialization
    -migrate-state      # reconfigure backend & attempt to migrate any existing state

#执行计划预览 (Planning)

Generates & review an execution plan

terraform plan [options]

    -var 'user=john'    # set value for input vars in the root module of config
    -var-file=filename  # load var values from the given file
    -input=true         # ask for input for vars if not directly set
    -out=path           # write a plan file to given path. can be used as input for "apply"
    -refresh-only       # verifies remote object consistency without proposing actions to undo changes done outside TF
    -destroy            # create plan to destroy all objects currenly managed
    -target=resource    # target planning to given resouce & its dependencies only.

terraform plan -refresh-only # updates state to match changes made outside of TF. Good for drift detection

#语法校验 (Validation)

terraform validate      # Validates the config files for errors

#应用部署 (Apply)

Executes changes to infra

terraform apply [options]

    -auto-approve       # skip interactive approval of plan before applying
    -replace            # 强制执行 replacement of a particular resource instance
    -var 'foo=bar'      # set a value for input vars in the root module of config
    -var-file=filename  # load var values from the given file
    -parallelism=n      # limit the no of concurrent operations. Default=10

terraform apply -auto-approve var-file=web-dev.tfvars
terraform apply -replace="aws_instance.server"
terraform plan -refresh-only # Updates statefile to accept changes made manually.

#销毁资源 (Destroy)

Destroy (deletes) Terraform managed infra. Same as terraform apply -destroy

terraform destroy [options]

    -auto-approve        # skip interactive approval before destroying
    -target              # limits destroy to only given resource & its dependencies


terraform destroy -target aws_vpc.my_vpc -auto-approve

Miscellaneous

terraform state show aws_instance.my_vm
terraform state pull > my_terraform.tfstate
terraform state mv aws_iam_role.my_ssm_role
terraform state list
terraform state rm aws_instance.my_server

terraform import aws_instance.new_server i-243abc
sudo apt install graphviz
terraform graph | dot -Tpng > graph.png

日志与调试 (Logging)

log levels = TRACE > DEBUG > INFO > WARN > ERROR

export TF_LOG_CORE=TRACE     # enable core 日志与调试 (Logging)
export TF_LOG_PROVIDER=TRACE # enable provider 日志与调试 (Logging)
export TF_LOG_PATH=logs.txt  # to persist logs

#🔗 参考资源