0

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.

Community
  • 1
  • 1
Prakash
  • 279
  • 1
  • 6
  • 18

2 Answers2

0

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] }}"
tux
  • 1,730
  • 1
  • 15
  • 19
  • Wrong. All lookups are executed on control host under account which executes ansible cli. – Konstantin Suvorov May 19 '17 at 12:55
  • @KonstantinSuvorov Thank you, I did not knew about this, I will change the answer accordingly – tux May 19 '17 at 12:56
  • @deepak thanks Deepak I will test it. According to your answer "remote_user" should be the user whose authorized_keys we want and not the user which we use control other machines right? – Prakash May 19 '17 at 14:44
  • the remote_user is the user whom you will connect as to the remote machine. the variable username, is the one which specifies the user for whom, you would require the authorized_keys – tux May 19 '17 at 16:30
  • @deepak Thank you. – Prakash May 21 '17 at 07:39
0

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
Prakash
  • 279
  • 1
  • 6
  • 18