known_hosts in CI: Pinning Host Keys Safely
known_hosts holds the host keys ssh trusts; in CI you build it deliberately so deploys are both verified and unattended.
The choice is between disabling host key checking (convenient, unsafe) and pre-seeding known_hosts (a little more setup, properly verified). This page covers doing it right in a pipeline.
What it does
known_hosts maps hostnames to their public host keys. On connection, ssh checks the server's presented key against this file. In CI you either scan keys in with ssh-keyscan or paste a pinned key from a secret, then point ssh at that file.
Common usage
mkdir -p ~/.ssh && chmod 700 ~/.ssh
# option A: scan the key (verify the fingerprint out of band)
ssh-keyscan host >> ~/.ssh/known_hosts
# option B: pin a known key from a CI secret (most secure)
printf '%s\n' "$KNOWN_HOSTS_ENTRY" >> ~/.ssh/known_hosts
chmod 600 ~/.ssh/known_hosts
ssh -o StrictHostKeyChecking=yes user@host "deploy.sh"Options
| Approach | What it does |
|---|---|
| ssh-keyscan host >> known_hosts | Fetch and trust the current host key |
| Pinned secret >> known_hosts | Trust a key value verified ahead of time |
| StrictHostKeyChecking=accept-new | Trust on first use, reject later changes |
| StrictHostKeyChecking=no | No verification (avoid for production) |
In CI
Pinning the exact host key string in a secret is the most secure option, since it does not trust whatever answers at deploy time. ssh-keyscan is fine when you verify the fingerprint once against the provider. Keep ~/.ssh at 700 and known_hosts at 600, and keep StrictHostKeyChecking on.
Common errors in CI
Host key verification failed. means the presented key is not in the file (empty scan, wrong port, or a rebuilt host). "WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!" means the pinned or scanned key no longer matches; update the pin or run ssh-keygen -R then re-scan. "Permanently added 'host' to the list of known hosts." is a normal informational message under accept-new.