run ansible command as another user using their ssh key 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?
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.