EC2 "Host Key Verification Failed": The Safe SSH Fix

Logeshwaran
—

EC2 Host key verification failed means your SSH client no longer trusts the server identity presented at the address you contacted. SSH compares the server’s public host key with the entry saved in known_hosts; after an instance rebuild or an Elastic IP move, the new server often has a different key. The safe fix is to verify the new host-key fingerprint independently, remove only the obsolete entry with ssh-keygen -R, and reconnect. Unexpectedly, using the same EC2 login key pair does not preserve the server host key: those are different credentials with different purposes.

⚡ Quick Answer

Console: EC2 → Instances → select the instance → Actions → Monitor and troubleshoot → Get system log; compare the SSH host-key fingerprint.

CLI: aws ec2 get-console-output --instance-id i-0123456789abcdef0 --query Output --output text

Client: After independently matching the new fingerprint, run ssh-keygen -R 203.0.113.10 for the exact affected host, then reconnect and compare the key again.

Read the safe repair procedure, especially if the change was unexpected.

Jake runs a phone-repair shop with a small booking site on an EC2 Linux instance. In this illustrative scenario, rebuilding the server while keeping its Elastic IP makes the site reachable but stops Jake’s SSH login with a severe-looking warning. The shop is missing an hour of admin access; simply clicking through could be worse if the address now reaches an impostor.

The tempting response is to disable host-key checking for the whole workstation. That hides the warning instead of answering whether the new server is really the instance Jake launched. The safer path is to establish server identity using account-controlled AWS information before updating the local trust record.

Jake: "I kept the same .pem key file. How can the server suddenly be a stranger?"

Ethan: "Your .pem file proves you are allowed in. The server host key proves which machine is answering. A rebuilt machine can keep your login key and still have a new host identity."

Understand what SSH actually compares

You see the warning before you get a shell because SSH protects the connection before granting access. Your client receives a public host key from the remote SSH server and checks it against a remembered identity for the hostname, IP address, and port you requested. The corresponding private host key normally stays on the server, where it proves possession during the SSH handshake.

On OpenSSH clients, the remembered information is usually in ~/.ssh/known_hosts for your user, with optional system-wide records. A host can appear as plain text or a hashed entry, and nonstandard ports use the bracketed [host]:port form. That is why manually deleting what looks like a random line is less reliable than ssh-keygen -R.

The EC2 key pair selected when the instance launches is a separate mechanism used for authenticating the client. The private key you supply with ssh -i is not the SSH daemon’s host private key. Keeping or replacing that login key does not prove the server has retained its host identity, and rotating the login key will not repair a host fingerprint mismatch.

Host-key verification is a defense against connections to an unexpected server, including accidental address reuse and potential man-in-the-middle interception. A known good key changed without explanation should be investigated. A known rebuild gives you a plausible explanation, but you still need a trustworthy source for the new fingerprint before accepting it.

Recognize the precise warning on your computer

On macOS, Linux, and Windows OpenSSH, a changed host key often produces a bold warning before authentication. You may see WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED! and Host key verification failed.. The output can also identify the offending entry and the known_hosts file containing it.

Some installations display Offending ED25519 key in /home/user/.ssh/known_hosts:12, while others reference RSA or ECDSA depending on the key negotiated. Windows OpenSSH normally uses C:\Users\YourUser\.ssh\known_hosts instead of a Unix home directory. The precise line and path depend on the machine, so use the values from your own error.

PuTTY has a different interface. It caches SSH host keys in user settings and can show a security alert that the server’s host key does not match the cached key. An initial connection also prompts you to accept a key, but first contact is not proof of authenticity unless you compare its fingerprint with a separate trusted source.

Occasionally the brief error line appears without the dramatic warning because batch mode or strict verification refuses to prompt. In those cases, increase SSH client verbosity with ssh -v to see which hostname, port, and host-key algorithm the client selected. Read the error as a trust mismatch first, not as a username or private-key permissions problem.

Tell a routine rebuild from an unexpected identity change

After you rebuild an EC2 instance, its operating system may generate fresh SSH host keys on first boot. If the new instance receives the same Elastic IP, existing clients associate that address with the old key and report a mismatch. This is a routine cause only when you can tie the address to the intended new instance.

Restoring an AMI is not by itself a guarantee that host keys change or remain unchanged. Image creation practices and initialization scripts determine whether keys are preserved, removed, or regenerated. Copying host private keys into every cloned instance can also create an undesirable shared identity, so treat instances built from one image as separate servers with separate identities.

A stop-and-start operation on an instance with an automatically assigned public IPv4 address can change the public IP. That alone commonly causes connection confusion when you use an old address or DNS record; it does not normally require a host-key change on the same persistent instance. Check which instance actually answers at the destination before assigning the cause.

A changed DNS record, reassigned Elastic IP, load-balanced SSH destination, restored disk, manually regenerated host keys, or potentially intercepted network path can all change what key your client sees. Use EC2 instance IDs, network interface information, and the server fingerprint to sort them out. The error is a signal to investigate, not evidence that an attack necessarily occurred.

Verify the replacement server fingerprint from AWS

When you have a changed key, obtain a trusted fingerprint before touching known_hosts. In the EC2 console choose Instances, select the intended instance, then Actions, Monitor and troubleshoot, Get system log. For supported images and initialization configurations, the system output includes a BEGIN SSH HOST KEY FINGERPRINTS block.

The system output can show several entries, commonly ED25519, ECDSA, and RSA. Match the key type and SHA256 fingerprint reported by the SSH client against the corresponding entry for your instance. Be careful not to confuse the EC2 key-pair fingerprint displayed on the Key pairs page with the instance SSH host-key fingerprint; these describe different keys.

The CLI alternative is aws ec2 get-console-output --instance-id i-0123456789abcdef0 --query Output --output text in the correct Region and account. You can save the output to a file and search it for the host-key block. Console output depends on the AMI and boot logging, so the block may be missing on customized images or after configuration changes.

If the system log does not reveal the fingerprint, use an already trusted administrative path such as Session Manager or a verified EC2 Instance Connect console session, when available. On the instance, sudo ssh-keygen -lf /etc/ssh/ssh_host_ed25519_key.pub displays its ED25519 host-key fingerprint. Compare it independently before trusting the SSH destination, and investigate discrepancies rather than accepting the prompt.

aws ec2 get-console-output --instance-id i-0123456789abcdef0 --query Output --output text
# On the instance through a trusted session:
sudo ssh-keygen -lf /etc/ssh/ssh_host_ed25519_key.pub

Remove only the stale entry and reconnect safely

Once you have an independently established replacement fingerprint, remove the old trust record for exactly the host you are contacting. For a connection by IP, ssh-keygen -R 203.0.113.10 edits your default known_hosts file. The address shown here is an example documentation address; replace it with the actual Elastic IP or hostname.

If you also connect through a DNS name, that name can have its own old entry and may require a separate ssh-keygen -R server.example.com. For a nonstandard SSH port such as 2222, use ssh-keygen -R "[server.example.com]:2222". The command can remove hashed host entries correctly, which is one reason it is safer than searching for an address in a text editor.

Reconnect with your usual login command, such as ssh -i shop.pem ec2-user@203.0.113.10 for a suitable Amazon Linux instance. OpenSSH may prompt to trust the new host key. Compare the displayed SHA256 fingerprint with the independent fingerprint, and accept only if they match. If they differ, stop and investigate routing, DNS, and instance identity.

After reconnecting, confirm the destination using hostname, instance metadata where appropriate, or a known application file. These checks complement the initial cryptographic fingerprint comparison rather than replacing it, and they can catch operational mistakes such as connecting to the wrong server after an Elastic IP reassociation. Keep your standard host-key checks enabled for future connections.

  1. Identify the actual instance and endpoint that should answer your connection.
  2. Obtain the new host-key fingerprint from an independent AWS-controlled path.
  3. Run ssh-keygen -R 203.0.113.10 for the precise address.
  4. Reconnect, compare the full SHA256 fingerprint, and accept only an exact match.
  5. Confirm you reached the intended instance and preserve the new known_hosts record.
ssh-keygen -R 203.0.113.10
ssh -i shop.pem ec2-user@203.0.113.10
# Nondefault port:
ssh-keygen -R "[server.example.com]:2222"

Follow a worked Elastic IP rebuild from warning to recovery

Imagine Jake’s booking server used Elastic IP 203.0.113.10 on instance i-0aaaexample0000001. The old instance is replaced by i-0bbbexample0000002, and the Elastic IP is reassociated to the replacement. Both values are illustrative; you would use actual identifiers returned by your EC2 account.

Jake’s existing laptop has the old ED25519 host key stored for 203.0.113.10. His first SSH attempt after the reassociation reports a changed remote host identification. He verifies in EC2 that the intended replacement owns the Elastic IP, then gets the replacement’s SSH host fingerprint from the new instance’s system log.

For illustration, suppose the trusted system log and the SSH prompt both display SHA256:EXAMPLEfingerprintReplaceWithRealOne. That string is a placeholder, not a usable host key. Jake removes only the stale record with ssh-keygen -R 203.0.113.10, reconnects, and accepts the new key only after its actual fingerprint matches the AWS-controlled source.

The process ends with a successful login to the intended replacement and a new known_hosts record. The critical step is not deletion of the old line by itself; it is validating the replacement identity before creating the new trust relationship. If the two fingerprints fail to match, Jake stops instead of weakening the connection, even though the shop needs the booking server back.

Jake: "I moved my Elastic IP to the new box. Why should deleting one line make it safe?"

Ethan: "Deleting one line alone is not enough. The trusted console fingerprint tells you whether the new box is really yours before you accept its key."

StageWhat Jake seesCorrect action
Before rebuildKnown host key for Elastic IPPreserve existing verified entry
New instanceDifferent fingerprintConfirm EIP association and console log
SSH attemptREMOTE HOST IDENTIFICATION HAS CHANGEDStop; compare fingerprints
Verified replacementTrusted fingerprint matchesRemove one stale entry and reconnect

Why StrictHostKeyChecking=no is the wrong shortcut

You may find commands that add -o StrictHostKeyChecking=no to every SSH invocation. That suppresses important protection, and in some host-key-change cases OpenSSH may still restrict certain risky behavior rather than safely accepting the unexpected key. It does not establish that the remote server is the EC2 instance you intended to contact.

Combining StrictHostKeyChecking=no with UserKnownHostsFile=/dev/null discards the persistent identity check entirely. The next server offering an SSH connection may be accepted without a durable, verified association. This is especially dangerous in automated deployments that carry credentials, artifacts, or production commands.

You should instead provision a trusted host-key fingerprint into your workflow and keep StrictHostKeyChecking=yes for unattended connections. If infrastructure is routinely rebuilt, automate retrieval and validation from a trusted management channel, or choose an access method that avoids public SSH connectivity. The objective is repeatable trust, not an exception that remains forever.

For one-off human recovery, the manual fingerprint comparison is usually the quickest responsible approach. The time spent checking the system log is small compared with the consequences of sending a production SSH session to the wrong host. Treat emergency access as a reason to use an independent verification channel, not as an excuse to disable it.

Jake: "The internet says I can add StrictHostKeyChecking=no and get straight in."

Ethan: "That skips the question the warning is asking. Verify the server key and change one trust record instead of teaching SSH to ignore surprises."

Fix Windows OpenSSH and PuTTY without removing unrelated keys

On Windows 10 or 11 with built-in OpenSSH, open PowerShell and run ssh-keygen -R 203.0.113.10 under the same Windows account that runs SSH. Your user known_hosts file normally lives under %USERPROFILE%\.ssh\known_hosts. If the command reports another file or a configured custom known_hosts path, use the path indicated by the actual SSH client.

OpenSSH on Windows uses the same basic mismatch logic as Linux and macOS, but file paths and quoting can change. A connection launched from WSL can have its own Linux home directory and different known_hosts contents. Similarly, Git Bash, PowerShell, and a container may not use the same SSH configuration even on the same laptop.

PuTTY stores host-key cache entries separately from OpenSSH; deleting a line from OpenSSH known_hosts will not clear PuTTY’s saved key. In PuTTY, inspect the host-key warning and compare the presented fingerprint against the independent EC2 source. Remove only the relevant old cached entry using PuTTY’s documented cache controls or the relevant current-user registry entry, with appropriate care.

Because Windows has multiple SSH clients, first establish which executable your terminal or deployment tool invokes. Use where.exe ssh in PowerShell to see possible binaries. Once you know the client, target its specific host-key store rather than repeatedly changing security groups, key pairs, or EC2 login usernames.

ssh-keygen -R 203.0.113.10
where.exe ssh
# Check which user and shell own the known_hosts file

Handle GitHub Actions runners and CI containers

In GitHub Actions, the failing SSH command may run on an ephemeral runner that has no stable known_hosts file across jobs. A workflow can also use a third-party action that creates its own SSH directory or Docker container. Determine which process actually issues the SSH connection before modifying the runner’s host-key records.

For a trusted fixed server, store an expected SHA256 fingerprint or audited public host key in an approved configuration source. At job start, populate a job-specific known_hosts file with that verified key and invoke SSH with strict checking. ssh-keyscan can collect the key the network currently presents, but using its output blindly is not independent verification.

If an EC2 instance is rebuilt and its keys rotate, update the trusted CI record through your reviewed provisioning workflow. A script that unconditionally removes the old entry and accepts whatever key the same untrusted network path offers defeats the whole check. That would convert every legitimate host-key warning into an unattended trust reset.

With containers, make sure the known_hosts path belongs to the container user, not only the host machine. A mounted file can provide the verified keys, or the image can receive a narrowly scoped trust file during job setup. Keep secrets and private SSH keys separate from the public host-key trust record.

Jake: "My GitHub job has no memory of the server. Is it okay to scan and trust any key each run?"

Ethan: "Collecting a key is not validating it. Put a reviewed host key into the job and keep strict checking on."

  1. Locate the actual SSH client inside the job or container.
  2. Obtain the expected host public key through reviewed provisioning or an independent management channel.
  3. Write that verified entry into the job-specific known_hosts file.
  4. Invoke SSH with StrictHostKeyChecking=yes.
  5. When an instance changes, approve and publish its new fingerprint before rerunning deployment.

Fix CodeBuild jobs with an explicit trust file

CodeBuild builds run inside managed or custom environments where ~/.ssh/known_hosts may be absent or recreated for each build. A failed SSH deploy from CodeBuild is not fixed by changing your personal laptop’s known_hosts. The fix belongs inside the build environment and its approved deployment configuration.

If the target is a stable host, inject its verified public host key into a file available to the build user and configure OpenSSH to use that file with strict checking. Store the trusted key in source-controlled infrastructure configuration when appropriate, or distribute it through a protected configuration service. A public host key is not a password, but its integrity matters because it establishes server identity.

You can use ssh -o UserKnownHostsFile=/path/verified_known_hosts -o StrictHostKeyChecking=yes to make the policy obvious in logs and commands. The file must contain a correctly formatted key associated with the exact hostname, address, and port. If a rebuild changes the fingerprint, update the trusted key through an independent workflow before the next deployment.

A failing build that logs only Host key verification failed should not be retried indefinitely. First confirm the deploy destination, whether DNS or Elastic IP moved, and whether the expected fingerprint changed. Retrying without an identity fix cannot make a mismatched trusted key become correct.

ssh -o UserKnownHostsFile=/path/verified_known_hosts \
    -o StrictHostKeyChecking=yes ec2-user@server.example.com

Understand stop/start, public IPv4, and Elastic IP moves

When a stopped EC2 instance with an automatically assigned public IPv4 address starts again, it can receive a different public address. If you keep connecting to the old address, you may reach nothing or possibly another resource later. The immediate repair is to discover the current public DNS or IP for the intended instance.

An Elastic IP keeps an address stable across supported lifecycle operations, but reassociating it to a replacement instance changes the machine behind the address. Your client may then see the old trusted host key associated with a server that legitimately has a different one. This is a classic host-key mismatch after infrastructure replacement.

Check the EC2 console instance details and the Elastic IP association before changing known_hosts. If you use a DNS name, also check its current destination and whether caching or a stale record could be leading the client elsewhere. Your SSH trust record can contain independent entries for the DNS name and the numerical address.

If the underlying machine and its host private keys have not changed, simply changing the public IP should not require regenerating server keys. The better question is whether the destination now refers to the same machine. Keep network-address changes separate from actual SSH host-key rotation during diagnosis.

ChangeExpected host keyWhat to check
Stop/start same EBS-backed instanceUsually unchangedCurrent public IPv4
Elastic IP moved to replacementOften changedNew instance fingerprint
Fresh image/new instanceOften changedBoot fingerprint from intended instance
DNS now points elsewhereDepends on destinationDNS answer and actual instance

Use EC2 Instance Connect for managed SSH entry

EC2 Instance Connect offers an AWS IAM-controlled route for delivering a short-lived SSH public key to supported Linux instances. It helps manage which user may authenticate without distributing one permanent client login key to everyone. The SSH server still has its own host identity, and that trust question does not disappear merely because authentication uses Instance Connect.

From the EC2 console, choose the instance, select Connect, and use the EC2 Instance Connect tab when the instance and network meet the prerequisites. The AWS CLI also provides aws ec2-instance-connect ssh --instance-id i-0123456789abcdef0 for supported environments. Permission, OS support, network access, and client prerequisites can vary.

For an independent host-key inspection, a verified EC2 Instance Connect console route may help you access the system and inspect /etc/ssh/ssh_host_*_key.pub. However, a conventional SSH client used through Instance Connect must still handle host-key verification appropriately. Treat convenience of login separately from trust in the destination.

When the instance is private, an EC2 Instance Connect Endpoint can provide a tunnel without making the instance publicly addressable, subject to endpoint configuration and security-group rules. A private path reduces exposure, but it does not authorize ignoring a changed host key inside SSH.

Avoid public SSH host-key problems with Session Manager

If repeated rebuilds make public SSH maintenance painful, consider Session Manager for interactive administration. Session Manager is part of AWS Systems Manager and can open a shell without a public SSH listener when the instance is configured as a managed node. That changes the authentication and connectivity path rather than suppressing the SSH security check.

In the EC2 console, select the instance, choose Connect, and open the Session Manager tab. From a configured CLI environment, use aws ssm start-session --target i-0123456789abcdef0. The instance needs the necessary SSM Agent connectivity, instance profile permissions, and an authorized IAM principal.

For a standard Session Manager interactive shell, you are not establishing a conventional SSH connection and therefore skip the same SSH known_hosts trust path. SSH tunneled through Session Manager is different: when you run SSH over the tunnel, SSH still performs host-key checks. Distinguish those modes in your operational instructions.

Session Manager also supports administrative designs that keep port 22 off the public Internet. It is a sensible default for teams that already manage instance roles and access through IAM. If Session Manager cannot connect, troubleshoot its own prerequisites rather than weakening SSH verification as a workaround.

Jake: "Could I stop opening SSH to the internet whenever I replace the server?"

Ethan: "A normal Session Manager shell can skip public SSH entirely when the instance is configured for it. SSH tunneled through a session still has SSH host-key checks."

aws ssm start-session --target i-0123456789abcdef0

Use ssh-keyscan and host-key inspection without trusting the network blindly

You may see ssh-keyscan -t ed25519 203.0.113.10 recommended as a quick way to update known_hosts. It fetches a public host key from whatever server responds over the current network path. That makes it a useful collection command but not proof that the responder is your intended EC2 instance.

To make keyscan useful, compare the fingerprint of its output with one obtained through the EC2 system log or a separately trusted session. A command such as ssh-keygen -lf verified_host_key.pub can display the SHA256 fingerprint of a saved public host key. Match the algorithm and full digest, not just a shortened prefix.

If the fingerprints match, you can add a correctly formatted known_hosts entry for the intended destination. Be aware that ssh-keyscan output uses hostnames followed by the key type and base64 public key. Keep it associated with the exact host and port your deployment actually uses.

For multiple instances behind one DNS name, ordinary host-key pinning may be unsuitable if separate SSH servers answer unpredictably. Route SSH to a stable, specifically identified host or use managed access channels. Suppressing trust checks because the destination rotates is treating an architecture mismatch as a client setting problem. If you must use a shared access name, establish a deliberate identity model such as approved host certificates or a stable managed jump host. Record what the client expects, how it gets the expected key, and who approves replacements. A deployment pipeline that knows only a changing IP address has no reliable basis for accepting a brand-new host identity on its own.

ssh-keyscan -t ed25519 203.0.113.10 > candidate_host_key.pub
ssh-keygen -lf candidate_host_key.pub
# Compare this digest against your independent EC2 fingerprint

Diagnose still-failing connections after removing the old entry

If your client still reports the same warning after ssh-keygen -R, inspect whether you connected using a different name, IP, or port than the one you removed. A DNS alias and a literal IP can produce separate known_hosts entries. Your client may also have a custom UserKnownHostsFile or a system-wide file.

Use ssh -v or, where helpful, ssh -G hostname to inspect the effective connection configuration. Confirm whether you are running OpenSSH from macOS, Linux, Windows, WSL, a container, or a CI runner. Removing a key on your laptop cannot change the key store inside an isolated build container.

If the server fingerprint changes between consecutive attempts without an intentional rebuild, stop and investigate. The destination might resolve to multiple instances, an intermediary might be misconfigured, or an attacker could be present. Compare the actual addresses and EC2 associations and establish a trustworthy identity path before any fresh acceptance.

If the warning is gone but you now see Permission denied (publickey), host-key verification has succeeded and you are dealing with client authentication. Check the login user, client private key, and server authorized keys separately. Mixing those two stages leads to unnecessary host-key rotation and extra confusion.

SymptomLikely next checkAction
Mismatch repeatsDifferent known_hosts fileInspect ssh -v and ssh -G
Mismatch alternatesDifferent server answersAudit DNS, EIP and routing
Permission denied publickeyClient authenticationCheck username and login key
CI onlyContainer trust storeInstall verified key in job

Document a repeatable safe workflow for rebuilt EC2 fleets

For teams rebuilding instances regularly, plan host identity into the deployment process instead of repairing it ad hoc. Record the instance ID, expected connection address, and host-key fingerprint when provisioning finishes. Publish the trust record through a controlled channel that deployers and CI jobs can retrieve without relying on the same unverified SSH connection.

Treat an Elastic IP reassociation as an event that may require a new host-key trust record. Update the record only after mapping the Elastic IP to the new instance and comparing the new fingerprint with an account-controlled source. This is a small operational step that preserves the protection SSH was designed to provide.

For long-lived hosts, maintain stable host keys when that is an intentional and secure part of your server lifecycle; for immutable fleets, prefer per-instance identities and automation that distributes verified public keys. Baking one reusable SSH host private key into every cloned image deserves a deliberate security review first.

Your runbook should identify who approves a host-key rotation, where the new fingerprint comes from, and how old records are retired. Include separate instructions for human OpenSSH, Windows PuTTY, and ephemeral CI environments. This creates one consistent process rather than a collection of one-time exceptions.

For example, a small deployment fleet might replace two instances every month and use one stable alias for each environment. Without an identity registry, each replacement leads to an emergency manual deletion in somebody’s terminal. A reviewed record that maps environment, instance ID, destination, and fingerprint makes the change predictable and auditable rather than a recurring surprise.

Account for users who connect by both private IP and public DNS. If your scripts switch between those names, your host-key policy should define which identity is authoritative and how each entry is updated. Keep any approved automation scoped to the required hosts so it cannot silently overwrite unrelated trust decisions.

Handle nonstandard ports, SSH aliases, and multiple host algorithms

When you connect to a custom SSH port, the hostname recorded in known_hosts is usually stored together with the port, rather than under the ordinary port 22 name. That means removing a plain IP entry may leave an old bracketed entry in place. First look at the port in your actual SSH command or configuration, and then use ssh-keygen -R with the matching bracketed form.

An SSH config alias also changes the picture. You might connect with ssh booking-prod while the HostName setting points at ec2-203-0-113-10.example or an address that changed after the rebuild. Use ssh -G booking-prod to inspect the effective HostName, Port, and UserKnownHostsFile values. Fix the record for the identity SSH actually checks, rather than assuming the friendly alias is the entire story.

Your server may advertise multiple SSH host key algorithms. If the client had a trusted RSA key but now negotiates ED25519, the displayed fingerprint could be different even for the same server. Compare like with like: match the algorithm named in the SSH output to the corresponding key fingerprint in the EC2 system log. The full SHA256 digest matters; two fingerprints should not be considered equivalent because they came from one instance.

System-wide known_hosts entries can also cause warnings when the user-level entry has been removed. Your organization may provision those records centrally to ensure machine identity is controlled. If you cannot change the system trust file, follow the administrative approval process rather than overriding it with a second incompatible entry. A centrally managed host-key change should be reviewed and distributed consistently.

Recognize when SSH host certificates change the best repair

If your organization uses OpenSSH host certificates, the security model differs from manually pinning a separate raw host key for every EC2 instance. A trusted host certificate authority can sign server identities, and clients can trust that CA for designated names through known_hosts configuration. This can reduce the operational burden of rotating individual host keys across short-lived fleets.

Host certificates are not automatically issued by EC2 simply because you launched an instance. Your team must design the certificate authority, signing workflow, permitted host identities, expiration, and revocation procedures. A bare host-key fingerprint mismatch on an unmanaged server is not resolved by inventing a CA entry on the client. Use this design only if you already have, or deliberately establish, a trustworthy issuance system.

For rapidly replaced instances, the certificate can bind a DNS name or approved instance identity to the new host public key during provisioning. The client verifies the signed certificate against its configured CA rather than relying on a manually updated per-instance fingerprint. This shifts the crucial trust decision to protecting the CA signing key and correctly validating issuance requests.

Certificate expiry introduces an additional operational failure mode. If the host certificate is expired, signed for the wrong hostname, or issued by an untrusted CA, SSH should refuse it. Investigate the certificate and trust policy rather than setting StrictHostKeyChecking=no. A well-managed certificate workflow can make rebuilds smoother, but a poorly managed one merely hides another source of identity uncertainty. Before rolling host certificates into an existing environment, inventory which clients and automation jobs connect by DNS, IP address, or SSH alias. Ensure the certificate principals cover the identities those clients actually verify. Plan a migration period in which trust configuration is distributed before servers switch to certificate presentation. Keep a secure break-glass management path for the day a certificate is accidentally issued for the wrong identity. Also document how to rotate the trusted CA rather than assuming it will live forever.

Investigate an unexpected host-key change as a security incident

When no one approved a rebuild, key rotation, DNS change, or Elastic IP reassignment, a changed SSH host key deserves an incident response rather than a routine cleanup. Start by preserving the original warning, its presented fingerprint, timestamp, destination address, and the source workstation or runner. Hold off on installing the newly presented key automatically, because doing so can destroy the evidence of the mismatch in your trust store.

Check the EC2 instance and network resources in the correct account and Region. Identify which network interface owns the address, whether Elastic IP reassociations or replacement instances occurred, and whether a deployment system changed DNS. Use the organization’s cloud activity logs and change records to determine whether those events were authorized. If the trusted control-plane records and the observed network key disagree, keep the connection blocked.

If you suspect DNS manipulation, test resolution from a separate trusted environment and compare results. If multiple addresses are expected, make sure your SSH design identifies one specific host rather than a round-robin pool of unrelated host keys. If the target is inside a private network, audit jump hosts, tunnels, and any proxy settings that affect the route. Each hop can change which endpoint the SSH client ultimately contacts.

Containment might involve restricting the affected destination, pausing automated deployments that send credentials there, and using Session Manager or another management channel to inspect the intended instance. Rotate exposed credentials only when there is a reason to suspect compromise and according to your security procedures. Restoring production access is important, but trusting an unverified server can convert a brief outage into a larger incident.

Gather evidence before opening an AWS Support case

If an unexpected fingerprint persists and you cannot establish which instance answers, gather the destination hostname, resolved IP, EC2 instance ID, Region, and timestamps. Record the SSH host-key algorithm and fingerprint reported by your client, but keep private keys and account secrets out of support tickets. The precise error variant can help distinguish first contact, mismatch, and an authentication failure.

Collect the instance system log from EC2 and note whether it includes a fingerprint block for the key type you negotiated. Document recent Elastic IP reassociations, instance rebuilds, AMI restoration, or security changes. Where appropriate, capture ssh -v output after redacting sensitive command arguments and environment details.

If the incident resembles an interception attempt, use an independent administrative access method and your organization’s security-response procedures. AWS Support can help examine EC2 configuration and platform behavior, but it cannot establish trust in an arbitrary third-party network endpoint on your behalf. Identity verification must remain part of your investigation.

If all evidence supports a routine replacement, the recovery is usually local and does not require a support case. Verify the new fingerprint, remove the specific old record, and reconnect. If the data disagree, preserve them instead of repeatedly accepting different keys until a connection happens to work.

Jake: "When should I stop trying and open a case?"

Ethan: "When the identity evidence disagrees, preserve the fingerprints and ask for help. A successful login is not worth trusting the wrong server."

A useful initial report is: “After EC2 instance replacement, SSH to this Elastic IP reports a changed host key. The destination is associated with instance ID [ID], and the system-log ED25519 fingerprint differs from the key presented by the network. Please help investigate the EC2 association and console output; I have not accepted the unverified key.” Adjust the description to the actual facts rather than copying a claim you have not established.

If the fingerprints match and the failure instead becomes a private-key authentication problem, revise the ticket category accordingly. A clear separation between host identity and user authentication saves time. It also prevents unnecessary regeneration of keys and avoidable changes to working security policies.

Frequently asked questions about EC2 SSH host keys

What does Host key verification failed mean on an EC2 instance?

Your SSH client does not trust the host identity currently presented for the destination. A stale known_hosts entry is common after a legitimate rebuild, but an unexpected change can indicate a wrong destination or interception. Verify the replacement fingerprint independently before changing the record.

Does this SSH message mean my EC2 instance is being attacked?

Not necessarily. Rebuilds, reassigned Elastic IP addresses, and DNS mistakes can cause the same warning. Treat an unexplained mismatch as a security concern until you establish the server identity through a trusted source.

How do I remove an old EC2 host key safely?

After verifying the new instance fingerprint, run ssh-keygen -R followed by the exact hostname or IP used in SSH. For nonstandard ports, use the bracketed host-and-port form. Reconnect and confirm that the newly presented fingerprint matches your independent source.

How do I find the real SSH host key fingerprint in AWS EC2?

Open the instance in the EC2 console and choose Actions, Monitor and troubleshoot, Get system log. Search for BEGIN SSH HOST KEY FINGERPRINTS if the image provides that output. Alternatively use the AWS CLI get-console-output command or a separately trusted administrative session to inspect the host public key.

Why does SSH fail after moving an Elastic IP to a new instance?

Your computer remembers the SSH host key associated with that address. A replacement instance commonly generates a different server host key, so the existing trust record conflicts. Validate the new instance fingerprint before replacing the entry.

Why does an SSH warning appear after EC2 stop and start?

A stop and start can change an automatically assigned public IPv4 address, leaving your client or DNS using an outdated destination. The same persistent instance generally retains its SSH host keys unless they were regenerated. Confirm the current address and actual instance identity.

Should I use StrictHostKeyChecking=no to fix EC2 SSH?

That option weakens the host identity check rather than establishing the correct server. Prefer independently verifying the new fingerprint and updating only the stale entry. Keep strict checking enabled for routine and automated connections.

Is the EC2 key pair fingerprint the same as the SSH host fingerprint?

No. The EC2 key pair typically authenticates the connecting user, while the SSH host key identifies the server. To validate a changed server identity, compare its SSH host-key fingerprint rather than the fingerprint of your login key pair.

Where is known_hosts on Windows OpenSSH?

The usual per-user path is under C:\Users\YourUser\.ssh\known_hosts. PowerShell OpenSSH supports ssh-keygen -R just like Linux and macOS. WSL, Git Bash, and other clients may use different files.

How do I fix a PuTTY host key mismatch for EC2?

Read the PuTTY security alert and independently validate the new server fingerprint. Update only the affected cached host-key entry using PuTTY cache management. Changing OpenSSH known_hosts alone does not clear PuTTY’s separate cache.

How do I fix Host key verification failed in GitHub Actions?

Place an independently verified SSH host public key in the runner or container known_hosts file. Keep strict checking enabled and make sure the file belongs to the SSH client actually issuing the request. Update the trusted key through your reviewed deployment process when the instance changes.

How do I fix this error in AWS CodeBuild?

Inspect the CodeBuild environment’s SSH configuration rather than your workstation. Install a verified known_hosts entry in the build environment and use StrictHostKeyChecking=yes. If an instance was replaced, validate and update the key before retrying the job.

Can ssh-keyscan verify that my EC2 server is genuine?

ssh-keyscan collects the key offered by the network endpoint but does not independently authenticate it. Compare its fingerprint with the EC2 console system log or another trusted channel. Only then use the collected public key as a trust entry.

Does EC2 Instance Connect avoid host key verification?

EC2 Instance Connect simplifies client SSH authentication through IAM-controlled short-lived keys. A normal SSH connection still has host identity checks. It does not justify blindly accepting a changed SSH server fingerprint.

Can Session Manager replace SSH access to EC2?

A standard Session Manager interactive shell can administer a properly configured managed instance without a public SSH port. It relies on SSM Agent connectivity and appropriate IAM permissions. When SSH is tunneled over Session Manager, SSH host-key verification still applies.

Why does the warning persist after I run ssh-keygen -R?

You may have removed the IP entry while connecting by hostname, selected a different port, or used another known_hosts file inside WSL or CI. Inspect ssh -v and the effective SSH configuration. If the fingerprint genuinely keeps changing, investigate the destination instead of repeatedly deleting records.

Jake’s repair booking server can come back online without abandoning the protection SSH gives him. When a rebuilt EC2 instance answers behind a familiar address, make identity verification the first step and known_hosts cleanup the second. If your fingerprints disagree or the destination keeps changing, investigate that discrepancy before logging in. May your next rebuild be routine, and your host-key warnings always mean something useful.

📌 If you keep one line from this page

Verify the new EC2 host-key fingerprint independently before deleting the old known_hosts entry and reconnecting.

Revision note. Written October 15, 2026, with Instance Connect and Session Manager as the recommended paths. Trust, but verify: compare the fingerprint before you delete the old entry.

Related