本地状态无法被 terraform 上的另一个进程解锁

问题描述 投票:0回答:4

我的 terraform 远程状态和储物柜是在 aws 帐户下的 s3 和 dynamodb 上配置的,在 gitlab runner 上,某些计划任务已崩溃,在下一个执行计划中会弹出以下错误:

Error: Error locking state: Error acquiring the state lock: ConditionalCheckFailedException:
The conditional request failed

Lock Info:
  ID:        <some-hash>
  Path:      remote-terrform-states/app/terraform.tfstate
  Operation: OperationTypePlan
  Who:       root@runner-abc-project-123-concurrent-0
  Version:   0.14.10
  Created:   2022-01-01 00:00:00 +0000 UTC
  Info:  some really nice info

在尝试解锁此储物柜以便再次执行其他执行计划时 - 我收到以下错误:

  terraform force-unlock <some-hash-abc-123>

  #output:
  Local state cannot be unlocked by another process

我们如何释放这个地形储物柜?

terraform amazon-dynamodb locker tfstate
4个回答
16
投票

根据terraform命令参考:

force-unlock

手动解锁已定义配置的状态。

这不会修改您的基础设施。该命令删除 锁定当前配置的状态。这种行为 锁取决于所使用的后端。 本地状态文件不能 被另一个进程解锁。

说明:显然执行计划正在本地处理计划输出文件并应用于 terraform 步骤的第二阶段,如下例所示:

第一阶段:

terraform plan -out execution-plan.out

第二阶段:

terraform apply -input=false execution-plan.out

确保第 1 阶段和第 2 阶段的文件名相同

但是 - 如果第 1 阶段被终止或意外崩溃,锁定器将被分配给本地状态文件,因此必须在 dynamodb 本身上删除,而不是使用 terraform 强制解锁命令。

解决方案:在 dynamodb terraform lockers 表下找到此特定项目并显式删除锁定的项目,您可以使用 aws 控制台或通过 api 执行此操作。 例如:

aws dynamodb delete-item \
    --table-name terraform-locker-bucket \
    --key file://key.json

key.json的内容:

{
 "LockID": "remote-terrform-states/app/terraform.tfstate",
 "Info": {
   "ID":"<some-hash>",
   "Operation":"OperationTypePlan",
   "Who":"root@runner-abc-project-123-concurrent-0",
   "Version":"0.14.10",
   "Created":"2022-01-01 00:00:00 +0000 UTC",
   "Info":"some really nice info"
   }
 }

6
投票

terraform force-unlock <lock id>

对于 terragrunt,在

<terragruntfile>.hcl
目录中,运行
terragrunt force-unlock <lock id>
。如果不起作用,请删除
terragrunt.lock.hcl
.terragrunt-cache/
,然后重试。

还有


3
投票

如果您使用 Terragrunt 并且可以看到锁定是针对特定模块的,您可以执行以下操作:

  1. 导航到该模块的相关 terragrunt 目录
  2. 运行 terragrunt 强制解锁
  3. 输入“是”确认

现在应该可以在本地和远程解锁。


0
投票

这是我的案例。我使用 Circleci,并将 Terraform-plan 作为我工作流程中的一项工作。由于 Terraform 状态被锁定,作业失败。我尝试在 terraform-plan 下添加

terraform force-unlock
作为命令,但它无法完成这项工作。

所以我做了什么。我的应用程序根目录中有一个

infrastructure
目录,其中包含 Terraform 配置。在目录下面有两个文件
.terraform.lock.hcl
main.tf
,其中包含一些配置,包括 Terraform 后端,在我的例子中它是“s3”。所以我只好在这个目录下调用unlock命令:

cd infrastructure/dev
terraform force-unlock '<lock_id>' 

可以在错误消息中找到lock_id,当它说状态已锁定时。

请注意,即使您不使用 Circleci,您也应该拥有此目录。

我希望它对某人有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.