Cannot use ansible_user with local connection

Viewed 2091

I have a playbook for running on localhost:

- hosts: localhost
  connection: local
  gather_facts: true
  roles:
    - role: foo
    - role: bar
    - role: baz

Then in various tasks I want to use ansible_user, but I get the error:

fatal: [localhost]: FAILED! => {"msg": "'ansible_user' is undefined"}

2 Answers

Okay figured it out.

In any task that uses become: true, e.g.:

- name: foo
  become: true
  file:
    path: /tmp/foo
    state: directory
    owner: "{{ansible_env.USER}}"       # cannot use {{ansible_user}}
    group: "{{ansible_env.USER}}"       # cannot use {{ansible_user}}
    mode: "0755"

So instead of ansible_user, we must use ansible_env.USER or ansible_env.USERNAME.

I think this is because ansible doesn't know which user to use - if it's a local connection, and we elevate permissions, then is the "ansible user" actually root, or is it the user running the playbook? Ansible gets confused so the variable is empty... I think.

(For this to work we must have gather_facts: true at the beginning of the play.)

Q: "Cannot use ansible_user with local connection."

A: There must be some kind of misconfiguration. The playbook below works as expected and there is no reason it wouldn't work with these tasks inside a role.

shell> cat playbook.yml
- hosts: localhost
  connection: local
  tasks:

    - debug:
        msg: "ansible_user [{{ ansible_user }}]"
      become: false
    - file:
        path: /tmp/foo
        state: directory
        owner: "{{ ansible_user }}"
        group: "{{ ansible_user }}"
      become: false

    - debug:
        msg: "ansible_user [{{ ansible_user }}]"
      become: true
    - file:
        path: /tmp/bar
        state: directory
        owner: "{{ ansible_user }}"
        group: "{{ ansible_user }}"
      become: true
Related