执行Terraform Plan时遇依赖锁定文件不一致错误求助
问题还原
执行terraform plan时触发以下错误:
Error: Inconsistent dependency lock file
The following dependency selections recorded in the lock file are inconsistent with the current configuration:
provider registry.terraform.io/hashicorp/aws: required by this configuration but no version is selected
provider registry.terraform.io/hashicorp/null: required by this configuration but no version is selected
To make the initial dependency selections that will initialize the dependency lock file, run:
terraform init
同时terraform providers输出显示,状态中的null Provider使用了旧命名空间registry.terraform.io/-/null,与配置中的registry.terraform.io/hashicorp/null不匹配。
解决方案
1. 初始化依赖并更新锁文件
直接执行错误提示中的命令,重新生成符合当前配置的依赖锁文件:
terraform init
2. 迁移旧的null Provider命名空间
由于状态中的null Provider是旧版本的无厂商命名空间,需要将其替换为官方的hashicorp命名空间:
terraform state replace-provider registry.terraform.io/-/null registry.terraform.io/hashicorp/null
3. 重新初始化并验证
再次执行初始化确保所有依赖匹配:
terraform init
之后运行terraform plan即可正常执行。
原因说明
- 锁文件不一致是因为当前配置引用的AWS、null Provider未在
.terraform.lock.hcl中记录版本,terraform init会自动选择兼容版本并更新锁文件。 - 状态中的null Provider使用旧命名空间,与配置中的官方命名空间冲突,导致依赖校验失败,必须通过
state replace-provider命令修正状态中的引用。
内容的提问来源于stack exchange,提问作者fahri

