1
votes

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: "}
1
Do you specifically have to switch to root before switching to userB? ie. Are there any restriction to directly switch from userA to userB ?saurabh14292
no restrictions to switch to root before userB, that's just the best way to do it interactively and without having to enter the password.Freddy

1 Answers

0
votes

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.