Interview Prep/Terraform/State Locking and Backend Errors

Apply finishes all resource changes, then fails with `Failed to save state` and `AccessDenied` mentioning `kms:GenerateDataKey`.

AdvancedTroubleshootingState Locking and Backend Errors
Answer

Likely causes → The bucket uses SSE-KMS with a customer-managed key (kms_key_id in the backend or bucket default encryption). The role can read state (or the old object used a different key) but cannot encrypt new writes.

Diagnose → Look for errored.tfstate in the working directory. Check the key policy and role policy for kms:GenerateDataKey, kms:Encrypt and kms:Decrypt.

aws kms get-key-policy --key-id alias/tfstate --policy-name default

Fix → Grant the KMS permissions, then push the saved state immediately:

terraform state push errored.tfstate

Do not run apply again first; that would work from the old state and duplicate resources.

Prevent → Test backend write permissions in a sandbox stack whenever IAM or KMS policies change.

All Terraform questions Roadmap: Terraform in production

More on State Locking and Backend Errors