i am trying to figure out how to run an ansible ping command as another user, using their ssh key.

User setup i have essentially:

  • master_user (me)

  • ansible (sudo user, pwdless sign in)

I logged in as ansible user and did:

  • ssh-keygen (generate key)
  • ssh-copy-id XXXX (copy the ssh key to corresponding server)

Tested it all and it works fine (each server has ansible user already fyi). I updated the hosts file to have all my hosts as well.

Now when i remote into master_user, i want to run a ansible command but as ansible user something like this:

ansible all --become-user=ansible -m ping

This fails because it is trying to ssh into the servers using the master_users ssh key.

Error message: Failed to connect to the host via ssh

When i run -vvvv flag i can see it trying to user master_user ssh by looks of it

Offending key for IP in /home/master_user/.ssh/

How can configure it so that it uses ansible user always and use ansible users ssh key?


3 Answers 3


become_user will tell which user to become to run a particular ansible module on the remote server.

If you want to run the ansible command on your control machine as an other user, you need to use sudo or su on this machine e.g.

sudo -s -u ansible ansible all -m ping

The -s option will load the user's shell an make sure homedir and all other envs are correctly set prior to running the command.

An other possible solution would be to use the ssh key you created for the ansible user from your account

ansible all --private-key=/home/ansible/.ssh/id_rsa -m ping

This will potentially work only if your current user has read access to the given key.

  • Option 1 works, option 2 doesn't. However when i do "sudo ansible all --private-key=... -m ping" it works. Almost there
    – Aeseir
    May 26, 2019 at 7:50
  • Option 2 will only work if your user can actually read the key of the other user which is rarely the case out of the box for security reasons. For option 1, I think I know where your problem stands. Edit on the way. May 26, 2019 at 15:19

If you're able to connect to the host

$ ssh ansible@<host>

then try

ansible <hosts> -u ansible -m ping
  • This doesn't work as the ansible attempts to use the master_user's keys, was the first thing i tried.
    – Aeseir
    May 25, 2019 at 9:35

Also, you need to point to the ssh user's certificates created. It should like this:

sudo /usr/local/bin/ansible-playbook \
  example.yml \
  -i example_hosts.ini\

This worked for me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.