ansible: run role as a different user

Viewed 456

I have two roles that run in a playbook, one that creates a user and the other which runs through a series of tasks that I want to run as the newly created user on the server.

The playbook is written as follows:

- hosts: centos
  connection: ssh
  gather_facts: false
  become: true

  roles:
  - ../roles/user_setup
  - ../roles/tasks

Let's say the user created from the user_setup role is called user1: I basically want the role named tasks to run as user1. What would be the best way to do this? Thanks.

1 Answers

This question almost provides you a solution. You can use something like:

- hosts: centos
  connection: ssh
  gather_facts: false

  roles:
  - role: ../roles/user_setup
    become: true

  - role: ../roles/tasks
    become: true
    become_user: user1

If you want to connect directly as user1 (rather than escalating to it), you can replace the latest role call with:

  - role: ../roles/tasks
    become: false
    remote_user: user1
Related