Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the home directory of a sudoed user from ansible_env?

Tags:

ansible

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

Also, I have already set "sudo_flags = -H" in ansible.cfg and I cannot login as 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"
}
like image 743
rahul Avatar asked Apr 20 '15 06:04

rahul


1 Answers

I can replicate the output above by running the playbook as the root user (either locally with - hosts: localhost, or by SSHing as root). The facts gathered by Ansible are those of the root user.

If this is what you are doing, then your workaround seems to be the best way of getting the postgres user's $HOME variable.

Even though you add sudo_user: postgres to the ansible_env->HOME task, the fact will not change since it is gathered at the start of the play.

like image 177
jonatan Avatar answered Oct 15 '22 13:10

jonatan