Scenario / Questions

I am trying to run a specific Ansible task as a different user than the one who is running the playbook. My .yml file looks like this:

---

- hosts: staging_servers
  tasks:    
    - name: check user
      remote_user: someusername
      shell: whoami

Running this task shows me that whoami command returns a different user than I defined in the task (precisely, returns the user which is defined in hosts file called ubuntu).

I also tried to define the task like this:

---

- hosts: staging_servers
  tasks:
    - name: check user
      sudo: yes
      sudo_user: someusername
      shell: whoami

but then I get ‘Missing sudo password‘ error, although there is a line in sudoers file which says someusername ALL=(ALL) NOPASSWD:ALL and issuing commands with sudo on remote machine as someusername doesn’t ask me for a password.

So, how can I run the specific task as a different user which is not the user defined in hosts file or root himself?

Find below all possible solutions or suggestions for the above questions..

Suggestion: 1

You’re misunderstanding both settings there:

  • remote_user is an Ansible setting that controls the SSH user Ansible is using to connect: ssh ${REMOTE_USER}@remotehost

  • someusername ALL=(ALL) NOPASSWD:ALL is a sudo configuration that allows the user someusername to execute all commands in any host without a password. It does not allow anyone to issue commands as someusername though.

Ideally, you would login directly as the right user and that’s what remote_user is all about. But usually you are only able to login as an administrative user (say, ubuntu) and have to sudo commands as another user (let’s say scrapy). Then you should leave remote_user to the user that logs in and the add the following ansible properties to the job:

- name: log in as ubuntu and do something as scrapy
  remote_user: ubuntu
  sudo: true
  sudo_user: scrapy
  shell: do-something.sh

Suggestion: 2

Note that after Ansible 1.9, the sudo wording was replaced with become, thus

sudo: yes
sudo_user: some_user

becomes (pun intended):

become: yes
become_user: some_user

See more specifics here: https://stackoverflow.com/a/22749788/402727