🔐

Terraform で statelock を解除する

2021/07/23に公開

概要

Terraform のバックエンドとしてtfstateを S3 にし statelock を DynamoDB で使っています.あるタイミングで変更をterraform applyしようとして誤っている箇所を見つけたのでキャンセルした後、terraform planをしたらError: Error acquiring the state lockというメッセージがでました.

ターミナルイメージ

 % terraform apply
Terraform will perform the following actions:

~中略~

Plan: 0 to add, 1 to change, 0 to destroy.

Do you want to perform these actions?
  Terraform will perform the actions described above.
  Only 'yes' will be accepted to approve.

  Enter a value: ^C^CERRO[0051] got 3 SIGTERM/SIGINTs, forcing shutdown      

% terraform plan 
╷
│ Error: Error acquiring the state lock
│ 
│ Error message: ConditionalCheckFailedException: The conditional request failed
│ Lock Info:
│   ID:        xxxx-xxxx-xxxx-xxxx-xxxx
│   Path:      xxx/xxx.tfstate
│   Operation: OperationTypeApply
│   Who:       xxxx@xxxx
│   Version:   1.0.3
│   Created:   2021-07-23 02:55:43.1115469 +0000 UTC
│   Info:      
│ 

対応

調べてみると,ロック状態になってしまい上記のようにterraform plan/applyなどできなくなるためロックを解除する必要があります.terraform force-unlock を実行すれば解除ができます.ドキュメントによると,ロックを解除してインフラも変更しないコマンドとのことです.

Manually unlock the state for the defined configuration.

This will not modify your infrastructure. This command removes the lock on the state for the current configuration. The behavior of this lock is dependent on the backend being used. Local state files cannot be unlocked by another process.

% terraform force-unlock xxxx-xxxx-xxxx-xxxx-xxxx(ID 情報)
Do you really want to force-unlock?
  Terraform will remove the lock on the remote state.
  This will allow local Terraform commands to modify this state, even though it
  may be still be in use. Only 'yes' will be accepted to confirm.

  Enter a value: yes

Terraform state has been successfully unlocked!

The state has been unlocked, and Terraform commands should now be able to
obtain a new lock on the remote state.

ロックを解除後,terraform plan/applyが成功するようになりました.

% terraform plan
~中略~

Plan: 0 to add, 1 to change, 0 to destroy.

───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────

Note: You didn't use the -out option to save this plan, so Terraform can't guarantee to take exactly these actions if you run "terraform apply" now.
% terraform apply
~中略~

Plan: 0 to add, 1 to change, 0 to destroy.

Do you want to perform these actions?
  Terraform will perform the actions described above.
  Only 'yes' will be accepted to approve.

  Enter a value: yes

~中略~
Apply complete! Resources: 0 added, 1 changed, 0 destroyed.

まとめ

初めての体験で勉強になったため備忘録として残します.

参考情報

https://qiita.com/tomy103rider/items/b1dec92aaa57b9af31d9
https://www.terraform.io/docs/cli/commands/force-unlock.html

Discussion