Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

execute ssh-add with ansible raise an error

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?

like image 784
Robert Avatar asked Aug 12 '15 15:08

Robert


1 Answers

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
like image 134
Angelo A Avatar answered Sep 21 '22 10:09

Angelo A