github/gitignore · Terraform.gitignore
Terraform .gitignore 模板详解
说明 Terraform.gitignore 忽略 .terraform 目录、tfstate、tfvars、override 文件和 CLI 配置的原因,以及为什么必须提交 .terraform.lock.hcl。
Terraform.gitignore 的重点在于防止处理基础设施代码的仓库泄露状态与机密。Terraform 状态文件以明文保存资源属性,其中可能包含数据库密码或密钥。
此模板不会忽略 .terraform.lock.hcl。HashiCorp 建议将这个依赖锁定文件纳入版本控制。
逐条规则详解
| 模式 | 忽略什么,为什么忽略 |
|---|---|
.terraform/ | 本地工作目录其中存放 terraform init 下载的 provider 二进制文件和模块,以及后端配置。它们是按操作系统区分的二进制文件,无法共享,而且体积很大。 |
*.tfstate*.tfstate.*.terraform.tfstate.lock.info | 状态文件记录实际基础设施与代码之间对应关系的文件。其中以明文包含敏感信息,而且多人各持一份副本会导致状态不一致。应放在 S3、Terraform Cloud 等远程后端并加锁。 |
*.tfvars*.tfvars.json | 变量值文件存放各环境取值和机密的文件。模板注释也说明其中很可能包含密码或私钥。 |
override.tfoverride.tf.json*_override.tf*_override.tf.json | override 文件在本地临时覆盖资源配置的文件。如果要提交,请像模板注释那样以 !example_override.tf 的形式恢复。 |
crash.logcrash.*.log | 崩溃日志Terraform 异常退出时留下的日志,可能包含配置内容。 |
.terraformrcterraform.rc | CLI 配置CLI 配置文件,其中可能包含 Terraform Cloud 的认证令牌。 |
实践中的注意事项
- 提交
.terraform.lock.hcl。这样所有人都会用相同的 provider 版本和哈希进行初始化。 - 需要共享的默认变量请放在
variables.tf的default或示例文件(terraform.tfvars.example)中,而不是*.auto.tfvars。*.tfvars规则不会忽略以.example结尾的文件。 - 用
terraform plan -out=tfplan生成的计划文件同样包含敏感信息,因此像模板注释那样添加*tfplan*规则更安全。 - 如果状态文件已经被提交,在从仓库中删除的同时,还要更换其中包含的所有机密。
原始模板
Terraform.gitignore
# Local .terraform directories.terraform/# .tfstate files*.tfstate*.tfstate.*# Crash log filescrash.logcrash.*.log# Exclude all .tfvars files, which are likely to contain sensitive data, such as# password, private keys, and other secrets. These should not be part of version# control as they are data points which are potentially sensitive and subject# to change depending on the environment.*.tfvars*.tfvars.json# Ignore override files as they are usually used to override resources locally and so# are not checked inoverride.tfoverride.tf.json*_override.tf*_override.tf.json# Ignore transient lock info files created by terraform apply.terraform.tfstate.lock.info# Include override files you do wish to add to version control using negated pattern# !example_override.tf# Include tfplan files to ignore the plan output of command: terraform plan -out=tfplan# example: *tfplan*# Ignore CLI configuration files.terraformrcterraform.rc# Optional: ignore graph output files generated by `terraform graph`# *.dot# Optional: ignore plan files saved before destroying Terraform configuration# Uncomment the line below if you want to ignore planout files.# planout
模板来源: github/gitignore/Terraform.gitignore @356fd7b (2026-09-11) · CC0-1.0