Learning center

Rotate a Cloud SQL user's password without failing Cloud Run logins

To rotate a Cloud SQL PostgreSQL password with no failed logins, switch Cloud Run to a second database user first, then change the old user's password. Changing the only user's password in place leaves a window in which some instances hold one password and the database expects the other. How long that window lasts depends on how the revision reads its secret, and pg_stat_activity shows when the old user has stopped connecting.

Why one user leaves a window#

PostgreSQL checks a password when a client connects, so the new password is enforced from the next login onward. Cloud Run delivers the password to the container in one of two ways. A secret exposed as an environment variable is resolved when the instance starts, and an instance keeps that value until it stops. A secret mounted as a volume is fetched from Secret Manager each time the file is read. Client authentication · Secrets in Cloud Run

The two changes, the database user's password and the secret's value, cannot happen at the same instant. Whichever comes first, some connection attempt in between carries the wrong password:

How the revision reads the passwordChange the database firstAdd the secret version first
Environment variable pinned to a versionEvery new connection fails until a revision pinned to the new version serves all trafficNothing changes until that revision deploys, then its new connections fail until the database changes
Environment variable at latestNew connections fail on every instance started before the secret version existed, until those instances stopInstances started after the new version fail until the database changes
Volume at latest, read on each connectNew connections fail until the version existsNew connections fail until the database changes

Google recommends pinning environment-variable secrets to a version number, and Secret Manager's guidance gives the reason: a pinned version can be validated and rolled back with your release process. That also makes the window in the first row the longest. Pinning works well with the two-user rotation below, because each user's password lives in its own pinned version. Secret Manager best practices

On Cloud SQL for MySQL 8.0, gcloud sql users set-password takes --retain-password, which keeps the old password valid beside the new one until --discard-dual-password removes it. The reference marks both flags as MySQL 8.0 only; PostgreSQL has no equivalent there, which is why it needs a second user. gcloud sql users set-password

The rotation with two users#

The service connects as orders_app. Both login users get their table privileges from one group role, orders_rw, so either can serve the application. A member that inherits a role has that role's privileges as soon as it connects. Ownership does not move with membership, though: the owner of a table is the role that created it, and only the owner can alter it. If migrations run as orders_app, give them their own user. Role membership · Privileges and ownership

Step 1 creates a database user, a change to the instance. --database-roles grants existing roles to the new user:

gcloud sql users create orders_app_b \
  --instance orders-db --project shop-prod \
  --database-roles=orders_rw --password="$NEW_PASSWORD"

Unlike set-password, this command takes the password only as --password, so set the variable from a file rather than typing the value into your shell history. Store the same value in a new secret; creating it with data gives it version 1. gcloud sql users create · gcloud secrets create

gcloud secrets create orders-db-password-b --project shop-prod --data-file=PASSWORD_FILE

Grant the revision's service account roles/secretmanager.secretAccessor on the new secret before step 2: Cloud Run checks at deploy time that the service account can access every secret the revision uses. Use secrets

Step 2 deploys a revision that logs in as the new user, with its password pinned to version 1 of the new secret. This creates a revision and, without --no-traffic, moves traffic to it:

gcloud run deploy orders-api --project shop-prod --region europe-west1 \
  --image IMAGE \
  --update-env-vars DB_USER=orders_app_b \
  --update-secrets DB_PASSWORD=orders-db-password-b:1

The old revision keeps DB_USER=orders_app and its own pinned version, and both logins stay valid. A rollback to it still works at this point. --update-secrets

Step 3 waits for orders_app to stop connecting, which the next section checks. Step 4 changes orders_app's password and records it in a new version of its secret, ready for the next rotation, when the roles swap. That step changes the instance, and from then on any revision that still logs in as orders_app with the old version fails at login.

Check: who still logs in with the old password#

Two places answer this. The revisions say which credentials each one is configured with:

gcloud run revisions list --service orders-api \
  --project shop-prod --region europe-west1 \
  --format='table(metadata.name, metadata.creationTimestamp)'

gcloud run revisions describe REVISION \
  --project shop-prod --region europe-west1 \
  --format='yaml(spec.containers[0].env)'

Each secret-backed variable carries valueFrom.secretKeyRef with name, the secret, and key, which is latest, a version number or an alias. A revision that reads latest tells you nothing about its instances; only their start time does. Container env fields

The database says who actually connects. pg_stat_activity has one row per session with usename, application_name and backend_start, the time the client connected. Group the sessions of the old user:

SELECT usename, application_name, count(*) AS sessions,
       min(backend_start) AS oldest, max(backend_start) AS newest
FROM pg_stat_activity
WHERE usename IN ('orders_app', 'orders_app_b')
GROUP BY usename, application_name
ORDER BY usename, newest DESC;

pg_stat_activity

What the query shows for orders_appReading
No sessions, for at least one cycle of every job that uses the databaseChange its password
Sessions with a newest after the traffic moveSomething still opens connections as the old user: the old revision through a tag or a share of traffic, a Cloud Run job, or another service. Find it before step 4
Only sessions older than the traffic moveOld instances that have not stopped. Cloud Run may keep an idle instance, with its open database connections, for up to 15 minutes. Wait for them to stop

An empty application_name hides which client a session belongs to. Setting it from K_REVISION at connect time makes the second column name the revision. Tag connections with their release · Container runtime contract

A worked fixture: one rotation, two outcomes#

The fixture is illustrative. orders-api-00018 connects to shop-prod:europe-west1:orders-db as orders_app, with DB_PASSWORD=orders-db-password:3. At 10:02 UTC the team creates orders_app_b, and at 10:05 deploys orders-api-00019 with DB_USER=orders_app_b and orders-db-password-b:1. Traffic moves fully to orders-api-00019.

Outcome A. The query at 10:14:

usenameapplication_namesessionsoldestnewest
orders_apporders-api-00018209:14:0309:51:40
orders_apporders-export110:10:0210:10:02
orders_app_borders-api-000191410:05:3110:13:52

The two orders-api-00018 sessions predate the traffic move and belong to an instance that has gone idle; they close when it stops. The orders-export session opened at 10:10, after the move. A Cloud Run job named orders-export runs at ten past every hour with DB_USER=orders_app. Changing the password now would fail its next run at 11:10. The team points the job at orders_app_b first and runs the query again after that run.

Outcome B. The query at 11:20 returns rows only for orders_app_b, among them the 11:10 export, still running. At 11:21 the team changes orders_app's password with gcloud sql users set-password and stores it as orders-db-password:4. gcloud sql operations list --instance orders-db records the UPDATE_USER operation at 11:21. The database logs no failed login for orders_app over the next day. orders-api-00018 can no longer serve as a rollback target until it is redeployed with the new version. Cloud SQL operation types

Where the checks mislead#

pg_stat_activity shows the sessions open at the moment you query. A job that runs weekly, or a service that connects only on scale-out, may be absent from every sample. Read the database's failed logins for a day after step 4 as well.

A revision that serves no traffic shows nothing in the query once its idle instances stop, which Cloud Run may delay by up to 15 minutes; a revision-level minimum keeps instances running only while the revision has traffic or a tag. Its configuration still holds the old credentials, and moving traffic back to it after step 4 fails at login. Idle instances · Minimum instances and revisions

If the application caches a password read from a volume, the volume behaves like an environment variable: the instance keeps the value it read first.

If the rotation went wrong and logins already fail, the incident guide reads the failure from the other end: who changed the database password. For where a login failure sits among Cloud SQL connection errors, see the four stages.

Questions#

Does changing a Cloud SQL password disconnect running Cloud Run instances?

PostgreSQL checks the password when a session connects, so sessions opened before the change keep working. The instances fail when their pools open a new connection with the old value, which can happen minutes or hours later.

Should a Cloud Run service read its database password through latest?

With an environment variable, latest is fixed per instance at its start, so a rotation affects instances by start time, not by revision. Google recommends pinning a version and deploying the change. A volume read on each connection follows latest without a deploy.

Can I rotate without a second database user?

On MySQL 8.0, --retain-password keeps both passwords valid for a while. On PostgreSQL, a single user means some connections fail between the two changes, for as long as the table above shows for your setup.

One month of free code review.

New organizations get one calendar month of hosted code review for private and public GitHub repositories. No card or cloud connection required. Eligibility and fair-use terms.

Start free with GitHub

Related reading