How to get an arbitrary remote user’s home directory in Ansible?

Question:

I can do that with shell using combination of getent and awk like this:

For the reference, in Puppet I can use a custom fact, like this:

which makes the user’s home directory available as a home_<user name> fact.

How do I get the home directory of an arbitrary remote user?

Answer:

Ansible (from 1.4 onwards) already reveals environment variables for the user under the ansible_env variable.

Unfortunately you can apparently only use this to get environment variables for the connected user as this playbook and output shows:

OUTPUT:

As with anything in Ansible, if you can’t get a module to give you what you want then you are always free to shell out (although this should be used sparingly as it may be fragile and will be less descriptive) using something like this:

There may well be a cleaner way of doing this and I’m a little surprised that using become_user to switch to the user specified doesn’t seem to affect the env lookup but this should give you what you want.

Leave a Reply