Mystic
Mystic

Reputation: 141

Single Ansible task for become yes and no

I have a lot of tasks running for the user and superuser. Most of them load configs via the template module. Question:

  1. Is it possible to complete somehow the same task for both a regular user and a superuser? Those. do not do two tasks, one with become: no, and the other with yes.
  2. Are there any conditions for template to distinguish become, so that at least one template is used.

I have quite a lot of experience with ansible and have read a lot of documentation and googled. Probably what I need is simply impossible, but suddenly someone came up with a crutch. Thanks.

Upvotes: 1

Views: 995

Answers (1)

larsks
larsks

Reputation: 312500

Ansible evaluates the become statement only once for the task, so if you were to write a task like this:

    - become: "{{ item|bool }}"
      command: id
      register: result
      loop:
        - false
        - true

It would always run with become: false; if you were to switch the order of the items in the loop, it would always run with become: true. However, the become_user setting can be set from a loop variable, so you can do something like this:

    - become: true
      become_user: "{{ item }}"
      command: id
      register: result
      loop:
        - root
        - "{{ ansible_user_id }}"

    - debug:
        var: result.results|map(attribute='stdout')|list

Running these tasks on my local system results in the following output:

TASK [command] *****************************************************************
changed: [localhost] => (item=root)
changed: [localhost] => (item=lars)

TASK [debug] *******************************************************************
ok: [localhost] => {
    "result.results|map(attribute='stdout')|list": [
        "uid=0(root) gid=0(root) groups=0(root) context=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023",
        "uid=1000(lars) gid=1000(lars) groups=1000(lars),10(wheel),18(dialout),983(libvirt) context=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023"
    ]
}

PLAY RECAP *********************************************************************
localhost                  : ok=3    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

Upvotes: 2

Related Questions