Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there anyway to run multiple Ansible playbooks as multiple users more efficiently?

Currently my playbook structure is like this:

~/test_ansible_roles ❯❯❯ tree .
.
├── checkout_sources
│   └── tasks
│       └── main.yml
├── install_dependencies
│   └── tasks
│       └── main.yml
├── make_dirs
│   └── tasks
│       └── main.yml
├── setup_machine.yml

One of the roles that I have is to install dependencies on my box, so for this I need sudo. Because of that all of my other tasks I need to include the stanza:

   become: yes
   become_user: my_username

Is there a better way to do this ?

like image 275
Muhammad Lukman Low Avatar asked May 13 '16 02:05

Muhammad Lukman Low


1 Answers

You can set the become options per:

  • play
  • role
  • task

Per play:

- hosts: whatever
  become: true
  become_user: my_username
  roles:
    - checkout_sources
    - install_dependencies
    - make_dirs

Per role:

- hosts: whatever
  roles:
    - checkout_sources
    - role: install_dependencies
      become: true
      become_user: my_username
    - make_dirs

Per task:

- shell: do something
  become: true
  become_user: my_username

You can combine this however you like. The play can run as user A, a role as user B and finally a task inside the role as user C.

Defining become per play or role is rarely needed. If a single task inside a role requires sudo it should only be defined for that specific task and not the role.

If multiple tasks inside a role require become, blocks come in handy to avoid recurrence:

- block:
    - shell: do something
    - shell: do something
    - shell: do something
  become: true
  become_user: my_username
like image 116
udondan Avatar answered Sep 20 '22 15:09

udondan