'Ansible: read value of become option in playbook

Is it possible to get value of parameter --become in a playbook?
For example, if the flag --become is present, I expect to get true, and false otherwise.

I used to think that there was a become variable, but actually it is absent.

Ideally, I want to use something like:

- name 
  become: {{ become }} 


Solution 1:[1]

You could write something like this:

- hosts: localhost
  gather_facts: false
  tasks:
    - name: get UID
      become: "{{ myvar|default(false)|bool }}"
      command: id
      register: uid

    - debug:
        var: uid.stdout

If we run it like this:

ansible-playbook playbook.yml

We get:

TASK [debug] *******************************************************************
ok: [localhost] => {
    "uid.stdout": "uid=1000(lars) gid=1000(lars) ..."
}

Whereas if we set myvar=true:

ansible-playbook playbook.yml -e myvar=true

We get:

TASK [debug] *******************************************************************
ok: [localhost] => {
    "uid.stdout": "uid=0(root) gid=0(root) groups=0(root) context=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023"
}

We use myvar|default(false)|bool so that if myvar isn't set, we get the boolean value false, and if myvar is set to the string value "false", the bool filter turns that into false, because otherwise a non-empty string evaluates to true in a boolean context.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 larsks