Search code examples
google-cloud-platformterraformterraform-provider-gcp

How to prevent Terraform plan from reporting changes for GCP key rotation?


I have set up a Terraform configuration to rotate GCP keys for multiple service accounts. The keys are rotated daily and stored as GitLab environment variables.

resource "time_rotating" "gcp_sa_private_key_rotation" {
  rotation_days = var.private_key_rotation_days
}

resource "google_service_account_key" "gcp_sa_private_key" {
  service_account_id = var.gcp_service_account_id

  keepers = {
    rotation_time = time_rotating.gcp_sa_private_key_rotation.rfc3339
  }
}

resource "gitlab_group_variable" "gcp_sa_private_key" {
  group = var.gitlab_group_id
  key = var.gitlab_variable_key
  value = google_service_account_key.gcp_sa_private_key.private_key
  protected = true
  masked = true
}

The keys were created successfully, but I have noticed that Terraform plan reports changes for each execution, e.g:

module.my_list_of_accounts["my_service_account"].google_service_account_key.gcp_sa_private_key has been deleted
  - resource "google_service_account_key" "gcp_sa_private_key" {
      - id                 = "my_key_id" -> null
      - keepers            = {
          - "rotation_time" = "2023-03-10T10:04:19Z"
        } -> null
      - key_algorithm      = "KEY_ALG_RSA_2048" -> null
      - name               = "my_key_id" -> null
      - private_key        = (sensitive value)
      - private_key_type   = "TYPE_GOOGLE_CREDENTIALS_FILE" -> null
      - public_key         = "my_public_key_value" -> null
      - public_key_type    = "TYPE_X509_PEM_FILE" -> null
      - service_account_id = "my_service_account_id_value" -> null
      - valid_after        = "2023-03-10T10:04:20Z" -> null
      - valid_before       = "9999-12-31T23:59:59Z" -> null
    }

I have tried running the apply command, but it says that no changes have been detected.

No changes. Your infrastructure matches the configuration.
Terraform has compared your real infrastructure against your configuration
and found no differences, so no changes are needed.

What can I do to prevent Terraform's plan from reporting changes? I want the keys to be rotated only when it's time to rotate.

I tried to execute terraform refresh before terraform plan which resulted in creating a second key.


Solution

  • I have found the reason for the issue - it was on my side. It turns out that the service account I used did not have the roles/iam.serviceAccountViewer role.