Skip to content

SSH Key Rotation With Ansible: Step-by-Step Guide, Updated for 2026

Built from Thomas Nyambati’s two Medium articles (Rack Brains Africa, Sep 6 and Sep 9, 2018) and his code repository. It walks the manual, Bash and Ansible methods, flags each place where 2018 advice no longer holds, and adds a tested modern playbook that adds the new key, verifies it, and only then removes the old one.

PDF: Download this guide (PDF)

At a glance

Metric Value Detail
Manual, Bash, Ansible 3 methods Same recipe each time: create, add, test, then remove
Rollout and rollback 5 lab tests Happy path, re-run, second rotation, failure before and after removal
Suggested cryptoperiod 1 to 2 years NIST SP 800-57 Part 1 Rev. 5, Table 1, private authentication keys
DSA removed OpenSSH 10.0 Released April 9, 2025; disabled in 7.0 (2015) and at build time in 9.8 (2024)
Source, Part 1 Thomas Nyambati, “Automate SSH Key Rotation With Ansible part 1”, Rack Brains Africa on Medium, Sep 6, 2018. Public. medium.com/rackbrains/automate-ssh-key-rotation-with-ansible-part-1-a99934d2dfc9
Source, Part 2 Thomas Nyambati, “Automate SSH Key Rotation With Ansible part 2”, Sep 9, 2018. Public. medium.com/rackbrains/automate-ssh-key-rotation-with-ansible-part-2-7c6f599dd086
Code github.com/rackbrainz/automate-ssh-key-rotation-with-ansible, which now redirects (HTTP 301) to github.com/menionlabs/automate-ssh-key-rotation-with-ansible. Last commit 19becda, Sep 11, 2018. MIT licensed.
How you sent it Two Medium print-outs as PDFs. The code in the articles is images, so this guide takes code from the repo and text from the live articles.
Guide type Steps 1 to 10 follow the series, fixed where it is out of date. Steps 11 to 15 are Beyond the source.

Read this first

Do not run the 2018 recipe unchanged on real servers. Its Bash defaults delete the new key along with the old one, its playbook removes every other key when exclusive is on, and nothing tests the new key before the old one goes. Practise in a disposable lab, and use the Step 11 playbook, which adds, verifies, then removes.

How the pieces fit

The safe order of operations, and where the series stops short.

flowchart LR
  a(["1. Generate new Ed25519 key"])
  b["2. Add new public key<br/>Old key stays"]
  c{"3. Verify login with only the new key"}
  d["4. Remove old key<br/>Exact key, nothing else"]
  e["5. Confirm new works, old is refused"]
  f["Roll back: remove the new key<br/>Old key never touched"]
  g(["Done: promote the new key"])
  a --> b
  b --> c
  c -->|"Pass"| d
  c -.->|"Fail"| f
  d --> e
  e --> g
Method in the series Source Where it stops short Step
Manual: ssh-keygen, ssh-copy-id, test, sed Part 1 Fine for one host; sed removal is fragile; no check that the test can fail 4 to 7
Bash: bin/rotate-keys.sh Part 2, Bash section Default match string deletes the new key; no test step; no rollback 8
Ansible: ssh-key-rotation.yml Part 2, Ansible sections Shared key, plain-text passphrase, exclusive removal, no verify 9 and 10
Modern playbook (added) Beyond the source Tested only on unprivileged lab hosts 11 and 12
SSH certificates (added) Beyond the source Needs a CA you can protect and audit 14

Where the 2018 series departs from today

Each row was checked against a current source on Dec 3, 2026, or tested in my lab.

Topic What the series says What I found Verdict
Key type Part 1: -t can be ‘DSA or RSA’; use 4096 bits DSA was disabled by default in OpenSSH 7.0 (2015), at build time in 9.8 (2024) and removed in 10.0 (Apr 2025); ssh-keygen -t dsa fails on 10.0p2. Ed25519 is the default since 9.5. The current manual lists ecdsa, ed25519, mldsa44-ed25519 and rsa (RSA default 3072). Update: use Ed25519
Lab image Part 1: ubuntu/trusty64 Ubuntu 14.04: standard support ended Apr 2019, Ubuntu Pro May 2024, paid legacy add-on to May 2029. Canonical stopped Vagrant boxes with 24.04; HCP Vagrant shuts down Dec 31, 2026. Replace
Module name Part 2: authorized_key The module is ansible.posix.authorized_key. The short name still resolved on ansible-core 2.22.1 with the collection installed, but ansible-lint flags it (fqcn). Use the full name
Idempotent keygen Part 2: the command task will not regenerate an existing key True for the repo code, which sets creates:; the second run reported ok. But it only checks that a file exists, and a same-path re-run never rotates. community.crypto.openssh_keypair is the purpose-built module. Holds, with limits
Exclusive Part 2: set is_exclusive to yes to remove old keys Lab: exclusive: true removed a second admin’s key and the connection key, leaving one key. Stage the change: add, verify, then remove by key. Risky
Passphrases Part 1: demo passphrase is weak; Part 2: move variables for security The repo keeps a passphrase in plain vars: and on the command line; Ansible -v printed it. Use Vault or a secrets manager. NISTIR 7966 notes automated keys are normally unencrypted and hard-coded passphrases add little. Fix
ssh-copy-id and sed Part 1 and Part 2 Bash: sed on the comment Lab: a short comment deleted both keys; a dot in the pattern matched another key. ssh-copy-id is interactive and only appends. Match the key body. Fragile
-o and KDF rounds Not mentioned in the series New key format is the default since OpenSSH 7.8 (2018). -o is still accepted. The current manual’s default is 32 KDF rounds (24 before the 10.6p1 release), relevant only with a passphrase. Note
Testing the new key Part 1: add to ssh-agent, then ssh Lab: a multiplexed session opened with the old key accepted a bogus key. The agent can also supply the old key. Use IdentitiesOnly, IdentityAgent=none and ControlPath=none. Could mislead
Certificates Not covered OpenSSH CA-signed certificates with short validity: tested, accepted when valid, rejected when expired or for the wrong principal. Consider
Standards Not covered NIST SP 800-57 Part 1 Rev. 5 (cryptoperiods, key states), NISTIR 7966 (SSH key management), CIS Ubuntu 24.04 v2.0.0 section 5.1 (server hardening, no user-key rotation item). Added

Step 1. Know what you are rotating: SSH keys and authorized_keys

From the source Part 1, “How does SSH work?”
What it is SSH is the encrypted remote-login protocol. A key pair has a private half that never leaves your machine and a public half that you append to ~/.ssh/authorized_keys on each server. The server lets in anyone who can prove they hold a private key whose public half is listed.
Why it matters Rotation means changing which public keys that file trusts. If you do not know exactly which keys are in it, you cannot rotate safely.
  1. List what the server trusts today — On a test host run ssh-keygen -lf ~/.ssh/authorized_keys. It prints one fingerprint and comment per key, so you know what you are replacing.
  2. Name the owner of every key — A key with no owner is a candidate for removal, not for copying forward (NISTIR 7966 section 5.4).
  3. Use the right file name — The article writes ~/ssh/authorized_keys; the real path is ~/.ssh/authorized_keys.

Common mistakes

  • ✗ Assuming a key with no comment is yours. The comment is a label anyone can edit; only the key body and fingerprint identify it.
  • ✗ Skipping the inventory and rotating blind. You will find the forgotten key only when something breaks.

Beyond the source

  • Public keys are not secret, but private keys must never be shared between people. A shared private key means you cannot tell who logged in.
  • OpenSSH has treated Ed25519 as its default key type since version 9.5 (October 2023), so a new key from a current client is already Ed25519 (OpenSSH 9.5 release notes).

  • ssh-keygen manual (OpenBSD) — man.openbsd.org

  • NISTIR 7966, section 3.4 and 5.4 — csrc.nist.gov

Step 2. Decide why and how often to rotate

From the source Part 1, “Why does rotating ssh keys matter?” and “Rotating ssh keys”
What it is The author gives three reasons: compromised keys from current users, keys of people who left, and idle keys. He says rotate on a defined cycle chosen by your own security and audit policy, and that rotation does not replace policies for how keys are shared and stored.
Why it matters A key that is never removed is a permanent credential. Rotation caps how long a stolen or forgotten key stays useful.
  1. Set a cycle — NIST SP 800-57 Part 1 Rev. 5, section 5.3.6 and Table 1 suggest a private authentication key cryptoperiod of no more than one to two years, depending on environment and sensitivity. Tighten it for privileged automation.
  2. Add event triggers to the calendar cycle — Rotate at once on offboarding, role change, suspected leak, or loss of a laptop. NISTIR 7966 section 5.2 makes termination of access part of the key life cycle.
  3. Remove idle keys, not just old ones — NISTIR 7966 section 5.4 suggests watching logs for 6 to 12 months to find keys that are never used, then removing those nobody approves.
  4. Write down the three-step recipe — Create a new key, add its public half, test it, then remove the old key. Every step below follows that order.

Common mistakes

  • ✗ Treating rotation as the only control. The article says so itself: policies on how keys are shared and secured still matter.
  • ✗ Rotating on a schedule but never removing the old key. That adds a key instead of replacing one.

Beyond the source

  • NIST SP 800-57 Part 1 Rev. 5 section 7 describes key states: pre-activation (new key added, not yet relied on), active, deactivated (old key removed), compromised and destroyed. Delete the old private key at the end, once your retention rules allow it.
  • A cycle is a policy choice, not a law. The 1 to 2 year figure is NIST’s suggestion for private authentication keys, not an SSH requirement.

  • NIST SP 800-57 Part 1 Rev. 5 — csrc.nist.gov

  • NISTIR 7966 (October 2015) — csrc.nist.gov

Step 3. Build a disposable lab, but not on trusty64

From the source Part 1, “Pre-requisites” and “Setting up vagrant”
What it is The author uses Vagrant and VirtualBox with the ubuntu/trusty64 box, a private network address 192.168.33.12 and the hostname octo, so he can rotate keys on a throwaway server.
Why it matters Key rotation can lock you out. Practise on a machine you can destroy.
  1. Pick a current guest, not Ubuntu 14.04 — Ubuntu 14.04 left standard security maintenance in April 2019, Ubuntu Pro coverage ended May 2024, and only a paid legacy add-on runs to May 2029 (Ubuntu security maintenance schedule).
  2. Check the box host first — Canonical stopped publishing Vagrant boxes starting with Ubuntu 24.04, and HashiCorp’s HCP Vagrant registry is decommissioned on December 31, 2026. Any box you rely on must be re-hosted or replaced.
  3. Or skip Vagrant — Any disposable VM or container with a current OpenSSH works. For this guide I ran unprivileged OpenSSH servers on 127.0.0.1, ports 2222 to 2226 (code below), so every claim could be tested without touching a real machine.
  4. Keep the host-key prompt on outside the lab — The lab turns host-key checking off to stay throwaway. Production runs must keep it on.

A throwaway sshd for testing (one host). Replace the paths; run it as a normal user.

ssh-keygen -q -t ed25519 -N '' -f hostkey
cat > sshd_config <<EOF
Port 2222
ListenAddress 127.0.0.1
HostKey $PWD/hostkey
PidFile $PWD/sshd.pid
AuthorizedKeysFile $PWD/authorized_keys
PasswordAuthentication no
KbdInteractiveAuthentication no
UsePAM no
StrictModes no
EOF
/usr/sbin/sshd -f sshd_config -D &

Common mistakes

  • ✗ Copying the Vagrantfile from the repo. It still pins ubuntu/trusty64, an end-of-life release.
  • ✗ Testing on a real server first because the lab felt like extra work. The lockout described in Step 10 happened in my lab on the first draft of the playbook.

Beyond the source

  • Your lab must mirror one production detail: where sshd looks for keys (AuthorizedKeysFile). Hosts that read /etc/ssh/authorized_keys/%u break any playbook that edits ~/.ssh.
  • I could not confirm which OpenSSH version trusty64 ships, so this guide does not claim one.
  • My lab ran sshd from an extracted Debian openssh-server package, with SshdSessionPath and SshdAuthPath lines pointing at it. A system-installed sshd does not need those two lines.

  • Ubuntu security maintenance schedule — ubuntu.com

  • Ubuntu release cycle — ubuntu.com
  • Vagrant on Ubuntu public images — ubuntu.com
  • Deprecation of HCP Vagrant — developer.hashicorp.com

Step 4. Generate the new key pair

From the source Part 1, “Generating SSH Keys”
What it is The author runs ssh-keygen with -t (type, “DSA or RSA”), -b 4096, -C (comment), -N (passphrase), and -f (output path), producing octo-ssh-key and octo-ssh-key.pub.
Why it matters The new key is the thing that will replace the old one, so type, strength and passphrase decide how long the new key stays safe.
  1. Choose Ed25519 — ssh-keygen -t ed25519 is the default on OpenSSH 9.5 and later. Ed25519 keys are small and fast and have no size to choose. RSA is still supported (default 3072 bits); 4096 is not wrong, only larger and slower.
  2. Never choose DSA — OpenSSH disabled ssh-dss at run time in 7.0 (2015), at build time in 9.8 (2024), and removed it in 10.0 (April 2025). On OpenSSH 10.0p2 my ssh-keygen -t dsa answered unknown key type dsa.
  3. Use a passphrase for human keys, typed at the prompt — Leave out -N. A passphrase on the command line is visible in shell history and in Ansible’s verbose output (I saw it in -v output).
  4. Label every key with its purpose and date — -C rotation-2026-12@octo gives an audit trail without being used to match keys later.
  5. Store it with the right permissions — Private key mode 0600, in a 0700 directory. ssh refuses a private key that others can read.

Modern equivalent of the article’s command. You will be asked for a passphrase.

ssh-keygen -t ed25519 -C "rotation-2026-12@octo" -f ~/.ssh/octo-2026-12

Common mistakes

  • ✗ Copying the article’s -t DSA or RSA advice. DSA is gone from current OpenSSH.
  • ✗ Using the author’s demo passphrase (weak by his own admission) or any passphrase in a script.
  • ✗ Generating on the server. The private key should be created where it will be used, never copied through a chat or ticket.

Beyond the source

Step 5. Add the new public key to the server

From the source Part 1, “Add the Public key to the authorized keys file”
What it is The author uses ssh-copy-id -i to log in to the server and append the new public key to authorized_keys, noting that editing the file by hand would not scale to many machines.
Why it matters The server must trust the new key before the old one is removed. Adding first is what keeps you from being locked out.
  1. Append, never replace — The old key must stay valid until the new key is proven. ssh-copy-id appends, which is the safe behaviour.
  2. Use ssh-copy-id for a one-off human key — It prompts, so it suits a person, not a script. Run it once per host and check the output says the key was added.
  3. Use the Ansible module for fleets — ansible.posix.authorized_key with state: present and exclusive: false adds a key idempotently. Step 11 does this.
  4. Check the file afterwards — ssh-keygen -lf ~/.ssh/authorized_keys should now list both fingerprints.

One-off add for a human key. The old key is untouched.

ssh-copy-id -i ~/.ssh/octo-2026-12.pub vagrant@192.168.33.12
ssh vagrant@192.168.33.12 'ssh-keygen -lf ~/.ssh/authorized_keys'

Common mistakes

  • ✗ Adding the key with an editor over a session and saving a broken file. One bad character in authorized_keys can reject every key in it.
  • ✗ Using exclusive mode for the add. It removes every other key and is the fastest way to lock yourself out (Step 10).

Beyond the source

  • I did not run ssh-copy-id in my lab, because it writes to the default ~/.ssh/authorized_keys and my lab used custom paths. The description above comes from its documented behaviour.
  • Consider restricting the new key as you add it, with a source address (from="203.0.113.0/24") or restrict. NISTIR 7966 recommends command and source restrictions wherever possible. I did not test these options in the lab.

  • ansible.posix.authorized_key — docs.ansible.com

  • NISTIR 7966, section 5.4 (restrictions) — csrc.nist.gov

Step 6. Test the new key before touching the old one

From the source Part 1, “Test the new key and replace the old ones”
What it is The author runs ssh-add to load the new private key into the agent, enters the passphrase, and then runs ssh vagrant@192.168.33.12 to prove the new key works.
Why it matters This is the only check between you and an outage. If it can pass for the wrong reason, the next step locks you out.
  1. Test with only the new key — ssh -i NEWKEY -o IdentitiesOnly=yes -o IdentityAgent=none -o ControlPath=none -o BatchMode=yes user@host true. Each option removes a way for the old key to answer for the new one.
  2. Read the exit code — 0 means the new key logged in. 255 with Permission denied (publickey) means it did not, so stop.
  3. Prove the test can fail — Run it once with a key you know is not installed. It must be rejected. A check that cannot fail is not a check.
  4. Keep a second session open — For manual work, leave an already-open session to the host until the whole rotation is verified.

A strict one-key test. Use the same flags for the old key afterwards and expect a rejection.

ssh -i ~/.ssh/octo-2026-12 -p 22 \
  -o IdentitiesOnly=yes -o IdentityAgent=none -o ControlPath=none \
  -o BatchMode=yes -o PasswordAuthentication=no \
  vagrant@192.168.33.12 true && echo "NEW KEY OK"

Common mistakes

  • ✗ Testing with a plain ssh user@host while the agent still holds the old key. The old key logs you in and you conclude the new key works.
  • ✗ Testing through a multiplexed connection. In my lab, with ControlMaster auto set as in the author’s ssh.config, a connection using a bogus key logged in successfully by riding an existing session opened with the old key. With ControlPath=none the same bogus key was rejected.

Beyond the source

  • The author’s repo ssh.config sets ControlMaster auto and ControlPersist 15m. That is handy for speed, but an open master can also stay alive after you remove the old key, so it can hide a lockout for up to 15 minutes. Close it with ssh -O exit or disable multiplexing for the check.
  • Verify from the same machine and account that will use the key. A test from your laptop does not prove the build server can log in.

  • ssh_config: IdentitiesOnly, ControlPath — man.openbsd.org

Step 7. Remove the old key safely

From the source Part 1, “Test the new key and replace the old ones” (the sed command)
What it is The author deletes the old key with a remote sed -i.bak '/vagrant/d' ~/.ssh/authorized_keys, matching the key’s comment (vagrant) as its unique identifier, and keeps a .bak copy.
Why it matters Removal is what makes this a rotation. Until the old key is gone, a stolen copy still works.
  1. Match the key body, not the comment — A comment is free text and matches loosely. The base64 body (second field) is unique to the key.
  2. Back up first, then write a new file — Copy authorized_keys, build the filtered file next to it, check it is not empty, then move it into place.
  3. Test again after removal — The new key must still log in, and the old key must now be refused.
  4. Destroy the old private key when policy allows — Keep it for rollback until the check passes, then delete it from every machine that had a copy.

Remove one key by its body. Run on the server, or wrap in ssh.

OLD=$(cut -d' ' -f2 old-key.pub)        # the unique base64 body
cp -p ~/.ssh/authorized_keys ~/.ssh/authorized_keys.pre-rotation
grep -vF -- "$OLD" ~/.ssh/authorized_keys > ~/.ssh/authorized_keys.new \
  && test -s ~/.ssh/authorized_keys.new \
  && chmod 600 ~/.ssh/authorized_keys.new \
  && mv ~/.ssh/authorized_keys.new ~/.ssh/authorized_keys

Common mistakes

  • ✗ Matching on a short comment. In my test, deleting lines containing ubuntu removed both the old key (comment ubuntu) and the new key (comment ubuntu@203.0.113.10), leaving an empty file.
  • ✗ Using a dot in the pattern. In sed the dot matches any character, so deploy@ci.example.com also removed deploy@ciXexample.com.
  • ✗ Leaving authorized_keys.bak behind. It holds the old key you meant to retire.

Beyond the source

  • The repo’s Bash script makes the first mistake by default (Step 8).
  • The one-liner below keeps a dated backup and refuses to replace the file if the filtered result is empty. I tested the grep on a local file; I did not run it over SSH.

  • GNU sed: regular expressions — gnu.org

Step 8. Script it in Bash, then see where it breaks

From the source Part 2, “Automating the process with Bash Scripts”; repo file bin/rotate-keys.sh
What it is bin/rotate-keys.sh reads options with getopts (-u user, -h host, -b bits, -c comment, -t type, -f path, -p passphrase, -k unique key), fills defaults, then runs three functions: generate the key, ssh-copy-id it, and delete the old key with sed.
Why it matters It shows the manual recipe as code, and shows why the author stops here: a script that loops over hundreds of hosts gets hard to maintain.
  1. Read the three functions as the three steps — Generate (ssh-keygen), add (ssh-copy-id), remove (remote sed). Part 2 calls them generateNewSshKeyPair, addNewSshPublicKey and removeOldPublicKey; the final repo names the first generateNewSshKey and has no sanityCheck function, with the defaults inline in main().
  2. Note the defaults — User ubuntu, 4096 bits, type rsa, passphrase equal to the user name, and the match string for removal equal to the user name.
  3. Do not run it as is — Use it to learn the order. The defaults and the lack of a test step make it unsafe; the fixes are in Step 11.

Common mistakes

  • ✗ Leaving the defaults. The comment defaults to ubuntu@HOST and the removal pattern defaults to ubuntu, so sed deletes the new key too (shown in Step 7).
  • ✗ Setting the passphrase to the username, or passing -p on the command line.
  • ✗ Trusting set -e. It stops on an error but does not roll back, so a failure after the add can leave two keys, and a failure after the sed can leave none.
  • ✗ Never testing the new key before the sed runs. The script goes straight from add to remove.

Beyond the source

  • Unquoted tests such as [ -z ${DOMAIN} ] misbehave if a value contains spaces. Quote them.
  • The repo is at commit 19becda (September 11, 2018), two days after Part 2. I could not see the code images inside your PDFs, so where this guide quotes code it quotes the repo, and the article text may differ in small ways.

  • automate-ssh-key-rotation-with-ansible (repo, now menionlabs) — github.com

  • ShellCheck — shellcheck.net

Step 9. Move to Ansible: configuration and inventory

From the source Part 2, “Automating the process with Ansible Scripts” and “Setup Ansible configuration”
What it is An ansible/ folder holds ansible.cfg (SSH arguments), ssh.config (keep-alive and connection sharing), and inventory.ini (host 192.168.33.12 in group octo, user vagrant). The author checks it with an Ansible ping.
Why it matters Ansible runs the same steps on many hosts, in parallel or in batches, and reports what changed.
  1. Install current tooling — I used ansible-core 2.22.1 with community.crypto 3.6.0 and ansible.posix 2.2.2. Install the collections with ansible-galaxy collection install community.crypto ansible.posix.
  2. Write the inventory with explicit connection settings — Set ansible_user and ansible_ssh_private_key_file per group. Use ansible_user, not the older ansible_ssh_user alias the repo uses.
  3. Keep host-key checking on — Pre-populate known_hosts. The lab turns it off only because its host keys are throwaway.
  4. Ping with the modern name — ansible all -m ansible.builtin.ping proves the control node can log in and run Python before you change any key.

A minimal inventory for the lab (adapt the addresses and key path).

[octo]
192.168.33.12

[octo:vars]
ansible_user=vagrant
ansible_ssh_private_key_file=~/.ssh/octo-current

Common mistakes

  • ✗ Copying ssh.config’s ControlPersist 15m into a rotation workflow without closing masters. See Step 6.
  • ✗ Skipping the ping. A broken connection found in the middle of a rotation is a lockout risk.

Beyond the source

Step 10. Read the author’s playbook, and fix it

From the source Part 2, “Generate ssh key”, “Add the Generated SSH public key to the authorized_keys file” and “Remove old ssh Public Keys”; repo file ansible/ssh-key-rotation.yml
What it is One play on the octo host with three tasks: run ssh-keygen through the command module on localhost, read the public key with lookup('file', ...), and add it with authorized_key as root. A variable is_exclusive decides whether other keys are removed; flipping it to yes removes them.
Why it matters It turns the three-step recipe into code. It also shows why a literal translation of a manual recipe is not yet safe.
  1. Notice what creates: does — The repo’s keygen task has args: creates: on the key path. On my second run Ansible reported ok, not changed, so the author’s claim that it will not regenerate an existing key holds for the repo code. It only tests that the file exists, so it never checks type, size or passphrase, and a repeat run with the same path never rotates anything.
  2. Replace it with a key module — community.crypto.openssh_keypair reads the existing key and, with regenerate: never, refuses to replace it. It supports ed25519 and sets file mode and comment.
  3. Replace exclusive with a per-key removal — state: absent with the old key removes exactly that key. In my lab, exclusive: true also removed a second admin’s key and the key Ansible was connected with.
  4. Take the passphrase out of vars — The repo’s playbook keeps a passphrase in plain vars:. The author says to move it to a separate file for security. Use Ansible Vault or a secrets manager, and see Step 13 for the trade-off.
  5. Lint the playbook — Run ansible-lint. The repo playbook produced 5 findings (three missing fully qualified module names, two truthy values). The modern playbook passes the production profile.

Common mistakes

  • ✗ Flipping is_exclusive to yes on a host where other people or tools log in. Their keys vanish with the old one. It is also per loop iteration: with a loop, each pass removes the previous pass’s key.
  • ✗ Using one shared key for the whole fleet. One leak then opens every host, and rotation becomes all-or-nothing. The modern playbook makes one key per host.
  • ✗ Running the add task as root when the login user can edit its own file. Least privilege applies to the rotation tool too.
  • ✗ Re-running a playbook that rotates onto the key it connects with. In my first draft that removed the only working key and locked me out of all my lab hosts; the final playbook skips hosts already on the new key.

Beyond the source

  • authorized_key still resolves under its short name: ansible-doc authorized_key and an ad-hoc run both worked on ansible-core 2.22.1 with ansible.posix installed. But the module belongs to ansible.posix, and ansible-lint flags the short name (fqcn[action]). Use the fully qualified name.
  • Part 2 says it mentions an Ansible Galaxy role with more features. I could not identify it, so nothing here relies on it.
  • Hard-coding the author’s passphrase is ‘for demo only’, but the repo is public. Treat any credential that has appeared in a public repo as spent.

  • community.crypto.openssh_keypair — docs.ansible.com

  • ansible-lint rules (fqcn, yaml) — ansible.readthedocs.io
  • Protecting sensitive data with Ansible Vault — docs.ansible.com

Step 11. Run the modern rotation playbook (Beyond the source)

From the source Beyond the source. Built from Part 2’s playbook and tested in my lab.
What it is A playbook that makes one Ed25519 key per host with community.crypto.openssh_keypair, adds it, proves a login with only the new key, removes only the old key, and proves the old key is refused. A serial rollout limits the blast radius, and a rescue block rolls back.
Why it matters It fixes the weak points above: no embedded passphrase, no exclusive wipe, no remove-before-verify, no shared key, and a built-in way to stop and undo.
  1. Set the connection key per host — ansible_ssh_private_key_file must point at the key Ansible uses today. The playbook reads it as the old key and its .pub file as the key to remove.
  2. Run the canary — ansible-playbook rotate-ssh-keys.yml -e rotation_id=2026-12 -l canary-host rotates one host. rotation_id is a label that names the new key file.
  3. Run the fleet in batches — -e rotation_serial=1 rotates one host at a time. A list such as [1, 5, "25%"] goes canary, then five, then a quarter at a time.
  4. Read the proof tasks — ‘Verify a fresh login using ONLY the new key’ and ‘Prove the OLD key is rejected now’ are the checks that matter. If either fails, the run stops.
  5. Promote the new key — The last task writes host_vars so the next run starts from the new key. Back up the keys directory, which is not in git, and delete retired private keys once policy allows.

rotate-ssh-keys.yml, exactly as tested.

---
# rotate-ssh-keys.yml: rotate one Ed25519 automation key per host.
# Per host: ADD new key -> VERIFY it works -> REMOVE old key -> PROVE the old key is dead.
# Needs:  ansible-galaxy collection install community.crypto ansible.posix
# Run:    ansible-playbook rotate-ssh-keys.yml -e rotation_id=2026-12 -e rotation_serial=1
- name: Rotate SSH automation keys (add, verify, then remove)
  hosts: "{{ rotation_hosts | default('all') }}"
  gather_facts: false
  serial: "{{ rotation_serial | default(1) }}"   # canary first; a list such as [1, 5, "25%"] also works
  any_errors_fatal: true                          # a failure stops this batch and every later batch
  vars:
    rotation_key_dir: "{{ playbook_dir }}/keys"   # control node only; keep out of git
    rotation_new_key: "{{ rotation_key_dir }}/{{ inventory_hostname }}-{{ rotation_id }}"
    rotation_comment: "ansible-rotation-{{ rotation_id }}@{{ inventory_hostname }}"
    rotation_extra_ssh_args: []                   # lab only: host-key options for a throwaway lab
    rotation_old_key_removed: false
    # One login probe, reused three times. No agent, no multiplexing, exactly one key.
    rotation_probe_argv: >-
      {{ ['ssh', '-i', probe_key, '-p', (ansible_port | default(22) | string), '-l', ansible_user,
          '-o', 'IdentitiesOnly=yes', '-o', 'IdentityAgent=none', '-o', 'BatchMode=yes',
          '-o', 'PasswordAuthentication=no', '-o', 'ControlMaster=no', '-o', 'ControlPath=none',
          '-o', 'ConnectTimeout=10'] + rotation_extra_ssh_args
         + [ansible_host | default(inventory_hostname), 'true'] }}

  tasks:
    - name: Require a rotation id
      ansible.builtin.assert:
        that: rotation_id is defined
        fail_msg: "Pass -e rotation_id=<label>, for example 2026-12"
        quiet: true

    - name: Pin the current (old) key now and read its public half (fails early if missing)
      ansible.builtin.set_fact:
        rotation_old_key: "{{ ansible_ssh_private_key_file }}"
        rotation_old_pubkey: "{{ lookup('ansible.builtin.file', ansible_ssh_private_key_file ~ '.pub') }}"

    - name: Skip hosts already rotated to this id (makes a re-run safe)
      ansible.builtin.meta: end_host
      when: rotation_old_key == rotation_new_key

    - name: Create the key directory on the control node (0700)
      ansible.builtin.file:
        path: "{{ rotation_key_dir }}"
        state: directory
        mode: "0700"
      delegate_to: localhost
      run_once: true

    - name: Generate a new Ed25519 key pair for this host
      community.crypto.openssh_keypair:
        path: "{{ rotation_new_key }}"
        type: ed25519
        comment: "{{ rotation_comment }}"
        mode: "0600"
        regenerate: never                         # never silently replace a key that exists
      delegate_to: localhost
      register: new_keypair

    - name: Add the new key, verify it, then remove the old key
      block:
        - name: Add the new public key (the old key stays valid)
          ansible.posix.authorized_key:
            user: "{{ ansible_user }}"
            key: "{{ new_keypair.public_key }}"
            state: present
            exclusive: false
            path: "{{ authorized_keys_path | default(omit) }}"      # omit = ~/.ssh/authorized_keys
            manage_dir: "{{ authorized_keys_path is not defined }}"

        - name: Verify a fresh login using ONLY the new key
          ansible.builtin.command:
            argv: "{{ rotation_probe_argv }}"
          vars:
            probe_key: "{{ rotation_new_key }}"
          delegate_to: localhost
          changed_when: false
          register: verify_new
          retries: 3
          delay: 2
          until: verify_new.rc == 0

        - name: Remove the old public key (exact key match, other keys untouched)
          ansible.posix.authorized_key:
            user: "{{ ansible_user }}"
            key: "{{ rotation_old_pubkey }}"
            state: absent
            path: "{{ authorized_keys_path | default(omit) }}"
            manage_dir: "{{ authorized_keys_path is not defined }}"

        - name: Remember that the old key is gone
          ansible.builtin.set_fact:
            rotation_old_key_removed: true

        - name: Confirm the new key still logs in after the removal
          ansible.builtin.command:
            argv: "{{ rotation_probe_argv }}"
          vars:
            probe_key: "{{ rotation_new_key }}"
          delegate_to: localhost
          changed_when: false

      rescue:
        - name: ROLLBACK before removal | take the new key back out
          ansible.posix.authorized_key:
            user: "{{ ansible_user }}"
            key: "{{ new_keypair.public_key }}"
            state: absent
            path: "{{ authorized_keys_path | default(omit) }}"
            manage_dir: "{{ authorized_keys_path is not defined }}"
          when: not rotation_old_key_removed

        - name: ROLLBACK after removal | put the old key back, connecting with the new key
          ansible.posix.authorized_key:
            user: "{{ ansible_user }}"
            key: "{{ rotation_old_pubkey }}"
            state: present
            path: "{{ authorized_keys_path | default(omit) }}"
            manage_dir: "{{ authorized_keys_path is not defined }}"
          vars:
            ansible_ssh_private_key_file: "{{ rotation_new_key }}"
            ansible_ssh_args: -o ControlMaster=no -o ControlPath=none
          when: rotation_old_key_removed

        - name: Stop this run
          ansible.builtin.fail:
            msg: >-
              Rotation failed on {{ inventory_hostname }} and was rolled back.
              {{ 'Old key restored.' if rotation_old_key_removed else 'New key removed; old key untouched.' }}

    - name: Prove the OLD key is rejected now
      ansible.builtin.command:
        argv: "{{ rotation_probe_argv }}"
      vars:
        probe_key: "{{ rotation_old_key }}"
      delegate_to: localhost
      changed_when: false
      failed_when: old_key_probe.rc == 0
      register: old_key_probe

    - name: Promote the new key for the next run (host_vars next to the playbook)
      ansible.builtin.copy:
        dest: "{{ playbook_dir }}/host_vars/{{ inventory_hostname }}.yml"
        content: |
          ---
          ansible_ssh_private_key_file: "{{ rotation_new_key }}"
        mode: "0600"
      delegate_to: localhost

Run it (canary first, then the fleet).

ansible-galaxy collection install community.crypto ansible.posix
ansible-playbook rotate-ssh-keys.yml -e rotation_id=2026-12 -l web-canary
ansible-playbook rotate-ssh-keys.yml -e rotation_id=2026-12 -e rotation_serial="[1,5,'25%']"

Common mistakes

  • ✗ Using the host-key options in rotation_extra_ssh_args. They are for a throwaway lab, not production.
  • ✗ Pointing authorized_keys_path at a file sshd does not read. In my lab, a host whose sshd read a different file made the verify step fail and triggered the rollback, as designed.
  • ✗ Using a plain ping or wait_for_connection for the verify. Ansible normally multiplexes its SSH connections, and a multiplexed session can answer for the wrong key (I showed this with plain ssh, not with ansible ping). The playbook uses a direct ssh probe with multiplexing off, so the result does not depend on that.

Beyond the source

  • Lab results (ansible-core 2.22.1, OpenSSH 10.0 on Debian 13): the happy path rotated 2 hosts and the old keys were rejected afterwards; a re-run with the same id changed nothing; a second rotation chained correctly from the promoted key; a verify failure on the first host rolled back and left the next hosts untouched; a simulated failure after removal restored the old key through the new one.
  • The playbook is a template. I tested it against unprivileged sshd processes, not against hosts that need become, bastions, or non-OpenSSH servers.

  • ansible.posix.authorized_key (state absent, exclusive, manage_dir) — docs.ansible.com

  • community.crypto.openssh_keypair — docs.ansible.com
  • Blocks and rescue — docs.ansible.com

Step 12. Roll out in batches, with a rollback plan (Beyond the source)

From the source Beyond the source. Ansible strategies page and lab tests.
What it is Ansible serial finishes the whole play on a batch of hosts before starting the next, and any_errors_fatal: true stops everything when one host fails.
Why it matters A bad assumption, such as an sshd that ignores your file, should hit one host, not the fleet.
  1. Start with a canary — A list such as [1, 5, "25%"] is documented: one host, then five, then batches of a quarter.
  2. Choose canaries that look like the rest — Include one host of each OS and each sshd configuration, because the failure is usually a difference.
  3. Know the rollback for each stage — See the table below. The playbook automates stages 2 and 3.
  4. Keep a way in that is not SSH — A cloud serial console, hypervisor console or out-of-band management is your break-glass access. Test it before the rotation.

Common mistakes

  • ✗ Using a large serial to finish faster. A failed batch still means that many hosts to repair.
  • ✗ Skipping any_errors_fatal. Without it, a failed host does not stop the other hosts in its batch.
  • ✗ Rolling back by hand without checking which key each host now trusts.

Beyond the source

  • Ansible’s documentation says serial changes the scope of failures to the batch size. max_fail_percentage can relax that.
  • NISTIR 7966 section 5.4 says to back up SSH configurations before changes so you can roll back quickly.

  • Controlling playbook execution: serial and strategies — docs.ansible.com

Step 13. Protect secrets and the key store (Beyond the source)

From the source Beyond the source. Part 2 says to move variables out of the playbook ‘for security reasons’.
What it is Decide where the rotation private keys live, who can read them, and what protects them.
Why it matters The rotation key is a master credential for every host it can reach.
  1. Keep keys off git and chat — The keys directory is 0700, files 0600, and ignored by git.
  2. Encrypt at rest — Put the control node’s disk or the keys directory on encrypted storage, or keep the keys in a secrets manager and fetch them for the run.
  3. Use Ansible Vault for anything in a playbook — Vault encrypts variables and files. Never put a passphrase in vars: or in a command line.
  4. Restrict what the key can do — Use from= and restrict options on the authorized key where you can, and a dedicated rotation account.
  5. Understand the passphrase trade-off — NISTIR 7966 notes that automated keys are usually unencrypted because nobody is present to type a passphrase, and that hard-coding a passphrase in a script adds little security. A key in an agent or a secrets manager is better than a passphrase in a file.

Common mistakes

  • ✗ Writing a passphrase into vars, an inventory or a command line. Ansible prints commands in -v output and logs.
  • ✗ Treating no_log as encryption. It hides output; it does not protect the file.
  • ✗ Keeping retired private keys forever. A retired key that still exists is a liability.

Beyond the source

  • The OWASP Secrets Management Cheat Sheet covers rotation, access control and auditing of secrets generally.
  • My playbook does not set a passphrase: the generated key is unencrypted, mode 0600. That is the common automation pattern NISTIR 7966 describes, and its protection is file permissions, disk encryption and the account that can read the file.

  • OWASP Secrets Management Cheat Sheet — cheatsheetseries.owasp.org

  • Ansible Vault guide — docs.ansible.com

Step 14. Consider SSH certificates instead of rotating keys (Beyond the source)

From the source Beyond the source. Not covered in Part 1 or Part 2.
What it is OpenSSH can trust a certificate authority (CA) instead of individual keys. You sign a user’s public key with the CA key, set who it is for (principals) and how long it is valid, and the server accepts it if it trusts the CA.
Why it matters With short-lived certificates, expiry does the removal for you. There is no authorized_keys sweep and no old key to forget.
  1. Make a CA key and guard it — ssh-keygen -t ed25519 -f user_ca. The CA private key is the crown jewel; keep it offline or in an HSM or managed signer.
  2. Tell sshd to trust it — Set TrustedUserCAKeys /etc/ssh/user_ca.pub in sshd_config on each server.
  3. Sign a user key for a short time — ssh-keygen -s user_ca -I alice-2026-12-03 -n box -V +1h alice.pub writes a certificate valid for one hour for principal box.
  4. Log in with the certificate — ssh picks up alice-cert.pub next to the key, or pass -o CertificateFile.
  5. Plan revocation — Use ssh-keygen -k key revocation lists and keep certificate lifetimes short enough that revocation rarely matters.

The commands used in the lab test (principal and path are examples).

ssh-keygen -t ed25519 -N '' -C my-user-ca -f user_ca
# sshd_config on the server:
#   TrustedUserCAKeys /etc/ssh/user_ca.pub
ssh-keygen -s user_ca -I alice-$(date +%F) -n alice -V +1h alice.pub
ssh-keygen -L -f alice-cert.pub          # inspect principals and validity
ssh -i alice -o CertificateFile=alice-cert.pub alice@server

Common mistakes

  • ✗ Issuing long-lived certificates. That recreates the old key problem with an extra component.
  • ✗ Skipping logging. Without a record of what the CA signed, you cannot answer who has access. NISTIR 7966 (2015) warns that most environments had no tracking of issued OpenSSH certificates; a signer with audit logs fixes that.
  • ✗ Putting the CA key on a laptop or build server.

Beyond the source

  • Lab results on OpenSSH 10.0: a certificate valid for 5 minutes was accepted; an expired certificate was rejected; a certificate for a different principal was rejected; the same key without a certificate was rejected.
  • A CA means one more system to run and protect. For a handful of hosts, per-host rotation as in Step 11 may be simpler.

  • ssh-keygen: CERTIFICATES — man.openbsd.org

  • NISTIR 7966 (certificates note) — csrc.nist.gov

Step 15. Make rotation routine: inventory, schedule, audit (Beyond the source)

From the source Beyond the source. NISTIR 7966 sections 5.2 to 5.5; NIST SP 800-57 Part 1 Rev. 5.
What it is Wrap the playbook in a repeatable process: a key inventory, a schedule, and evidence.
Why it matters A rotation you run once is a demo. A rotation with an owner, a date and a log is a control.
  1. Keep an inventory of keys and owners — One row per key: owner, host, purpose, creation date, next rotation date.
  2. Schedule the cycle and the events — Calendar rotation at a cycle you choose (NIST suggests one to two years for private authentication keys), plus rotation on offboarding or suspected exposure.
  3. Collect evidence — Keep the playbook output: which hosts rotated, the new fingerprints, and the old-key rejection check.
  4. Find keys outside the process — Compare each host’s authorized_keys against the inventory and investigate extras, as NISTIR 7966 describes for orphan keys.
  5. Automate carefully — Run from a CI job or scheduler you trust with the rotation key, and require a human approval for the fleet stage.

Common mistakes

  • ✗ Rotating only on a calendar and ignoring offboarding.
  • ✗ Not testing restore. If the control node’s keys directory is lost, rotation becomes a lockout.
  • ✗ Treating CIS Benchmarks as a rotation policy. The CIS Ubuntu Linux 24.04 LTS Benchmark v2.0.0 (May 28, 2026), section 5.1, hardens the SSH server (host key file permissions, root login, key exchange algorithms, and more). I found no item about rotating user keys in its table of contents.

Beyond the source

  • I read the CIS benchmark through a third-party mirror, because CIS’s own downloads need registration. Check the version you are audited against.

  • CIS Benchmarks — cisecurity.org

  • NIST SP 800-57 Part 1 Rev. 5 — csrc.nist.gov

What I tested

A throwaway lab on this box: ansible-core 2.22.1, community.crypto 3.6.0, ansible.posix 2.2.2, ansible-lint 26.11.1, OpenSSH 10.0 client and unprivileged sshd processes on 127.0.0.1. No real server was touched.

Test Result
Happy path, 2 hosts, serial 1 Both hosts rotated; old and initial keys rejected afterwards; the new key accepted
Re-run with the same rotation id No changes on either host (hosts already on the new key are skipped)
Second rotation from the promoted key Chained correctly; one key left on each host
Verify fails on the first host (sshd reads a different file) New key removed, old key untouched, run stopped; the next hosts received no keys
Failure injected after removal Old key restored using the new key; both keys valid afterwards, so remove the new key or re-run
First draft: rotate onto the key in use Removed the only working key and locked out the lab hosts; fixed with the end_host guard and an early pin of the old key
Multiplexing check A bogus key logged in through an open master; rejected with ControlPath=none
sed with a short comment Both keys deleted, empty file
exclusive: true A second admin key and the connection key were removed
creates: keygen task, run twice Second run unchanged; passphrase visible in -v output; RSA 2048 key never replaced
SSH certificates Valid accepted; expired, wrong principal and no certificate rejected
ansible-lint Repo playbook: 5 findings. Modern playbook: passes the production profile

Standards and best practices

Read on Dec 3, 2026. NIST documents were read in full text; the CIS benchmark through a third-party mirror.

Standard or guidance What it says here Where it applies
NIST SP 800-57 Part 1 Rev. 5 (May 2020), section 5.3.6, Table 1 Private and public authentication key cryptoperiod: no more than one to two years, depending on environment and sensitivity Steps 2 and 15
NIST SP 800-57 Part 1 Rev. 5, section 7 Key states: pre-activation, active, deactivated, compromised, destroyed Steps 2 and 7
NISTIR 7966 (Oct 2015), sections 4.3 and 5.2 Unterminated keys are a risk; provisioning, review and termination are part of the life cycle Steps 1, 2 and 15
NISTIR 7966, section 5.4 Inventory keys, remove orphans, monitor 6 to 12 months for unused keys, add command and source restrictions, back up before change Steps 1, 5, 12 and 15
NISTIR 7966, footnotes 6 and 7 OpenSSH certificates are hard to audit without tracking; hard-coded passphrases add little security Steps 13 and 14
CIS Ubuntu Linux 24.04 LTS Benchmark v2.0.0 (May 28, 2026), section 5.1 Hardens the SSH server (for example host key file permissions, root login, key exchange); no user-key rotation item found Step 15
OpenSSH release notes 7.0, 7.8, 9.5, 9.8, 10.0 and 10.6 DSA removal timeline, new key format, Ed25519 default, KDF rounds Steps 4 and 6
Ansible documentation: serial, blocks, Vault, module references Batches, rescue, secrets, module options Steps 10 to 13
ansible-lint (fqcn and yaml rules) Fully qualified module names and clean YAML Step 10
OWASP Secrets Management Cheat Sheet Handling, rotating and auditing secrets Step 13

Troubleshooting

Symptom Likely cause Fix
Permission denied (publickey) right after removal New key not installed, or sshd reads a different authorized_keys file Restore the old key from the backup or console, then run sshd -T and read its authorizedkeysfile line
Verify passes but a fresh login fails later A multiplexed or agent-held session hid the failure Test with IdentitiesOnly, IdentityAgent=none and ControlPath=none; close masters with ssh -O exit
Playbook says UNREACHABLE after the rotation The inventory still points at the old key Point ansible_ssh_private_key_file at the new key (the playbook writes host_vars for this)
authorized_keys is empty sed matched too much, or exclusive removed everything Restore authorized_keys.pre-rotation or the .bak, then use exact-key removal
unknown key type dsa OpenSSH 10.0 or later has removed DSA Generate an Ed25519 key; replace any DSA keys on servers
Host key verification failed Lab hosts were rebuilt with new host keys Remove the stale known_hosts line; do not disable checking in production
Key not found: lookup of .pub file Inventory key has no matching .pub file Create it with ssh-keygen -y -f KEY > KEY.pub; the playbook fails early on purpose
Module not found: community.crypto Collections not installed ansible-galaxy collection install community.crypto ansible.posix
Rolled back after removal, two keys present Rescue restored the old key; the new key remains Remove the new key, find the cause, and re-run

Final checklist

Your to-do list. Nothing is ticked for you, as of Dec 3, 2026.

  • Inventory every authorized key on the target hosts and name an owner for each
  • Set a rotation cycle and event triggers (offboarding, suspected leak)
  • Build a disposable lab on a supported OS; do not use trusty64 or an unhosted Vagrant box
  • Generate Ed25519 keys; no DSA; no passphrase on a command line
  • Add the new key first; never use exclusive to add
  • Verify with only the new key, with the agent and multiplexing off, and prove the check can fail
  • Remove the old key by exact key body, with a backup and an empty-file guard
  • Confirm the old key is refused and the new key still works
  • Run a canary host, then batches with serial and any_errors_fatal
  • Keep a non-SSH way in (console or out-of-band access) and test it
  • Put keys in a 0700 directory, outside git, on encrypted storage; use Vault for secrets
  • Lint the playbook with ansible-lint and use fully qualified module names
  • Delete retired private keys when policy allows; record the evidence
  • Evaluate SSH certificates if you manage many hosts or people

What is unverified

  • I did not read the code images in your two PDFs. Code comes from the repo (commit 19becda); the repo’s function names and defaults differ slightly from Part 2’s text.
  • The Ansible Galaxy role that Part 2 mentions: I could not identify it.
  • ssh-copy-id, from= and restrict options, and the grep removal over SSH were not run in my lab.
  • The lab used unprivileged OpenSSH on one machine. I did not test become, bastion hosts, hosts with sshd configuration management, or non-OpenSSH servers.
  • The trusty64 box’s OpenSSH version; whether any Vagrant box you need will still be hosted after Dec 31, 2026.
  • The CIS benchmark was read through a mirror, not CIS’s site.
  • NIST’s 1 to 2 year figure is a suggestion for private authentication keys, not an SSH requirement; your policy decides.

Sources