Skip to content

Instantly share code, notes, and snippets.

@mgedmin
Last active September 27, 2015 18:44
Show Gist options
  • Save mgedmin/37d38501bdf44b724654 to your computer and use it in GitHub Desktop.
Save mgedmin/37d38501bdf44b724654 to your computer and use it in GitHub Desktop.
Managing /etc/ssh/ssh_known_hosts in Ansible

My group_vars/all has this:

ssh_host_keys:
  github: |
    github.com ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAq2A7hRGmdnm9tUDbO9IDSwBK6TbQa+PXYPCPy6rbTrTtw7PHkccKrpp0yVhp5HdEIcKr6pLlVDBfOLX9QUsyCOV0wzfjIJNlGEYsdlLJizHhbn2mUjvSAHQqZETYP81eFzLQNnPHt4EVVUh7VfDESU84KezmD5QlWpXLmvU31/yMf+Se8xhHTvKSCZIFImWwoG6mbUoWf9nzpIoaSjB+weqqUUmpaaasXVal72J+UX2B+2RPW3RcT0eOzQgqlJL3RKrTJvdsjE3JEAvGq3lGHSZXy28G3skua2SmVi/w4yCE6gbODqnTWlg7+wC604ydGXA8VJiS5ap43JXiUFFAaQ==
  myserver1: |
    myserver1.example.com ssh-rsa AAA...
    myserver1.example.com ssh-dss AAA...
    myserver1.example.com ssh-ecdsa-sha2-nistp256 AAA...
  myserver2: |
    myserver2.example.com ssh-rsa AAA...
    myserver2.example.com ssh-dss AAA...

My group_vars/somegroup (or host_vars/somehost) contain these:

known_hosts:
  - github
  - myserver1
  - myserver2

And then I have a task in my 'common' role to assemble and deploy /etc/ssh/ssh_known_hosts from the above.

  • roles/common/defaults/main.yml:

    # hostnames to include in /etc/ssh/ssh_known_hosts
    # (for each of them there should be a host key in ssh_host_keys[item])
    known_hosts: []
    
    # mapping of hostnames to multiline strings containing public host keys
    # (must repeat hostname in front of ssh-dss/rsa/ecdsa on each line)
    ssh_host_keys: {}
    
  • roles/common/vars/main.yml:

    ssh_known_hosts: "{% for item in known_hosts %}{{ssh_host_keys[item]}}{% endfor %}"
    
  • roles/common/tasks/known-hosts.yml:

    - name: /etc/ssh/ssh_known_hosts
      copy: content="{{ ssh_known_hosts }}" dest=/etc/ssh/ssh_known_hosts
      when: ssh_known_hosts != ""
      tags: [ ssh, known-hosts ]
    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment