Interview Prep/Ansible/Variables, Facts and Precedence Problems

`{{ ansible_env.HOME }}` resolves to `/root`, and files land in the wrong home directory

IntermediateTroubleshootingVariables, Facts and Precedence Problems
Answer

Likely causes → Facts were gathered with become: true at play level, so the environment facts describe root. ansible_env is a snapshot from fact gathering, not from the current task's user.

Fix → Look up the home directory of the user you actually mean:

- ansible.builtin.getent:
    database: passwd
    key: deploy
- ansible.builtin.set_fact:
    deploy_home: "{{ ansible_facts.getent_passwd['deploy'][4] }}"

Or use "~deploy" paths where the module expands ~.

Prevent → Do not depend on ansible_env for paths. Make the user's home an explicit role variable.

All Ansible questions Roadmap: Ansible

More on Variables, Facts and Precedence Problems