Fix Terraform handling of externally revoked access tokens
What
This MR improves the handling of access tokens when they have been revoked externally (outside of Terraform). Before this change, Terraform would not detect or act on the revoked status until the token's scheduled rotation time, at which point the rotation would fail with a 400 Bad request - Token already revoked
error.
│ Error: Error rotating GitLab ProjectAccessToken
│
│ with module.project_gitlab_infra_tools["cmbr"].module.prat_common_ci_tasks_semantic_release[0].gitlab_project_access_token.prat,
│ on .terraform/modules/project_gitlab_infra_tools/modules/access-token/access_token.tf line 1, in resource "gitlab_project_access_token" "prat":
│ 1: resource "gitlab_project_access_token" "prat" {
│
│ Could not rotate GitLab ProjectAccessToken, unexpected error: POST
│ https://gitlab.com/api/v4/projects/<redacted>/access_tokens/13316791/rotate:
│ 400 {message: 400 Bad request - Token already revoked}
Why
When access tokens are revoked outside of Terraform, the provider would not detect this as a difference requiring reconciliation. It would only attempt to rotate the token when approaching its expiration date according to the rotation configuration. This led to two issues:
- Revoked tokens remained in that state, potentially breaking dependent systems until their next scheduled rotation
- When rotation was finally attempted, the operation would fail, requiring manual intervention with
terraform state rm
This issue was particularly disruptive for automated Terraform pipelines, especially when tokens were manually revoked for security reasons.
How
The fix adds a new condition in the ModifyPlan
function across all token resources (project, group, personal, and group service account) that:
- Proactively detects when a token has been revoked externally during plan phase
- Checks if the token is still needed (i.e.
rotation_configuration
is set or the expiry date is in the future) - Marks the token for recreation by adding the
revoked
attribute toRequiresReplace
- Sets planned values for required attributes to clearly report the planned changes
Additionally, comprehensive test cases have been added for each token type to verify this behavior:
- Testing immediate recreation of revoked tokens that are still needed
- Testing non-recreation of revoked tokens that have expired
The changes provide a more graceful user experience, enabling automatic recovery from externally revoked tokens without waiting for rotation time or requiring manual intervention.