I spent some minutes trying to understand what was happening when trying to run `ansible ping` on a machine I could manually ssh into, but ansible could not connect to it. Here is what I did to fix that.

2023 January 28

The remote machine had an “ubuntu” user on IP, and I had configured the ansible hosts file this way:



# remember to edit your /etc/hosts if you are using multipass to trigger the VMs. E.g.:
# [the-ip-you-are-adding-here] www.example.com example.com nginx.example.com traefik.example.com tomcat.example.com mysql.example.com

# example 1 - normal user with sudo ansible_become=true ansible_become_method=sudo ansible_ssh_user=ubuntu ansible_ssh_private_key_file=~/.ssh/id_ed25519

# example 2 - root user (avoid at all costs)
# ansible_user=root


I was able to successfully connect to the machine with ssh, but ansible kept complaining about the sudo password:

$ ansible -vvvv -i ~/ansible/conf/hosts all -m ping | FAILED! => {
    "msg": "Missing sudo password"

I scratched my head because the ssh key was correctly configured on the ansible hosts file above, I could ssh into the machine with the key, so what could be happening?

That was when I realized a simple thing: ansible was able to connect.

The problem was that the ubuntu user on the remote machine, when I ran commands with sudo, was asking for the password!

Then, the fix was simple on the remote machine (ubuntu in this case): I ran some commands to allow the users on the sudo group (which was the case of the ubuntu user) to do sudo passwordless - that was safe in my case because the machine only allowed login as the ubuntu user, with ssh keys, and had fail2ban installed to stop attempts from others to login.

Here are the commands I ran on the remote Ubuntu machine:

# become root:
$ sudo su

# to edit the sudo configuration (this will open vi)
$ visudo

Inside this file, I changed the following configuration:

# Allow members of group sudo to execute any command
# %sudo         ALL=(ALL:ALL) ALL

After that, I logged off from the machine, logged in again, and ran sudo su again.

I was then able to run this sudo command without a password.

So, now ansible should be able to do the same:

$ ansible -vvvv -i ~/ansible/conf/hosts all -m ping | SUCCESS => {
    "changed": false,
    "ping": "pong"

And it did! So, problem solved! \o/