Freddy
Freddy

Reputation: 174

How to switch or become another remote user when running one task in ansible-playbook?

I am trying to simply run a command while logged in as a different user in the remote machine than what I initially ssh into using ansible.

on my remote machine I have: -userA -userB

I ssh as userA, run several tasks and want to switch to userB to run a command such as "conda list" to test that enviornment is working for userB.

Effectively what I want to do in ansible is for one task:

  1. ssh into remote machine as userA
  2. perform sudo su
  3. then su userB

I tried to modify my playbook to use become_user and become. Also through extensive google searches and on stack overflow I was shown the become_method:su.

Here is my playbook

  - name: verify conda install by conda list command
    command: ls
    become: yes
    become_user: "{{user}}"
    become_method: su
    become_flags: "su - root -c"
    register: out
    tags: conda_verify

Where {{user}} is defined in defaults as userB

Here is the output of the error:

TASK [anaconda-install : verify conda install by conda list command] 
FAILED! => {"changed": false, "module_stderr": 
"Shared connection to 10.66.144.68 closed.\r\n", "module_stdout": "No passwd entry for user 'su'\r\n", "msg": "MODULE FAILURE\nSee stdout/stderr for the exact error", "rc": 1}

Now if I remove the playbook command

become_flags: "su - root -c"

The playbook then timesout waiting for a password.

FAILED! => {"msg": "Timeout (12s) waiting for privilege escalation prompt: "}

Upvotes: 1

Views: 2949

Answers (1)

saurabh14292
saurabh14292

Reputation: 1401

You can use something like this :

- name: install required packages
  yum:
    name: maven
  become: yes
  become_user: userB

And when executing, make sure you are passing extra variable from command line as below :

ansible-playbook user_switch.yml --extra-vars "ansible_become_password=<Password of userB>"

Also check ansible configuration for "ask_sudo_pass" depending on your system configuration for switching with sudo.

Upvotes: 1

Related Questions