How to switch a user per task or set of tasks?


A recurring theme that’s in my ansible playbooks is that I often must execute a command with sudo privileges (sudo: yes) because I’d like to do it for a certain user. Ideally I’d much rather use sudo to switch to that user and execute the commands normally. Because then I won’t have to do my usual post commands clean up such as chowning directories. Here’s a snippet from one of my playbooks:

Ideally I could run commands or sets of commands as a different user even if it requires sudo to su to that user.


With Ansible 1.9 or later

Ansible uses the become, become_user, and become_method directives to achieve privilege escalation. You can apply them to an entire play or playbook, set them in an included playbook, or set them for a particular task.

You can use become_with to specify how the privilege escalation is achieved, the default being sudo.

The directive is in effect for the scope of the block in which it is used

See Hosts and Users for some additional examples and Become (Privilege Escalation) for more detailed documentation.

In addition to the task-scoped become and become_user directives, Ansible 1.9 added some new variables and command line options to set these values for the duration of a play in the absence of explicit directives:

As of Ansible, the older sudo/sudo_user syntax described below still works, but the deprecation notice states, “This feature will be removed in a future release.”

Previous syntax, deprecated as of Ansible 1.9 and scheduled for removal:

Leave a Reply