Reputation: 10953
I am trying to use Ansible to create an infrastructure for ssh connections.
- name: Copy ssh key to each server
copy: src=static_folder_key dest=/home/ec2-user/.ssh/ mode=0600
- name: Enable ssh Agent
shell: eval $(ssh-agent -s)
- name: Adding ssh key for static forlder project
shell: ssh-add /home/ec2-user/.ssh/static_folder_key
sudo: True
I create a new ssh key and copy to my servers. Then I execute the agent and later I add the new key to allow the connection. But When I execute the ansible I got this error.
TASK: [git | Adding ssh key for static forlder project] ***********************
failed: [admin_vehicles] => {"changed": true, "cmd": "ssh-add /home/ec2-user/.ssh/static_folder_key", "delta": "0:00:00.004346", "end": "2015-08-12 15:05:00.878208", "rc": 2, "start": "2015-08-12 15:05:00.873862", "warnings": []}
stderr: Could not open a connection to your authentication agent.
failed: [leads_messages] => {"changed": true, "cmd": "ssh-add /home/ec2-user/.ssh/static_folder_key", "delta": "0:00:00.004508", "end": "2015-08-12 15:05:01.286031", "rc": 2, "start": "2015-08-12 15:05:01.281523", "warnings": []}
stderr: Could not open a connection to your authentication agent.
FATAL: all hosts have already failed -- aborting
If I execute this actions manually, everything goes fine.
ssh-add /home/ec2-user/.ssh/static_folder_key
Identity added: /home/ec2-user/.ssh/static_folder_key (/home/ec2-user/.ssh/static_folder_key)
So any tips? Maybe I am missing something in my playbook task?
Upvotes: 9
Views: 11607
Reputation: 128
The solution for this is to invoke eval "$(ssh-agent)"
before the ssh-add
. Initially I tried with two Ansible tasks but it failed the same way since they are atomic and cannot persist the state. The ultimate solution I end up with is to invoke both commands in a single task like this:
- name: Evaluating the authentication agent & adding the key...
shell: |
eval "$(ssh-agent)"
ssh-add ~/.ssh/id_rsa_svn_ssh
Upvotes: 8
Reputation: 1520
The environment for each task is independent, so you cannot leave ssh-agent
settings made in one task to others.
I strongly recommend you to utilize SSH agent forwading. Put the following in ~/.ssh/config
, then run ssh-agent
and ssh-add static_folder_key
locally before running ansible-playbook
. That's all.
Host *
ForwardAgent yes
Even when agent forwarding is not an option, you don't have to run ssh-agent
for a private key file with no passphrase. Copy the following configuration in ~/.ssh/config
on remote hosts and run ssh
to static-folder-host
.
Host static-folder-host
Hostname static-folder-host.static-folder-domain
User static-folder-user
IdentityFile ~/.ssh/static_folder_key
Upvotes: 5