Black Friday 2025 – NPI EA (cat = Baeldung on Ops)
announcement - icon

Yes, we're now running our Black Friday Sale. All Access and Pro are 33% off until 2nd December, 2025:

>> EXPLORE ACCESS NOW

Partner – Orkes – NPI EA (cat=Kubernetes)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

1. Introduction

Some Ansible tasks require special user privileges for their execution. So, when running them, we switch to a user with the necessary privileges. However, as our playbook becomes larger, the privileges needed for each task may vary, necessitating a user switch for each task.

In this tutorial, we’ll go over how to switch a user per task in Ansible.

2. Using the Become Directives

The Become directives (particularly become and become_user) enable us to execute tasks as specific users. So, if we want to execute one task on our host with a user named baeldung and another with a user named baeldung_2, we’ll use the mentioned directives:

- name: Display Time and Install curl
  hosts: localhost

  tasks:
    - name: Display Current Time
      command: date
      become: true
      become_user: baeldung
    - name: Install curl
      apt:
        name: curl
        state: present
      become: true
      become_user: baeldung_2

In the play above, if we wanted to run any of the tasks as root, we would’ve specified become: true without become_user.

3. Switching Users for Tasks in a Block

We can define become and become_user using different users for as many tasks as we want. However, if we have a large playbook, specifying a different user for each task can be a lot of work.

Fortunately, we can group multiple tasks requiring similar privileges using the block keyword and define the same user for tasks in each block:

- name: Display Time, Return Username, Install curl, and Install wget
  hosts: localhost

  tasks:
    - name: Display Current Time and Return Username
      block:
        - name: Display Current Time
          command: date
        - name: Return Username
          command: whoami
      become: true
      become_user: baeldung

    - name: Install curl and wget
      block:
        - name: Install curl
          apt:
            name: curl
            state: present
        - name: Install wget
          apt:
            name: wget
            state: present
      become: true

In the play above, we have a block with two tasks: one that displays time and another that runs whoami. When we run the play, the baeldung user executes the tasks in the mentioned block, going by our become and become_user definitions at the block level.

The second block has a task that installs curl and another that installs wget. Since we specified become: true without a become_user directive, the root user executes both tasks.

Using the block keyword in the play enables us to define become and become_user twice instead of defining them four times.

4. Switching User at the Play Level

If the privilege required for tasks targeted for a specific set of hosts is the same, then we can use become and become_user at the play level. This way, we wouldn’t have to switch users for each task:

- name: Play A
  hosts: localhost
  become: true
  become_user: baeldung

  tasks:
    - name: Display Current Time
      command: date
    - name: Return Username
      command: whoami

- name: Play B
  hosts: 192.168.22.2
  become: true
  become_user: baeldung_2

  tasks:
    - name: Install curl
      apt:
        name: curl
        state: present
    - name: Install wget
      apt:
        name: wget
        state: present

Here, we have two plays, Play A and Play B, and each has two tasks. Play A‘s tasks display the time and return the username, and are executed as the baeldung user on localhost. Play B‘s tasks install curl and wget, and are executed as the baeldung_2 user on host 192.168.22.2.

We could’ve switched users for each task in both plays. However, to be more efficient, we declared the user once for each play. This option is ideal when the required escalation privileges are host-specific, not task-specific.

5. Switching User With Roles

Besides plays and blocks, we can group tasks requiring similar user privileges into roles, so we don’t have to switch users for each task.

To illustrate this, we’ll create two roles, roleA and roleB. In roleA‘s tasks directory, we’ll have one task that displays the date and one that returns the username:

$ cat roleA/tasks/main.yml
- name: Display Current Time
  command: date
- name: Return Username
  command: whoami

Then, in roleB‘s tasks directory, we’ll have one task that installs wget and another that installs curl:

$ cat roleB/tasks/main.yml
- name: Install curl
  apt:
    name: curl
    state: present
- name: Install wget
  apt:
    name: wget
    state: present

Next, we’ll call the roles in our play while defining the users to execute each role:

- name: play for roleA and roleB
  hosts: localhost
  roles:
    - name: roleA
      become: true
      become_user: baeldung
    - name: roleB
      become: true

When we run the play, the tasks in roleA will be executed by the user baeldung, while root will execute those in roleBOf course, this means we wouldn’t have to specify a different user for each task.

6. Switching Users Conditionally

We can switch users for each task in Ansible when certain conditions are met. For instance, we can run tasks as baeldung when our ansible_os_family is Debian but as root if it isn’t:

...
    - name: Return username
      command: whoami
      become: true
      become_user: "{{ 'baeldung' if ansible_os_family == 'Debian' else 'root' }}"

For even more flexibility, we can use conditionals at task, block, role, and play levels when switching users.

7. Conclusion

In this article, we discussed how to switch a user per task in Ansible. We also explored how to group tasks with the same privilege requirements in roles, blocks, and plays before executing them with the same user. Finally, we mentioned how to switch users conditionally.