Search code examples
sshansiblesudoansible-inventoryansible-ad-hoc

Ansible SSH as one user and Sudo as another


I have some difficulties to adapt Ansible configuration to my environment.

My testing environment :

  • PermitRootLogin no
  • Only one user allowed to connect through SSH (foo, without any privileges)
  • A user with sudo privileges (bar ALL=(ALL) ALL)

My ansible host inventory looks like this :

[servers]
server1 ansible_ssh_host=192.168.0.1 ansible_sudo=true ansible_ssh_user=foo ansible_sudo_user=bar

I have an SSH key for foo user.

When I try this ad hoc command (or any other) with bar password :

ansible server1 -m raw -a "echo test > /etc/testfile" --ask-sudo-pass
server1 | FAILED => Incorrect sudo password

Then if I do the same command with foo password :

ansible server1 -m raw -a "echo test > /etc/testfile" --ask-sudo-pass
Sorry, user foo is not allowed to execute '/bin/bash -c echo SUDO-SUCCESS-rlpfhamukjnsfyokqbjpbttviiuildif; echo test > /etc/testfile' as bar on server1.

So Ansible definitely use foo as sudo user and not bar as I specified. Is there a way to force the use of bar instead of foo? I really don't understand the sudo functionality on Ansible, even if I use the same user for everything (bar for SSH and bar password) ansible give returns me :

server1 | FAILED | rc=1 >>
echo test > /etc/testfile : Permission denied

When I'm logging as bar on my host and doing "sudo echo test > /etc/testfile" it ask me for bar password and does the command correctly. Where am I wrong with Ansible behavior ?


Solution

  • Think of it like this:

    • ansible_ssh_user is the user to ssh to the host as
    • ansible_sudo_user is the user to sudo on the host

    In other words, using your users and commands as the example, the equivalent commands that ansible will run are:

    ssh foo@server1 sudo -u bar "echo test > testfile"

    Therefore the foo user's password needs to be provided, not the bar user. The foo user will need privileges to sudo as bar. Something like this in sudoers:

    foo    ALL=(bar) NOPASSWD: ALL
    

    Now foo can run all commands as bar with no password.