Introduction
Rotating SSH host keys across a fleet is safe when you treat it as a two-sided change: add the new host public key to every relevant known_hosts file before the server starts presenting it, then swap the host key on the managed host, verify connectivity, and only after that remove the old key. Ansible can orchestrate this sequence at scale, but the playbook must preserve a valid trust path at every step because an SSH client that detects a changed host key will refuse the connection by default. The workflow in this article uses a dual-trust window, where both the old and new public keys are accepted during the transition, so operators can rotate keys without cutting off their own access.
Host key rotation comes up for ordinary operational reasons. A server may have been provisioned from an image that reused host keys, a security incident may require replacing private material, or an organization may be retiring weak algorithms in favor of Ed25519. The technical work is simple on a single machine. The risk appears when the same change is repeated across dozens or hundreds of hosts and the control node, jump hosts, monitoring systems, and deployment runners all hold stale known_hosts entries. A careful Ansible workflow turns that risky manual process into a repeatable sequence with explicit verification points.
Why SSH host key rotation causes lockouts
SSH host key verification exists to protect clients from connecting to the wrong server. On the first connection, the client records the server public host key in ~/.ssh/known_hosts or /etc/ssh/ssh_known_hosts. On later connections, OpenSSH compares the key presented by the server with the stored key. If the key has changed, the client stops before authentication continues and prints a warning. This behavior is correct from a security perspective, because a changed key can indicate a man-in-the-middle attack. During planned rotation, the same protection becomes an availability problem if clients are not updated first.
The failure is visible and immediate. An operator or an automation runner sees an error like the following:
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED! @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!Someone could be eavesdropping on you right now (man-in-the-middle attack)!It is also possible that a host key has just been changed.The fingerprint for the ED25519 key sent by the remote host isSHA256:AbCdEfGhIjKlMnOpQrStUvWxYz0123456789AbCdEfG.Please contact your system administrator.Add correct host key in /home/ansible/.ssh/known_hosts to get rid of this message.Offending ED25519 key in /home/ansible/.ssh/known_hosts:42 remove with: ssh-keygen -f "/home/ansible/.ssh/known_hosts" -R "10.20.30.11"Host key verification failed.The message gives a manual recovery path, but that recovery path assumes you still have another way into the host. For a fleet operation, the failure can affect the Ansible control node itself. If the control node rejects the new host key, every later task in the play fails with UNREACHABLE, and the automation that was supposed to finish the rotation can no longer connect. The result is an avoidable outage caused by ordering, not by SSH itself.
There is also a second failure mode that receives less attention. Even if the controller can connect, other systems may still trust the old key: jump hosts, CI runners, backup servers, monitoring probes, or administrators’ laptops. A rotation plan that only updates the Ansible controller is incomplete. The plan needs an inventory of every client that stores host keys for the target systems, or at least a clear boundary around which clients are managed by the automation.
Prerequisites and safety checks
The examples in this article use ansible-core 2.16 on a Linux control node with Python 3.11. Managed hosts run OpenSSH server and use systemd. The commands and playbooks are written for common Linux distributions, but service names and file paths should be checked against your environment before running them in production. Debian-based systems usually expose the SSH service as ssh, while RHEL-based systems usually expose it as sshd.
Before touching any host key, confirm that you have an independent recovery path. A cloud serial console, hypervisor console, IPMI, or another out-of-band mechanism is the difference between an inconvenient mistake and a prolonged incident. Ansible cannot repair an SSH trust failure over the same SSH connection that just failed. Out-of-band access is not part of the happy path, but it is part of responsible execution.
You also need a clear picture of which key types are in use. Many hosts currently have Ed25519, RSA, and sometimes ECDSA host keys. Rotating only one type while clients negotiate another can create confusing results. The examples below rotate Ed25519 and RSA host keys because that combination covers modern defaults and older clients that still require RSA. If your environment has a different policy, adjust the key list explicitly rather than relying on defaults.
The following checks are worth running before the first playbook:
# On the control nodeansible --versionssh -V
# On a managed hostsudo sshd -T | grep -i '^hostkey'sudo ls -l /etc/ssh/ssh_host_*_key*sudo systemctl status sshd || sudo systemctl status sshThe sshd -T command prints the effective configuration. It tells you which host key files the daemon currently uses, which matters if a host has custom HostKey entries in sshd_config. If you skip this check, you may rotate files that the daemon never reads, or miss files that it does read.
Repository layout and Ansible configuration
A small, explicit repository layout makes the rotation easier to review and rerun. The layout below separates inventory, variables, playbooks, and generated artifacts. It also keeps each phase in its own playbook so you can pause between phases, inspect the state, and continue when the previous step has been verified.
ssh-hostkey-rotation/├── ansible.cfg├── inventory/│ └── production.ini├── group_vars/│ └── all.yml├── playbooks/│ ├── 01-generate-new-hostkeys.yml│ ├── 02-distribute-known-hosts.yml│ ├── 03-activate-new-hostkeys.yml│ ├── 04-verify-connectivity.yml│ └── 05-remove-old-hostkeys.yml└── artifacts/ └── hostkeys/The ansible.cfg file should keep host key checking enabled. Disabling host key checking globally removes the safety mechanism that protects normal SSH connections. The dual-trust workflow described here does not require turning it off.
[defaults]inventory = ./inventory/production.iniremote_user = ansiblehost_key_checking = Trueretry_files_enabled = Falsetimeout = 30forks = 20stdout_callback = yamlinterpreter_python = auto_silent
[privilege_escalation]become = Truebecome_method = sudo
[ssh_connection]pipelining = Truessh_args = -o ControlMaster=auto -o ControlPersist=60sThe inventory can be simple. The important detail is that you know how Ansible connects to each host, because the same names and addresses must be used when updating known_hosts.
[web]web-01 ansible_host=10.20.30.11web-02 ansible_host=10.20.30.12
[db]db-01 ansible_host=10.20.30.21
[all:vars]ansible_become=trueShared variables belong in group_vars/all.yml. Keeping key paths, rotation identifiers, and backup locations in one place reduces the chance of phase-to-phase drift.
---ssh_rotation_id: "2026-11-25"ssh_host_key_dir: /etc/sshssh_backup_dir: /var/backups/ssh-hostkeysssh_new_key_suffix: ".new-rotation"
ssh_key_specs: - type: ed25519 filename: ssh_host_ed25519_key - type: rsa filename: ssh_host_rsa_key bits: 4096
ssh_controller_known_hosts: "{{ lookup('env', 'HOME') + '/.ssh/known_hosts' }}"ssh_artifacts_dir: "{{ playbook_dir }}/../artifacts/hostkeys"The rotation identifier is used in backup names and comments. It gives you a concrete label to search for in logs, file names, and audit trails. Using a date is practical, but any unique identifier works as long as you use it consistently.
Phase 1: generate new host keys on managed hosts
The first phase creates new host keys on each managed host without replacing the active keys. The new keys live next to the old ones under a temporary name. This keeps the active SSH service unchanged while giving you new public keys that can be distributed to clients.
Generating keys on the managed host is preferable to generating them centrally. A host private key should not travel across the network unless you have a strong reason and a controlled transfer mechanism. With on-host generation, the private key is created where it will be used, and only the public key needs to be collected.
---- name: Phase 1 - Generate new SSH host keys hosts: all become: true gather_facts: true
tasks: - name: Ensure local artifact directory exists ansible.builtin.file: path: "{{ ssh_artifacts_dir }}" state: directory mode: "0755" delegate_to: localhost run_once: true become: false
- name: Ensure remote backup directory exists ansible.builtin.file: path: "{{ ssh_backup_dir }}" state: directory owner: root group: root mode: "0700"
- name: Check for existing new private keys ansible.builtin.stat: path: "{{ ssh_host_key_dir }}/{{ item.filename }}{{ ssh_new_key_suffix }}" loop: "{{ ssh_key_specs }}" loop_control: label: "{{ item.type }}" register: new_key_stats
- name: Generate new host private keys ansible.builtin.command: cmd: >- ssh-keygen -t {{ item.item.type }} {% if item.item.bits is defined %}-b {{ item.item.bits }}{% endif %} -f {{ ssh_host_key_dir }}/{{ item.item.filename }}{{ ssh_new_key_suffix }} -N "" -C "{{ inventory_hostname }}-{{ item.item.type }}-{{ ssh_rotation_id }}" loop: "{{ new_key_stats.results }}" loop_control: label: "{{ item.item.type }}" when: not item.stat.exists changed_when: true no_log: true
- name: Set private key ownership and permissions ansible.builtin.file: path: "{{ ssh_host_key_dir }}/{{ item.filename }}{{ ssh_new_key_suffix }}" owner: root group: root mode: "0600" loop: "{{ ssh_key_specs }}" loop_control: label: "{{ item.type }}"
- name: Set public key ownership and permissions ansible.builtin.file: path: "{{ ssh_host_key_dir }}/{{ item.filename }}{{ ssh_new_key_suffix }}.pub" owner: root group: root mode: "0644" loop: "{{ ssh_key_specs }}" loop_control: label: "{{ item.type }}"
- name: Read new public keys ansible.builtin.slurp: src: "{{ ssh_host_key_dir }}/{{ item.filename }}{{ ssh_new_key_suffix }}.pub" loop: "{{ ssh_key_specs }}" loop_control: label: "{{ item.type }}" register: new_pubkeys
- name: Save new public keys as local artifacts ansible.builtin.copy: dest: "{{ ssh_artifacts_dir }}/{{ inventory_hostname }}.{{ item.item.type }}.pub" content: "{{ item.content | b64decode }}" mode: "0644" loop: "{{ new_pubkeys.results }}" loop_control: label: "{{ item.item.type }}" delegate_to: localhost become: falseThe no_log: true on key generation is a precaution. The command does not print the private key, but private key operations should still be treated carefully in logs. The public key artifacts are safe to store locally because they are public by design. They also give you a record of what was distributed during the rotation.
The ssh-keygen -N "" flag creates a host key without a passphrase. Host keys must be readable by sshd at startup without interactive input, so a passphrase is not appropriate here. The permission tasks are not optional. OpenSSH is strict about private key permissions, and incorrect permissions can prevent the daemon from using the key.
Phase 2: distribute new keys to known_hosts
This phase prevents lockouts. Before any managed host presents a new key, every client that needs to connect must trust that new key. The safest way to do this is to add the new public key while keeping the old one. With both keys present in known_hosts, the client can accept either key during the transition.
There is an important Ansible detail here. The ansible.builtin.known_hosts module manages entries by host name. If you ask it to ensure a key for a host and a different key already exists, it can replace the existing entry. That behavior is useful for normal cleanup, but it is dangerous during a dual-trust window because it may remove the old key too early. For the addition step, ansible.builtin.lineinfile is a better fit because it can append the new key without deleting the old one.
---- name: Phase 2 - Distribute new host keys to controller known_hosts hosts: all gather_facts: false become: false
tasks: - name: Read generated public keys from artifacts ansible.builtin.set_fact: rotation_pubkeys: >- {{ ssh_key_specs | map(attribute='type') | map('regex_replace', '^(.*)$', ssh_artifacts_dir ~ '/' ~ inventory_hostname ~ '.\\1.pub') | list }}
- name: Load public key contents ansible.builtin.set_fact: rotation_pubkey_lines: >- {{ lookup('file', ssh_artifacts_dir ~ '/' ~ inventory_hostname ~ '.' ~ item.type ~ '.pub') | trim }} loop: "{{ ssh_key_specs }}" loop_control: label: "{{ item.type }}" register: loaded_pubkeys
- name: Build known_hosts entries for inventory name and address ansible.builtin.set_fact: new_known_hosts_entries: >- {{ loaded_pubkeys.results | map(attribute='ansible_facts.rotation_pubkey_lines') | map('regex_replace', '^', inventory_hostname ~ ',' ~ (ansible_host | default(inventory_hostname)) ~ ' ') | list }}
- name: Add new key entries to controller known_hosts ansible.builtin.lineinfile: path: "{{ ssh_controller_known_hosts }}" line: "{{ item }}" create: true mode: "0600" state: present loop: "{{ new_known_hosts_entries }}" loop_control: label: "{{ inventory_hostname }}" delegate_to: localhost throttle: 1This playbook updates the controller’s known_hosts. In many environments, that is only one client among several. If jump hosts, CI workers, or backup systems also initiate SSH connections to the managed hosts, run an equivalent distribution step for those clients. The same principle applies: add the new key, keep the old key, and do not remove anything until verification is complete.
The known_hosts format deserves care. The example writes entries keyed by inventory_hostname,ansible_host. You should include every name or address that clients use to connect. If some jobs connect to web-01.example.internal and others connect to 10.20.30.11, both identifiers need matching entries. A missing alias can look like a random failure later, even when the main inventory name works.
Another operational detail is hashed known_hosts. If HashKnownHosts yes is enabled, hostnames in the file are hashed, which makes simple line matching harder. For a dedicated automation account, many teams keep HashKnownHosts no in ~/.ssh/config or manage a separate known_hosts file. That trade-off favors manageability over hostname obfuscation. If you keep hashed entries, prefer a workflow that uses ssh-keygen and explicit file management, and test it carefully on a staging host.
Phase 3: activate the new host keys
Once the new public keys have been distributed, the managed hosts can start presenting the new private keys. This is the sensitive phase. The playbook should back up the old keys, install the new keys with correct permissions, validate the SSH daemon configuration, reload the service, and reset Ansible’s SSH connection.
---- name: Phase 3 - Activate new SSH host keys hosts: all become: true gather_facts: true serial: "20%"
pre_tasks: - name: Determine ssh service name ansible.builtin.set_fact: ssh_service_name: "{{ 'ssh' if ansible_facts['os_family'] == 'Debian' else 'sshd' }}"
handlers: - name: Validate sshd configuration ansible.builtin.command: sshd -t changed_when: false listen: Reload ssh service
- name: Reload ssh service ansible.builtin.service: name: "{{ ssh_service_name }}" state: reloaded listen: Reload ssh service
tasks: - name: Back up current host keys ansible.builtin.copy: src: "{{ ssh_host_key_dir }}/{{ item.filename }}{{ suffix }}" dest: "{{ ssh_backup_dir }}/{{ inventory_hostname }}-{{ ssh_rotation_id }}-{{ item.filename }}{{ suffix }}" remote_src: true owner: root group: root mode: preserve loop: "{{ ssh_key_specs | product(['', '.pub']) | list }}" loop_control: label: "{{ item.0.type }}{{ item.1 }}" vars: suffix: "{{ item.1 }}" item: filename: "{{ item.0.filename }}" failed_when: false
- name: Install new private host keys ansible.builtin.copy: src: "{{ ssh_host_key_dir }}/{{ item.filename }}{{ ssh_new_key_suffix }}" dest: "{{ ssh_host_key_dir }}/{{ item.filename }}" remote_src: true owner: root group: root mode: "0600" loop: "{{ ssh_key_specs }}" loop_control: label: "{{ item.type }}" notify: Reload ssh service
- name: Install new public host keys ansible.builtin.copy: src: "{{ ssh_host_key_dir }}/{{ item.filename }}{{ ssh_new_key_suffix }}.pub" dest: "{{ ssh_host_key_dir }}/{{ item.filename }}.pub" remote_src: true owner: root group: root mode: "0644" loop: "{{ ssh_key_specs }}" loop_control: label: "{{ item.type }}" notify: Reload ssh service
- name: Apply sshd changes before continuing ansible.builtin.meta: flush_handlers
- name: Reset persistent SSH connections ansible.builtin.meta: reset_connectionThe serial: "20%" setting limits blast radius. On a first production run, even serial: 1 or a small canary group is sensible. If a host fails to reload sshd, you want to discover that before the play has touched the rest of the fleet. Serial execution costs time, but it gives you a controlled failure boundary.
The handler order matters. The validation handler runs before the reload handler because handlers execute in definition order. If sshd -t fails, the reload should not proceed. That check catches syntax errors in configuration, but it does not prove every client will trust the new key. Trust is handled by Phase 2. Service validity is handled here.
The reset_connection task is easy to skip and painful to miss. Ansible may reuse an existing SSH control connection. After the host key changes, a fresh connection is the real test. Resetting the connection forces Ansible to establish a new SSH session, which exercises the new trust path.
Phase 4: verify connectivity before cleanup
Verification is a separate phase because it should be boring and explicit. The goal is to prove that Ansible can still reach every host, that the expected key files are present, and that the fingerprints match the newly generated keys. Do not remove old known_hosts entries until this phase passes.
---- name: Phase 4 - Verify connectivity and fingerprints hosts: all become: true gather_facts: false serial: 1
tasks: - name: Reset connection before verification ansible.builtin.meta: reset_connection
- name: Check Ansible connectivity ansible.builtin.ping: become: false
- name: Read active public key fingerprints ansible.builtin.command: cmd: "ssh-keygen -lf {{ ssh_host_key_dir }}/{{ item.filename }}.pub" loop: "{{ ssh_key_specs }}" loop_control: label: "{{ item.type }}" register: active_fingerprints changed_when: false
- name: Show active fingerprints ansible.builtin.debug: msg: "{{ inventory_hostname }} {{ item.item.type }} {{ item.stdout }}" loop: "{{ active_fingerprints.results }}" loop_control: label: "{{ item.item.type }}"
- name: Compare active key with generated artifact ansible.builtin.command: cmd: >- diff -u {{ ssh_artifacts_dir }}/{{ inventory_hostname }}.{{ item.type }}.pub {{ ssh_host_key_dir }}/{{ item.filename }}.pub delegate_to: localhost become: false loop: "{{ ssh_key_specs }}" loop_control: label: "{{ item.type }}" changed_when: falseThe diff task compares the local artifact with the active public key on the host through Ansible’s file access model. In this example, it runs on the controller and expects the artifact to match the public key content you intended to deploy. If you prefer, fetch the active public key from the host and diff locally; the key point is to compare what you generated with what the host is serving.
Verification should also include clients outside Ansible. If a monitoring system connects by SSH, test it now. If developers use a bastion host, test from the bastion. This phase is where you learn whether the rotation scope was complete. Finding a missed client after cleanup is much more annoying than finding it while both keys are still trusted.
Phase 5: remove old keys and clean up
After verification, you can remove the dual-trust state. Cleanup has two sides. On the controller and other clients, remove old known_hosts entries for the host and keep only the new keys. On the managed host, remove temporary key files and, if your policy requires it, remove old backups after a retention period.
For controller cleanup, removing all entries for the host and then adding back only the new keys is clearer than trying to surgically identify the old line. The ssh-keygen -R command is convenient for removing entries by hostname or address.
---- name: Phase 5 - Remove old trust entries and temporary files hosts: all become: false gather_facts: false serial: 1
tasks: - name: Remove old known_hosts entries on controller by name ansible.builtin.command: cmd: "ssh-keygen -f {{ ssh_controller_known_hosts }} -R {{ inventory_hostname }}" delegate_to: localhost changed_when: false failed_when: false
- name: Remove old known_hosts entries on controller by address ansible.builtin.command: cmd: "ssh-keygen -f {{ ssh_controller_known_hosts }} -R {{ ansible_host }}" delegate_to: localhost when: ansible_host is defined changed_when: false failed_when: false
- name: Read new public key artifacts ansible.builtin.set_fact: new_pubkey_lines: >- {{ ssh_key_specs | map(attribute='type') | map('regex_replace', '^(.*)$', ssh_artifacts_dir ~ '/' ~ inventory_hostname ~ '.\\1.pub') | map('file') | map('trim') | list }}
- name: Add only new keys back to controller known_hosts ansible.builtin.lineinfile: path: "{{ ssh_controller_known_hosts }}" line: "{{ inventory_hostname }},{{ ansible_host | default(inventory_hostname) }} {{ item }}" create: true mode: "0600" state: present loop: "{{ new_pubkey_lines }}" delegate_to: localhost throttle: 1
- name: Phase 5b - Remove temporary key files on managed hosts hosts: all become: true gather_facts: false
tasks: - name: Remove temporary new key files ansible.builtin.file: path: "{{ ssh_host_key_dir }}/{{ item.0.filename }}{{ ssh_new_key_suffix }}{{ item.1 }}" state: absent loop: "{{ ssh_key_specs | product(['', '.pub']) | list }}" loop_control: label: "{{ item.0.type }}{{ item.1 }}"The cleanup on the managed host removes only the temporary .new-rotation files. It does not delete the backup copies created in Phase 3. Keeping backups for a short retention window is useful if you discover a late client that still depends on the old key. Once the rotation has been stable for your chosen retention period, you can remove those backups through a separate, deliberate cleanup task.
Troubleshooting common lockout scenarios
Even with a careful plan, SSH rotation can fail in predictable ways. The key is to recognize the error, identify which phase broke the trust path, and use the recovery path that does not depend on the broken SSH trust.
Host key verification failed on the controller
The most common failure looks like this:
fatal: [web-01]: UNREACHABLE! => { "changed": false, "msg": "Failed to connect to the host via ssh: Host key verification failed.", "unreachable": true}This usually means Phase 3 activated the new host key before Phase 2 added the new public key to the controller’s known_hosts. It can also happen if you connected through a hostname or IP that was not included in the known_hosts entry. Check the exact target Ansible used, then inspect the controller file:
ssh-keygen -F 10.20.30.11 -f ~/.ssh/known_hostsssh-keygen -F web-01 -f ~/.ssh/known_hostsIf the host is unreachable over SSH, use the out-of-band console to restore the previous key files from the backup directory and reload sshd:
sudo cp /var/backups/ssh-hostkeys/web-01-2026-11-25-ssh_host_ed25519_key /etc/ssh/ssh_host_ed25519_keysudo cp /var/backups/ssh-hostkeys/web-01-2026-11-25-ssh_host_ed25519_key.pub /etc/ssh/ssh_host_ed25519_key.pubsudo chmod 0600 /etc/ssh/ssh_host_ed25519_keysudo chmod 0644 /etc/ssh/ssh_host_ed25519_key.pubsudo sshd -tsudo systemctl reload sshdAfter restoring access, fix the known_hosts distribution step and repeat the rotation for that host.
sshd refuses to start or reload because of permissions
Bad permissions on private keys can make the new key unusable. A common error in logs is:
sshd[2417]: error: Permissions 0644 for '/etc/ssh/ssh_host_ed25519_key' are too open.sshd[2417]: error: Unable to load host key: /etc/ssh/ssh_host_ed25519_keysshd[2417]: fatal: No supported key exchange algorithms [preauth]Another failure mode is a missing or unreadable key file, which can produce:
sshd[2451]: error: No host keys available, exiting.Both cases point to file installation problems. Private keys must be owned by root and set to 0600. Public keys should be 0644. If the daemon failed to reload, check the service status and journal on the console:
sudo sshd -tsudo ls -l /etc/ssh/ssh_host_*_key*sudo journalctl -u sshd -n 50 --no-pagersudo systemctl status sshdThe fix is to restore correct permissions or restore the backup key files. This is why the playbook creates backups before activation and validates with sshd -t before reloading.
Ansible connects but uses the wrong host alias
Sometimes the controller has the new key for web-01, but Ansible connects to 10.20.30.11 and that address has no matching new entry. The error looks identical to a normal host key mismatch, which makes it easy to misdiagnose. The cause is not the key rotation itself; it is incomplete known_hosts coverage.
Check every identifier clients use:
ssh-keygen -F web-01 -f ~/.ssh/known_hostsssh-keygen -F 10.20.30.11 -f ~/.ssh/known_hostsssh-keygen -F web-01.example.internal -f ~/.ssh/known_hostsThe fix is to add all relevant aliases during Phase 2. In inventory-driven automation, it helps to standardize on one connection name. In mixed environments, include every name that appears in scripts, monitoring checks, and human workflows.
The new key already exists and the playbook behaves unexpectedly
If a previous run failed halfway, you may see an error like:
ssh-keygen: /etc/ssh/ssh_host_ed25519_key.new-rotation already exists.This is why the generation playbook checks for file existence before running ssh-keygen. If you wrote the command without that guard, reruns would fail or overwrite files. Overwriting a newly generated key after Phase 2 has already distributed its public key is especially bad, because the distributed public key would no longer match the private key on the host.
The recovery is to decide which state is authoritative. If the public key was already distributed, keep the generated key pair and continue. If the key was generated but never distributed, you can remove the temporary files and regenerate them. Make that decision explicitly; do not let reruns guess.
SSH service reload succeeds but later connections fail
A reload can succeed while a later connection still fails because the problem is on the client side, not the server side. This often happens when cleanup removed the old key from the controller but a bastion host, CI runner, or developer machine still has the old key. The managed host is healthy, but the client is stale.
The diagnostic question is simple: where is the connection coming from? Test from the affected client, not only from the Ansible controller. If the client is outside your automation scope, you need a communication plan for the rotation. A technically correct server-side rotation can still create support tickets if client updates are not coordinated.
Operational trade-offs and rollout strategy
The dual-trust workflow has a clear benefit: it avoids the most common lockout by allowing clients to accept both the old and new host keys during the transition. The cost is temporary complexity. During the window between Phase 2 and Phase 5, clients trust more key material than they will at the end. That window should be short, observable, and deliberate.
Serial execution is another trade-off. Running with serial: 1 or serial: "20%" slows the rollout, but it gives you early feedback. A full parallel rotation across hundreds of hosts can turn a small mistake into a fleet-wide event. For host key changes, the safer default is to start with a canary group, verify external clients, then expand in batches.
Key generation location also involves trade-offs. On-host generation keeps private keys local and is easy to automate with Ansible. Central generation can fit environments that require keys to be created inside a controlled key ceremony or hardware-backed process, but it introduces a sensitive distribution step. If you choose central generation, protect the transfer path, limit artifact exposure, and delete temporary copies after deployment.
Algorithm selection should be explicit. Ed25519 is a good default for modern OpenSSH environments. RSA 4096 remains useful for compatibility with older clients and appliances. ECDSA may be required in some environments, but it should be included intentionally, not accidentally. Rotate every key type that sshd is configured to present, or update sshd_config so the daemon presents only the keys you intend to manage.
Finally, treat host key rotation as an operational change with records. Keep the generated public key artifacts, the playbook run logs, the rotation identifier, and the backup retention period. When a client reports a host key warning two weeks later, those records let you answer whether the change was planned, which key was installed, and which fingerprint the client should trust. The technical rotation is only complete when the trust state across all relevant clients is consistent.