Skip to content

Run Ansible tasks as different remote user

Had a somewhat curious situation: need to run a task in Ansible in different user accounts, but I don't have sudo or su access, only ssh access for every account. Took me a moment to figure out how to do that.

 

In Ansible one can use the $remote_user variable which specifies the account used on the remote system. Usually this is used on a Play(book) level:

- hosts: some.host.tld
  gather_facts: True
  become: no
  remote_user: "someremoteuser"

Then the entire Play will use "someremoteuser" as login. So far, so good. But I need to change remote_user for single tasks. That is possible as well:

- name: Try user 1
  command:
    cmd: "id"
  remote_user: "user1"
  register: whoami_1

- name: Debug user 1
  debug:
    msg: "{{ whoami_1 }}"

- name: Try user 2
  command:
    cmd: "id"
  remote_user: "user2"
  register: whoami_2

- name: Debug user 2
  debug:
    msg: "{{ whoami_2 }}"

The task "Try user 1" will login as user "user1", and "Try user 2" will open a new connection and login as "user2".

This can even be used in a loop:

  vars:
    run_users:
      - "user1"
      - "user2"

- name: Try user
  command:
    cmd: "whoami"
  remote_user: "{{ item }}"
  register: whoami
  loop: "{{ run_users }}"

Every "whoami" command will be executed as a different login user.

Excuse me while I rewrite my Playbook.

Trackbacks

No Trackbacks

Comments

Display comments as Linear | Threaded

No comments

Add Comment

Enclosing asterisks marks text as bold (*word*), underscore are made via _word_.
E-Mail addresses will not be displayed and will only be used for E-Mail notifications.
To leave a comment you must approve it via e-mail, which will be sent to your address after submission.
Form options