Skip to content

Instantly share code, notes, and snippets.

@jonprindiville
Last active May 17, 2019 21:17
Show Gist options
  • Save jonprindiville/2fcc5dfe163601b72bfbb4c238a9d496 to your computer and use it in GitHub Desktop.
Save jonprindiville/2fcc5dfe163601b72bfbb4c238a9d496 to your computer and use it in GitHub Desktop.
GitHub -> known_hosts

Some commands for use in Circle CI config related to the task of getting GitHub's SSH keys into your known_hosts file.

Why is that useful? It's useful to me because I have some Circle CI jobs where I create a new branch, push it back to GitHub and create a PR. Without having a github.com entry in your known_hosts file, the git push would fail. I mean, really it would hang waiting for user input with a prompt like:

The authenticity of host 'github.com (...)' can't be established.
RSA key fingerprint is [...].
Are you sure you want to continue connecting (yes/no)?

Anyway, here's a couple commands you can add to your Circle configs to help get GitHub into your known_hosts file without too much fuss.

You should add these in under the top-level commands attribute of your version 2.1 config.yml. The version is important, commands was introduced in 2.1.

add_github_to_known_hosts:
description: Adds Github SSH keys to known_hosts
# The fingerprints given below were fetched from Github on 17-05-2019:
# https://help.github.com/en/articles/githubs-ssh-key-fingerprints
steps:
- add_key_to_known_hosts:
domain: github.com
key_type: dsa
fingerprint: "SHA256:br9IjFspm1vxR3iA35FWE+4VTyz1hYVLIE2t1/CeyWQ"
- add_key_to_known_hosts:
domain: github.com
key_type: rsa
fingerprint: "SHA256:nThbg6kXUpJWGl7E1IGOCspRomTxdCARLviKw6E5SY8"
add_key_to_known_hosts:
description: Adds SSH key to known_hosts (if it matches a fingerprint)
parameters:
domain:
type: string
key_type:
type: string
fingerprint:
type: string
steps:
- run:
name: Add "<< parameters.key_type >>" key from << parameters.domain >> to known_hosts
command: |
# Fetch publicly available key
SCAN=$(ssh-keyscan -t << parameters.key_type >> << parameters.domain >>)
echo "*** scanned key: $SCAN"
# Compute fingerprint
SCAN_FINGERPRINT=$(echo "$SCAN" | ssh-keygen -lf - )
echo "*** scanned fingerprint: $SCAN_FINGERPRINT"
echo "*** known fingerprint: << parameters.fingerprint >>"
if [[ "$SCAN_FINGERPRINT" =~ "<< parameters.fingerprint >>" ]]; then
echo "Scanned key matches known fingerprint, adding..."
mkdir -p ~/.ssh
echo "$SCAN" >> ~/.ssh/known_hosts
chmod 0700 ~/.ssh
chmod 0600 ~/.ssh/known_hosts
else
echo "Scanned key does not match known fingerprint, not adding."
exit 1
fi
@jonprindiville
Copy link
Author

Oh... I guess this could be an orb 🤔

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment