Using authorized_key module in a playbook to set up SSH key for new users


Question

Scenario:

Based on the [clients] section of the hosts file do the following:

  1. Check if the SSH login of user "foo" fails and if yes
  2. Add SSH keys for user "foo" using authorized_key module
  3. Assuming that user "foo" already exists on remote machine and SSH public key has already been created on the local (ansible) host

I am aware of this solution using Ansible command line but I would like to be able to put this into a playbook. It's acceptable to make script interactive with user typing in password including sudo.

Right now I figured out how to do what I want using 3-rd party role GROG.authorized-key but it still requires me to run playbook with -K switch. Is there something in Ansible (beside command line switches) that would only prompt for the password if it is needed?

- hosts: clients
  vars:
    authorized_key_list:
      - name: pdo
        authorized_keys:
         - key: "{{ lookup('file', '/home/pdo/.ssh/id_rsa.pub') }}"
           state: present
  roles:
    - { role: GROG.authorized-key }
1
1
5/23/2017 12:33:25 PM

I think based on your comments this should work:

- hosts: clients
  become: true
  tasks: 
  - name: Add authorized_key to pdo user on the remote client machine(s)
    authorized_key: user=foo key="{{ lookup('file', '/home/pdo/.ssh/id_rsa.pub') }}"

Call it with -K to get the become password question. This will make a sudo command on the remote machine. Thats what you need, isn't it?

1
4/20/2016 10:35:03 AM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon