Search code examples
ansiblessh-keys

ssh-add permanently using ansible


I'm trying to add a SSH key to SSH agent using ssh-add in ansible tasks.

My ansible task for it looks like this:

- name: add id_rsa in ssh-agent
  shell: eval `ssh-agent -s` && ssh-add -K ~/.ssh/id_rsa_mykey

and it returns the following results:

TASK: [add id_rsa in ssh-agent] *********************************************** 
changed: [testcom.mydomain.com] => {"changed": true, "cmd": "eval `ssh-agent -s` && ssh-add -K ~/.ssh/id_rsa_mykey", "delta": "0:00:00.086725", "end": "2015-08-26 13:35:38.527742", "rc": 0, "start": "2015-08-26 13:35:38.441017", "stderr": "Could not create keychain item\nIdentity added: /var/root/.ssh/id_rsa_mykey (/var/root/.ssh/id_rsa_mykey)", "stdout": "Agent pid 8559", "warnings": []}

I don't know why it couldn't add the key to the keychain but it seems like the key has been added. However when I check with ssh-add -l, it says that the agent has no identities. I couldn't find out where the problem lies.

The key can be added manually in terminal using the same command.


Solution

  • The ssh-agent effect is limited to a single task which invokes it because the connection info to ssh-agent is kept in the environment variables. You might want to see what you eval in the task.

    $ ssh-agent -s
    SSH_AUTH_SOCK=/tmp/ssh-uKzY20owbmmf/agent.8285; export SSH_AUTH_SOCK;
    SSH_AGENT_PID=8286; export SSH_AGENT_PID;
    echo Agent pid 8286;
    

    You cannot use this ssh-agent in later tasks or interactive sessions without settings shown above.

    In any cases I never recommend to run ssh-agent in this way (eval $(ssh-agent)). It's hard to properly finish daemonized ssh-agent on quit, very easy to make ownerless ssh-agent processes in the system. It would be much better to utilize SSH agent forwarding instead.