Skip to content

Instantly share code, notes, and snippets.

@mwik
Created February 19, 2018 21:14
Show Gist options
  • Save mwik/ee93698ab76931273af5ac479af37546 to your computer and use it in GitHub Desktop.
Save mwik/ee93698ab76931273af5ac479af37546 to your computer and use it in GitHub Desktop.
Ansible playbook to get ssh host keys from Azure virtual machines
---
- hosts: localhost
gather_facts: no
vars:
home: "{{ lookup('env','HOME') }}"
tasks:
- name: Fetch SSH public keys
shell: 'az vm run-command invoke --name {{item}} --command-id RunShellScript --scripts "cat /etc/ssh/ssh_host_ecdsa_key.pub" --query output[0].message | grep -o "ecdsa-sha2-nistp256 .*="'
register: host_key
with_items: "{{groups['all']|sort}}"
- name: Import SSH public keys
lineinfile:
dest: "{{home}}/.ssh/known_hosts"
line: "{{item.1}}.example.com,{{hostvars[item.1].private_ip}}{{(hostvars[item.1].public_ip is none)|ternary('', ',' + [hostvars[item.1].public_ip]|join(''))}} {{host_key.results[item.0].stdout}}"
with_indexed_items: "{{groups['all']|sort}}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment