Terraform apply は成功したのに state の保存が 403 になった(backend に readonly のプロファイルが残っていた)
Terraform apply は成功したのに state の保存が 403 になった(backend に readonly のプロファイルが残っていた)
S3 バックエンドの Terraform で、terraform apply のリソース作成は成功したのに、最後の state の保存だけが 403 で失敗した。原因と戻し方のメモ。
起きたこと
aws_iam_user.app: Creation complete after 1s [id=...]
aws_iam_user_policy_attachment.app_administrator: Creation complete after 0s [id=...]
│ Error: Failed to save state
│
│ Error saving state: failed to upload state: operation error S3: PutObject, https response error StatusCode: 403,
│ ... api error AccessDenied: User: <ReadOnlyAccess の SSO ロール>
│ is not authorized to perform: s3:PutObject on resource: "<state のバケット>/terraform.tfstate"
│ Error: Failed to persist state to backend
│ ... the state has been written to the file "errored.tfstate" in the current working directory.リソースは AWS 上に作られている。S3 の state にだけ書けておらず、手元に errored.tfstate が残った。
原因
同じ作業ディレクトリで、以前 plan を流すために次の init をしていた。
terraform init -backend-config="profile=<readonly-profile>"-backend-config で渡したプロファイルは .terraform/terraform.tfstate に保存され、以降の init を打ち直すまで残る。apply のときは AWS_PROFILE に write のプロファイルを入れていたので、provider(リソースの作成)は write で動いた。backend(state の読み書き)だけが readonly のプロファイルのままで、s3:PutObject が拒否された。
残っているかは次で見られる。null なら、プロファイルの指定は残っていない。
jq '.backend.config.profile' .terraform/terraform.tfstate戻し方
apply は打ち直さない。打ち直すと state が分岐する(Terraform のエラーにもそう出る)。
terraform init -reconfigure # backend の設定を作り直す(プロファイルの指定が消える)
terraform state push errored.tfstate # 保存できなかった state を S3 に書く
terraform plan -target=<apply した対象> # No changes. になることを確かめる
rm errored.tfstateinit -reconfigure は backend の設定を作り直すだけで、state の移行や上書きはしない。state push は、S3 にある state より serial が新しいので、そのまま通った。