3

Trying to add two people's Github public keys to a user's authorized users file. I am able to successfully retrieve the SSH keys:

---
- hosts: 127.0.0.1
  connection: local
  vars:
    my_users:
      belminf: "belminf"
      bob: "tmessins"
  tasks:
    - name: Retrieving all keys from GitHub
      shell: /usr/bin/curl https://github.com/{{ item.value }}.keys 2> /dev/null
      register: ssh_keys
      with_dict: my_users

    - debug: var=ssh_keys

However, I'm unsure how to loop through ssh_keys results and use authorized_keys task to add the retrieved keys.

My ridiculous attempt:

   - name: Adding keys to authorized_keys
      authorized_key: user=belminf key="{{ item }}" path=/home/belminf/test_auth state=present
      with_items: ssh_keys.results

Results in invalid key specified. Understandably but I'm out of ideas. Anyone?

Belmin Fernandez
  • 10,629
  • 26
  • 84
  • 145

3 Answers3

7

As of Ansible 1.9, the value for key can be a url, obviating the need for curling the url via the shell module.

Example:

- name: Add my SSH key
  authorized_key: user=jeffwidman key=https://github.com/jeffwidman.keys
Jeff Widman
  • 2,285
  • 3
  • 22
  • 20
6

OK, I made some tweak on your playbook, and here is the revised version

---
- hosts: 127.0.0.1
  connection: local
  vars:
    my_users:
      belminf: "belminf"
      bob: "tmessins"
  tasks:
    - name: Retrieving all keys from GitHub
      shell: /usr/bin/curl https://github.com/{{ item.value }}.keys 2> /dev/null
      register: ssh_keys
      with_dict: my_users

   - name: Adding keys to authorized_keys
      authorized_key: user=belminf key="{{ item.stdout }}" path=/home/belminf/test_auth state=present
      with_items: ssh_keys.results
      ignore_errors: yes

Some changes note:

  • On authorized_key module, the key was changed to item.stdout. The stdout was public key that you need.
  • On authorized_key module, I defined ignore_errors: yes to resume playbook execution whenever the your curl task failed to fetch, either internet problem or 404 Not found (like tmessins's key). Of course you can tweak it by controlling what defines failure so it still failed when other error happened.
masegaloeh
  • 17,978
  • 9
  • 56
  • 104
  • Works! I was trying to loop through the output of the command line-by-line assuming `authorized_key` only accepted one key as a parameter but apparently doesn't. Thanks! – Belmin Fernandez Feb 06 '15 at 11:50
0

It's really simple now:

- name: get github key(s) and update the authorized_keys file
  authorized_key:
    user: "{{ username }}"
    key: "https://github.com/{{ username }}.keys"

for detail, check this github role

arbabnazar
  • 499
  • 6
  • 9