Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ansible become_user with variable

I am using Ansible 2.1.0.0

I try to use become_user with a variable in a task, but I receive the following message:

fatal: [host]: FAILED! => {"failed": true, "msg": "'ansible_user' is undefined"}

The task executing this is

- name: Config git user name
  git_config: name=user.name scope=global value={{ ansible_host }}
  become: Yes
  become_user: "{{ansible_user}}"

And the playbook has the following line to define the remote user:

- name: Foo
  hosts: foo
  vars:
    http_port: 80
  remote_user: admin

I've seen this response which seems to be the same problem, but this does not work for me.

I have seen also a set_fact solution but I would like to use the remote_user var if possible so no extra lines must be added if a playbook already has the remote_user var set.

Does anyone know how to do this or what I am doing wrong?

like image 340
Hugo Avatar asked Jun 23 '16 12:06

Hugo


People also ask

What is become_user in Ansible?

Ansible become_user is to run a particular task as a specific user in general Unix command it can be done with sudo -u <theusername> to use become_user you should also set the become to yes.

How are variables referenced in an Ansible template?

Special Variables Ansible provides a list of predefined variables that can be referenced in Jinja2 templates and playbooks but cannot be altered or defined by the user. Collectively, the list of Ansible predefined variables is referred to as Ansible facts and these are gathered when a playbook is executed.

How do you mention sudo privilege in Ansible?

To specify a password for sudo, run ansible-playbook with --ask-become-pass ( -K for short). If you run a playbook utilizing become and the playbook seems to hang, most likely it is stuck at the privilege escalation prompt. Stop it with CTRL-c , then execute the playbook with -K and the appropriate password.

Should I run Ansible as root?

Note: Ansible does not require root access; however, if you choose to use a non-root user, you must configure the appropriate sudo permissions for the tasks you want to accomplish. You will be prompted for the root password for servera, which will allow your SSH key to be installed on the remote host.


1 Answers

What about that:

- name: Foo
  hosts: foo
  vars:
    http_port: 80
    my_user: admin
  remote_user: "{{my_user}}"

then:

- name: Config git user name
  git_config: name=user.name scope=global value={{ ansible_host }}
  become: Yes
  become_user: "{{my_user}}"
like image 157
michael_bitard Avatar answered Oct 04 '22 20:10

michael_bitard