Bash – ansible-playbook doesn’t work inside a bash script

ansibleansible-playbookbashshell

I am not sure what is going on and hence I enquiring here as well in hopes that some of you might.

I am trying to figure out why the same one-liner will successfully connect on my remote server

ansible-playbook initial.yml -u root -e 'host_key_checking=False' 

but if I run this same one-liner from inside a shell script, then I will get:

fatal: [*********]: UNREACHABLE! => {"changed": false, "msg": "Failed to connect to the host via ssh: root@*************: Permission denied (publickey).\r\n", "unreachable": true}

I have tried with sudo and without.
The shell script is inside the same directory.

Any thoughts?

Best Answer

When you run ansible-playbook while logged in, then ansible can use the connection to your ssh key agent to enable using ssh keys to login without entering a password or passphrase.

You don't specify how you are running the script containing the command, but more often than not the point of putting it in a script is so that it can be called easily from cron. However the runtime environment from cron has no connection to an ssh key agent, and hence the login to the remote host fails.

One workaround for this is to use an authorization key without a passphrase, but you have to realize the security implications! Anyone that gets their fingers on that private key can login anywhere the public key is installed. One way to mitigate this is to use a forced command with the public key, but that's a different topic.