Cleanup of service account secrets using Cloud Function
Overview
The Cloud Function deletes old keys for a GCP service account and updates the required secret data for all service account secrets stored in the Secret Manager. The function is triggered by a Cloud Scheduler job.
Cloud Scheduler starts the Cloud Function.
For each secret stored in Secret Manager:
The Cloud Function checks if the value of the type label is set to service-account. If not, it stops running.
The Cloud Function checks if the value of the skip-cleanup label is not set to true. If not, it stops running.
The Cloud Function reads the name of the service account from the latest version of a secret.
The Cloud function checks if the latest secret version is older than the time in hours set in the age GET parameter. If not, it stops running.
The Cloud Function removes old versions of keys for the service account.
The Cloud Function removes old versions of a secret stored in Secret Manager.
Cloud Function deployment
To deploy Cloud Function follow these steps:
Run go mod vendor inside the development/gcp/cloud-functions/rotateserviceaccount/ directory.
Create the secret-manager-notifications Pub/Sub topic if it does not exist.
Create the service-${PROJECT_NUMBER}@gcp-sa-secretmanager.iam.gserviceaccount.com service account with the roles/pubsub.publisher role if it does not exist.
Use the following command to deploy the Cloud Function: