How to get sudoed user home directory from ansible_env?

When I sudo as a user, ansible_env does not have the correct HOME set - "/ root" . However, if I repeat the HOME env variable, it is correct - "/ var / lib / pgsql" . Is there any other way to get sudo'ed's home directory?

In addition, I already set "sudo_flags = -H" to ansible.cfg, and I cannot log in as the postgres user.

- name: ansible_env->HOME sudo: yes sudo_user: postgres debug: msg="{{ ansible_env.HOME }}" - name: echo $HOME sudo: yes sudo_user: postgres shell: "echo $HOME" register: postgres_homedir - name: postgres_homedir.stdout sudo: yes sudo_user: postgres debug: msg="{{ postgres_homedir.stdout }}" 

Result:

 TASK: [PostgreSQL | ansible_env->HOME] **************************************** ok: [postgres] => { "msg": "/root" } TASK: [PostgreSQL | echo $HOME] *********************************************** changed: [postgres] TASK: [PostgreSQL | postgres_homedir.stdout] ********************************** ok: [postgres] => { "msg": "/var/lib/pgsql" } 
+5
source share
2 answers

I can reproduce the result above by running the playbook as root (locally with - hosts: localhost or SSHing as root). The facts collected by Ansible are root user data.

If this is what you are doing, then your workaround seems to be the best way to get the $ HOME variable for postgres.

Even if you add sudo_user: postgres to the ansible_env->HOME task, this fact will not change since it is compiled at the beginning of playback.

+1
source

"~" expands as a non-root user if you use "become: no". In the example below, I combine this with an explicit "sudo" to do something like root in the home directory:

 - name: Setup | install command: sudo make install chdir=~/git/emacs become: no 
0
source

All Articles