Automation, from a shell script to a workflow · Lesson 6 of 8 · about 35 minutes

Rotating a password without downtime

A database password has to change: someone who knew it has left, or it's simply due. The usual way works perfectly until the app next restarts, and then the app is locked out. This lesson shows that happening, then rotates the password with a script that switches the app to a second login, checks it, and only then switches the old one off, with not one failed request.

By the end you'll know

  • Why changing a password in the database can break the app a day later
  • How two logins let you rotate a password with no downtime
  • Why the order of the steps matters, and what to check between them
  • How to keep a new password out of your screen, your history and the list of running commands
  • How to prove "no downtime" instead of hoping for it

Before you start

  • You need: Vagrant and VMware Fusion or VirtualBox, as in Linux Lesson 7, and the practice folder: git clone https://github.com/Kwamib/automation-practice.git, or git pull in it.
  • This lesson uses services from Linux Lesson 7, and a little SQL; the SQL track covers PostgreSQL properly.
  • Where commands run: on your own computer to build the server, then on the server, called db-1.
  • The output below is from real runs on November 19, 2026, just before midnight in New York (04:45 to 04:55 UTC).

The problem: a change that breaks things tomorrow

Apps log in to their database with a username and password. Sooner or later, that password has to change:

  • someone who knew it leaves (Lesson 4's leavers, again)
  • it turns up somewhere it shouldn't, like a chat message, a ticket, or a file in Git
  • a policy says so, every 90 days, say

Changing it is called rotating it, and it's one of the most common causes of self-inflicted outages, for an unexpected reason: the obvious way works perfectly at first. Job listings ask for this as "secrets management" or "credential rotation", and interviews like to ask "how would you rotate a database password without downtime?". This lesson answers that question with a real run.

The server

On your own computer:

BASH
cd ~/Apps/automation-practice/rotate
vagrant up
vagrant ssh
  • vagrant up: builds a server called db-1, and runs setup.sh. That installs PostgreSQL with the bookshop's database, starts the bookshop app on port 8080, and installs the rotation script and a watcher.
  • vagrant ssh: logs you in.

(On the server)

BASH
cd /tmp
curl -s http://127.0.0.1:8080/books
sudo sed 's/PASSWORD=.*/PASSWORD=(hidden)/' /etc/bookshop/db.env
sudo -u postgres psql -c "SELECT rolname, rolcanlogin FROM pg_roles WHERE rolname LIKE 'bookshop%' ORDER BY 1;"
sudo -u postgres psql -c "SELECT usename, application_name FROM pg_stat_activity WHERE application_name = 'bookshop-app';"
OUTPUT
5 books (database login: bookshop_a)
DB_USER=bookshop_a
DB_PASSWORD=(hidden)
  rolname   | rolcanlogin
------------+-------------
 bookshop   | f
 bookshop_a | t
 bookshop_b | f
(3 rows)

  usename   | application_name
------------+------------------
 bookshop_a | bookshop-app
(1 row)
  • cd /tmp: a folder the postgres user can enter, which saves a harmless warning from psql.
  • curl -s URL: asks the app for its book count; -s hides the progress bar. The app says which login it's using.
  • sed 's/PASSWORD=.*/PASSWORD=(hidden)/' FILE: shows the app's settings file with the password hidden. .* means "everything after".
  • sudo -u postgres psql -c "SQL": runs one SQL command as postgres, the database's admin. -u picks the user, and -c gives the command.
  • pg_roles: the database's logins; rolcanlogin is whether each can log in (t true, f false).
  • pg_stat_activity: who's connected right now, and from which app.

The setup is the heart of the lesson: the app has two logins, bookshop_a and bookshop_b, both members of a group, bookshop, which is what can read the books. Only one is switched on at a time. bookshop_a is in use, and bookshop_b waits as the standby. Cloud providers' own rotation tools work the same way, and call it the alternating users approach.

The app keeps one connection open and reuses it, as nearly every real app does. It reads its login from /etc/bookshop/db.env when it starts, and again when it's reloaded (systemctl reload): then it logs in with the new details first, and only swaps over if that works.

watch-app asks the app for its book count five times a second, and reports every request that fails. It turns "no downtime" from a hope into a number.

The usual way

The password needs changing. The obvious command, with the app being watched:

BASH
watch-app 40 > ~/watch-quick.txt &
sleep 2
sudo -u postgres psql -c "ALTER ROLE bookshop_a PASSWORD 'Summer2026';"
sleep 5
curl -s http://127.0.0.1:8080/books
history | tail -4
OUTPUT
[1] 5176
ALTER ROLE
5 books (database login: bookshop_a)
    4  sudo -u postgres psql -c "ALTER ROLE bookshop_a PASSWORD 'Summer2026';"
    5  sleep 5
    6  curl -s http://127.0.0.1:8080/books
    7  history | tail -4
  • watch-app 40 > FILE &: watch the app for 40 seconds, in the background (&), saving the results to a file (>).
  • ALTER ROLE ... PASSWORD '...': change a login's password in the database.
  • history | tail -4: the last 4 commands you typed.

The password changed, and the app is fine. Its connection was opened with the old password before the change, and PostgreSQL doesn't close existing connections when a password changes. Everyone goes home. Two problems are already sitting there:

  • The new password is in your shell history, in plain text, in ~/.bash_history, and in the list of running commands while it ran.
  • The app's settings file still has the old password.

The next day, the app restarts, for a deploy, an update, or a reboot:

BASH
sudo systemctl restart bookshop-app
sleep 3
curl -s -w ' (status %{http_code})\n' http://127.0.0.1:8080/books
journalctl -u bookshop-app --no-pager | tail -2
wait
tail -6 ~/watch-quick.txt
OUTPUT
can't reach the database: connection to server at "127.0.0.1", port 5432 failed: FATAL:  password authentication failed for user "bookshop_a"
 (status 503)
Nov 19 04:54:05 db-1 bookshop-app[5445]: can't log in to the database as bookshop_a: connection to server at "127.0.0.1", port 5432 failed: FATAL:  password authentication failed for user "bookshop_a"
...
04:54:31 FAILED: status 503
04:54:31 FAILED: status 503
04:54:32 FAILED: status 503
watch-app: 172 requests over 40s, 109 failed
  • curl -w ' (status %{http_code})\n': also prints the status code. \n starts a new line.
  • journalctl -u bookshop-app: the app's log; tail -2 keeps the last 2 lines.
  • wait: wait for the background watch-app to finish.

Status 503, "password authentication failed", and 109 of 172 requests failed in the seconds after the restart. It doesn't heal: every request fails until someone works out why. And the person who restarted it isn't the person who changed the password, a day earlier. They see a database error, not "a password changed yesterday", which is why outages like this take so long to fix.

Changing the password in the database first is changing the locks while the staff are still inside. Everyone in the building carries on as normal, so it looks fine. The problem only shows the next morning, when they try to get back in with yesterday's key.

The password that never got set

My first try at this step didn't break anything at all, because the command never ran. The password I chose was Summer2026!:

OUTPUT
-bash: !': event not found

In an interactive Bash shell, ! inside double quotes means "repeat an earlier command" (this is history expansion). !';" made Bash look for an earlier command starting with ';", find none, and refuse to run the whole line. The database never saw it. It's one more reason not to type passwords into commands: a perfectly good password can stop the command that sets it. If you must, use single quotes around the whole command, or switch the feature off with set +H.

The safe way: two logins

The rotation script, rotate-db-password, installed at /usr/local/sbin/rotate-db-password, also on GitHub (opens in a new tab):

BASH
#!/usr/bin/env bash
# rotate-db-password: give the bookshop app a new database password, with no
# downtime, and switch the old one off.
#
#   rotate-db-password            show what it would do (changes nothing)
#   rotate-db-password --apply    do it
#
# The app has two database logins, bookshop_a and bookshop_b, with the same
# permissions. One is in use; the other is the standby. Rotating means:
#   1. give the standby a new password, and switch it on
#   2. test it, doing what the app does
#   3. point the app at it, and reload the app (no restart)
#   4. check the app really switched
#   5. only then, switch the old login off
# If a check fails, it stops, or puts things back as they were.
#
# The new password is never printed, logged or put on a command line.
# Exit codes: 0 rotated, 1 a check failed (and it was undone), 2 called wrongly.
set -euo pipefail

ENV_FILE=${ENV_FILE:-/etc/bookshop/db.env}
APP=${APP:-bookshop-app}
RECORD=${RECORD:-/var/log/db-rotation.log}
who_ran=${SUDO_USER:-$(id -un)}

say() { printf '%s rotate-db-password: %s\n' "$(date -u +%FT%TZ)" "$*" >&2; }
apply=0
case "${1:-}" in
	"") ;;
	--apply) apply=1 ;;
	*) echo "usage: rotate-db-password [--apply]" >&2; exit 2 ;;
esac
[ "$(id -u)" -eq 0 ] || { say "run me with sudo"; exit 2; }

# SQL as the database's admin user. The SQL goes in on standard input, so
# nothing secret ever appears in the list of running commands.
sql() { runuser -u postgres -- psql -X -q -t -A -v ON_ERROR_STOP=1 -d bookshop; }

current=$(sed -n 's/^DB_USER=//p' "$ENV_FILE")
case "$current" in
	bookshop_a) standby=bookshop_b ;;
	bookshop_b) standby=bookshop_a ;;
	*) say "refusing: $ENV_FILE says DB_USER=$current, which isn't bookshop_a or bookshop_b"; exit 2 ;;
esac
in_use=$(echo "SELECT string_agg(DISTINCT usename, ',') FROM pg_stat_activity WHERE application_name = '$APP';" | sql)
say "the app is set to use $current, and is connected as: ${in_use:-nobody}"
say "the plan: new password for $standby, test it, switch the app to it, check, then switch $current off"
if [ "$apply" -eq 0 ]; then
	say "dry run: nothing was changed. Add --apply to do it."
	exit 0
fi

# 1. A new password for the standby login. 32 random characters, made by
#    Python's secrets module, safe to put in SQL and in a file.
new=$(python3 -c 'import secrets; print(secrets.token_urlsafe(24))')
say "1. giving $standby a new password, and switching it on"
printf "ALTER ROLE %s WITH LOGIN PASSWORD '%s';\n" "$standby" "$new" | sql

# 2. Test it the way the app uses it: log in over the network, and read the books.
say "2. testing $standby: logging in, and reading the books table"
if ! books=$(PGPASSWORD="$new" psql -X -t -A -h 127.0.0.1 -U "$standby" -d bookshop -c 'SELECT count(*) FROM books' 2>&1); then
	say "CHECK FAILED: $standby can't do what the app needs: $books"
	echo "ALTER ROLE $standby NOLOGIN PASSWORD NULL;" | sql
	say "switched $standby off again; the app and $current were never touched"
	exit 1
fi
say "   $standby can read the books table ($books books)"

# 3. Point the app at the new login: write the file in one step, keep the old
#    one to roll back to, and reload the app. A reload, not a restart: the app
#    logs in again in the background, and swaps over only if that works.
say "3. pointing the app at $standby, and reloading it"
install -m 600 "$ENV_FILE" "$ENV_FILE.previous"
tmp=$(mktemp "${ENV_FILE%/*}/.db.env-XXXXXX")
printf 'DB_USER=%s\nDB_PASSWORD=%s\n' "$standby" "$new" >"$tmp"
chown --reference="$ENV_FILE" "$tmp"
chmod --reference="$ENV_FILE" "$tmp"
mv -f "$tmp" "$ENV_FILE"
systemctl reload "$APP"

# 4. Check the app really switched: connected as the new login, and answering.
say "4. checking the app switched"
switched=0
for _ in 1 2 3 4 5 6 7 8 9 10; do
	sleep 1
	now=$(echo "SELECT string_agg(DISTINCT usename, ',') FROM pg_stat_activity WHERE application_name = '$APP';" | sql)
	if [ "$now" = "$standby" ] && curl -fsS -m 3 http://127.0.0.1:8080/health >/dev/null; then
		switched=1
		break
	fi
done
if [ "$switched" -eq 0 ]; then
	say "CHECK FAILED: the app is connected as '${now:-nobody}', not $standby. Putting things back."
	mv -f "$ENV_FILE.previous" "$ENV_FILE"
	systemctl reload "$APP"
	sleep 2
	echo "ALTER ROLE $standby NOLOGIN PASSWORD NULL;" | sql
	say "rolled back: the app is set to use $current again, and $standby is switched off"
	printf '%s FAILED rotation from %s to %s (rolled back), run by %s\n' "$(date -u +%FT%TZ)" "$current" "$standby" "$who_ran" >>"$RECORD"
	exit 1
fi
say "   the app is connected as $standby, and answering"

# 5. Only now, switch the old login off, and end any sessions still using it.
say "5. switching $current off"
echo "ALTER ROLE $current NOLOGIN PASSWORD NULL;
SELECT count(pg_terminate_backend(pid)) FROM pg_stat_activity WHERE usename = '$current';" | sql >/dev/null
rm -f "$ENV_FILE.previous"

printf '%s rotated from %s to %s, run by %s\n' "$(date -u +%FT%TZ)" "$current" "$standby" "$who_ran" >>"$RECORD"
say "done: the app uses $standby with a new password, and $current can't log in"

The order is the whole idea:

StepWhatIf it fails
1Give the standby login a new password, and switch it on. The login in use isn't touched.Nothing has changed for the app
2Test it the way the app uses it: log in over the network, and read the booksSwitch the standby off again; the app was never touched
3Write the new login to the app's settings file in one step, keep the old one, and reload the app (not restart)Step 4 notices
4Check the app really switched: connected as the new login, and answeringPut the old file back, reload, switch the standby off
5Only now, switch the old login off, and end any sessions still using it

At every moment, the app has a login that works. Before step 3, it's the old one, untouched. After step 3, it's the new one, tested. The old one is only switched off once the app is provably not using it.

The details that make it safe:

  • The password never appears anywhere a person or program could see it. It's made by Python's secrets module (secrets.token_urlsafe(24): 32 random characters, safe in SQL and in a file). It's sent to PostgreSQL through standard input (printf ... | sql), not as part of a command, so it never appears in the list of running commands. It's never printed or logged. PGPASSWORD passes it to the test login in the environment, which only root can read.
  • runuser -u postgres -- psql -X -q -t -A -v ON_ERROR_STOP=1: run psql as the database admin. -X ignores personal settings files, -q is quiet, -t -A prints bare values with no table borders, and ON_ERROR_STOP=1 stops at the first error rather than carrying on.
  • The test is the app's real work, SELECT count(*) FROM books, not just "can it log in". A login that can log in but can't read the books would pass the second test and take the app down.
  • The settings file is replaced in one step (mktemp in the same folder, then mv, as in Lesson 1), with the same owner and permissions as the old one (chown --reference, chmod --reference).
  • A reload, not a restart. ExecReload=/bin/kill -HUP $MAINPID in the app's service sends it a signal, and the app logs in with the new details in the background, swapping over only if that works. A restart would drop every request for a moment.
  • "Did it switch?" is checked in the database itself, in pg_stat_activity, not just by asking the app.
  • ALTER ROLE ... NOLOGIN PASSWORD NULL switches the old login off and removes its password. pg_terminate_backend ends any session still using it.

Get out of the hole

The app is down, from the usual way. The script doesn't need it to be healthy; it needs a working standby:

BASH
watch-app 20 > ~/watch-recover.txt &
sleep 2
sudo rotate-db-password --apply
wait
tail -4 ~/watch-recover.txt
curl -s http://127.0.0.1:8080/books
OUTPUT
2026-11-19T04:54:56Z rotate-db-password: the app is set to use bookshop_a, and is connected as: nobody
2026-11-19T04:54:56Z rotate-db-password: the plan: new password for bookshop_b, test it, switch the app to it, check, then switch bookshop_a off
2026-11-19T04:54:56Z rotate-db-password: 1. giving bookshop_b a new password, and switching it on
2026-11-19T04:54:56Z rotate-db-password: 2. testing bookshop_b: logging in, and reading the books table
2026-11-19T04:54:56Z rotate-db-password:    bookshop_b can read the books table (5 books)
2026-11-19T04:54:56Z rotate-db-password: 3. pointing the app at bookshop_b, and reloading it
2026-11-19T04:54:56Z rotate-db-password: 4. checking the app switched
2026-11-19T04:54:57Z rotate-db-password:    the app is connected as bookshop_b, and answering
2026-11-19T04:54:57Z rotate-db-password: 5. switching bookshop_a off
2026-11-19T04:54:57Z rotate-db-password: done: the app uses bookshop_b with a new password, and bookshop_a can't log in
04:54:56 FAILED: status 503
04:54:56 FAILED: status 503
04:54:56 FAILED: status 503
watch-app: 92 requests over 20s, 10 failed
5 books (database login: bookshop_b)

"Connected as: nobody" is the outage, seen from the database. Within a second, the app was on bookshop_b and answering. All 10 failures came before the switch, at 04:54:56, while the app was still down from the restart, and none after.

A rotation on a healthy app

On a fresh server, with the app working, a rotation and then another, which swaps the two logins back:

BASH
watch-app 30 > ~/watch-rotate.txt &
sleep 2
sudo rotate-db-password --apply
wait
tail -3 ~/watch-rotate.txt
OUTPUT
2026-11-19T04:46:47Z rotate-db-password: 1. giving bookshop_b a new password, and switching it on
...
2026-11-19T04:46:48Z rotate-db-password: done: the app uses bookshop_b with a new password, and bookshop_a can't log in
watch-app: 137 requests over 30s, 0 failed
...
2026-11-19T04:48:03Z rotate-db-password: done: the app uses bookshop_a with a new password, and bookshop_b can't log in
watch-app: 141 requests over 30s, 0 failed

Two rotations, 278 requests, not one failed. That's what "without downtime" means, measured. Afterwards:

BASH
sudo -u postgres psql -c "SELECT rolname, rolcanlogin FROM pg_roles WHERE rolname LIKE 'bookshop%' ORDER BY 1;"
sudo cat /var/log/db-rotation.log
OUTPUT
  rolname   | rolcanlogin
------------+-------------
 bookshop   | f
 bookshop_a | t
 bookshop_b | f
(3 rows)

2026-11-19T04:46:48Z rotated from bookshop_a to bookshop_b, run by vagrant
2026-11-19T04:48:03Z rotated from bookshop_b to bookshop_a, run by vagrant

One login on, one off, and a record of each rotation and who ran it, with no password anywhere in it.

A rotation that stops itself

Rotations go wrong when the standby login isn't quite the same as the one in use. Here, someone has removed bookshop_b from the bookshop group, so it can log in but can't read the books:

BASH
sudo -u postgres psql -c "REVOKE bookshop FROM bookshop_b;"
sudo rotate-db-password --apply; echo "exit $?"
curl -s http://127.0.0.1:8080/books
sudo -u postgres psql -c "GRANT bookshop TO bookshop_b;"
OUTPUT
REVOKE ROLE
2026-11-19T04:48:41Z rotate-db-password: 1. giving bookshop_b a new password, and switching it on
2026-11-19T04:48:41Z rotate-db-password: 2. testing bookshop_b: logging in, and reading the books table
2026-11-19T04:48:41Z rotate-db-password: CHECK FAILED: bookshop_b can't do what the app needs: ERROR:  permission denied for table books
2026-11-19T04:48:41Z rotate-db-password: switched bookshop_b off again; the app and bookshop_a were never touched
exit 1
5 books (database login: bookshop_a)
GRANT ROLE
  • REVOKE bookshop FROM bookshop_b: takes bookshop_b out of the group that can read the books. GRANT puts it back.
  • echo "exit $?": the exit code of the command before it.

The test caught it at step 2, before the app was touched. A test that only checked "can it log in?" would have passed, switched the app over, and taken it down. Test what the app actually does.

Clean up

BASH
exit

(On your own computer)

BASH
vagrant destroy -f

In real life

  • Use a secrets manager where you can: AWS Secrets Manager, HashiCorp Vault and others store the password, hand it to the app, and can run rotations like this one on a schedule. They use the same two-login idea. The AWS track covers Secrets Manager.
  • Make apps reloadable, or run two copies behind a load balancer and restart them one at a time. Either way, no request needs to see a gap.
  • Never type a password into a command. It ends up in your history and in the list of running commands. psql can ask for one without showing it: \password bookshop_a.
  • Check the database's logging. If PostgreSQL logs every statement (log_statement = 'all'), an ALTER ROLE ... PASSWORD goes into its log in plain text.
  • Rotate after every leaver who knew the password, and on a schedule too, so rotating is routine rather than an emergency.
  • Restart the app after a rotation, in a quiet moment, to prove the new login also works from a cold start.

Spot the problem

Work out what's wrong before you read the explanation.

"The rotation worked. Why did the 2am report fail?" A team rotates the bookshop database's password with this script. Every check passes, watch-app shows no failures, and the old login is switched off. That night, the finance report fails: "password authentication failed for user bookshop_a". What's wrong? The report script is a second user of the same login, with its own copy of the old password in its own settings file. The rotation switched the app over, then switched the old login off, which broke everything else that used it. pg_stat_activity only shows who's connected right now, and the report only connects at 2am. The fix: give every program its own login, so rotating one can't break another. And before switching an old login off, find everything that uses it: search the servers' settings for it, and look in the database's connection logs over a full day, not a moment.

Keep this

ToUse
Run SQL as the database adminsudo -u postgres psql -c "SQL"
List logins, and whether they can log inSELECT rolname, rolcanlogin FROM pg_roles;
Who's connected, and from whatSELECT usename, application_name FROM pg_stat_activity;
Give a login a new password and switch it onALTER ROLE NAME WITH LOGIN PASSWORD '...';, sent on standard input
Switch a login offALTER ROLE NAME NOLOGIN PASSWORD NULL;
End a login's sessionsSELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE usename = 'NAME';
Give or take a group's permissionsGRANT GROUP TO NAME;, REVOKE GROUP FROM NAME;
A random passwordpython3 -c 'import secrets; print(secrets.token_urlsafe(24))'
Set a password without showing it, in psql\password NAME
Make a service re-read its settingsExecReload=/bin/kill -HUP $MAINPID, then systemctl reload NAME
Stop ! breaking a commandSingle quotes around it, or set +H

Where you are now

You changed a password the usual way and watched it work, then fail completely at the next restart: 109 failed requests and an error that points nowhere near the cause. You've seen a ! stop a password being set at all. And you've rotated it properly, with a second login, a test of the app's real work, a reload instead of a restart, and a check in the database before the old login was switched off: 278 requests, none failed. The script also got you out of the outage in a second, and stopped itself when the standby couldn't do the job. Lesson 7 moves from servers to the work on everyone's desk: a weekly report built from a folder of spreadsheets, in Python.

Check yourself

  1. After ALTER ROLE changed the password, why did the app keep working?

  2. Why does the script use two logins, bookshop_a and bookshop_b?

  3. The standby could log in but couldn't read the books. What happened?

  4. Why does the script reload the app instead of restarting it?

  5. The command with the password Summer2026! printed 'event not found'. Why?

  6. Where does the script's new password end up?

Key terms

  • Rotating a password: replacing it with a new one, and making the old one stop working.
  • Alternating users: rotating with two logins that take turns: one in use, one on standby.
  • Standby login: the second login, switched off until the next rotation.
  • Reload: telling a running program to read its settings again, without stopping it.
  • Connection: an open session between the app and the database. It stays logged in even if the password then changes.
  • History expansion: Bash's feature that treats ! as "an earlier command".
  • Secrets manager: a service that stores passwords for programs, hands them out, and can rotate them.

Go deeper