How to get the list of authorized_keys of a given user?

2.5k views Asked by At

I want to write a ansible playbook where we can provide a username and ansible will display the authorized keys for that user. The path to the authorized keys is {{user_home_dir}}/.ssh/authorized_keys.

I tried with shell module like below:

---
- name: Get authorized_keys 
  shell: cat "{{ user_home_dir }}"/.ssh/authorized_keys
  register: read_key

- name: Prints out authorized_key 
  debug: var=read_key.stdout_lines

The problem is, it will show me the file inside /home/ansible/.ssh/authorized_keys. "ansible" is the user that I am using to connect to remote machine.

Below is vars/main.yml

---
authorized_user: username
user_home_dir: "{{ lookup('env','HOME') }}"

Any idea? FYI I am new to ansible and tried this link already.

2

There are 2 answers

5
tux On

In your vars file, you have

user_home_dir: "{{ lookup('env','HOME') }}"

Thanks to Konstantin for pointing it out... All lookups are executed on the control host. So the lookup to env HOME will always resolve to the home directory of the user, from which ansible is being invoked.

You could use the getent module from ansible to retrieve an user's info. The below snippet should help

---

- hosts: localhost
  connection: local
  remote_user: myuser
  gather_facts: no

  vars:
    username: myuser

  tasks:

    - name: get user info
      getent:
        database: passwd
        key: "{{ username }}"
      register: info

    - shell: "echo {{ getent_passwd[username][4] }}"
0
Prakash On

Below worked. We need to have become too otherwise we will get permission denied error.

---
- hosts: local
  remote_user: ansible
  gather_facts: no
  become: yes
  become_method: sudo

  vars:
    username: myuser

  tasks:

    - name: get user info
      getent:
        split: ":"
        database: passwd
        key: "{{ username }}"

    - name: Get authorized_keys
      shell: cat "{{ getent_passwd[username][4]  }}"/.ssh/authorized_keys
      register: read_key

    - name: Prints out authorized_key
      debug: var=read_key.stdout_lines