How to Add an SSH key with a passphrase as part of an ansible playbook

153 Views Asked by At

I am putting together a server using ansible. As part of that I need to clone some private repo's from GitHub to the server. My access to GitHub is via an ssh key that is passphrase protected. I have tried to do the following:

  1. Copy the ssh key to the server. - works ok

    - name: Copy the github keys to the server
      copy:
        src: "{{ ssh_key_path }}"
        dest: "{{ ssh_key_path }}"  # Destination path on the remote server
        mode: 0600  # Set appropriate permissions on the key file
  1. Attempt to add the ssh-key to the ssh-agent - fails (see below)
    - name: Add SSH Key to SSH Agent
      shell: |
        eval "$(ssh-agent -s)"
        ssh-add "{{ ssh_key_path }}"
  1. Attempt to use the key to access the GitHub repo
    - name: Clone the repository
      git:
        repo: [email protected]:xxx-YYYY/test.git
        dest: /var/www/test  
        update: yes
        accept_hostkey: yes
        clone: yes
        key_file: "{{ ssh_key_path }}"

When I try and do step 2 it fails with

TASK [Add SSH Key to SSH Agent] **********************************************************************************************************************************
fatal: [server]: FAILED! => {"changed": true, "cmd": "eval \"$(ssh-agent -s)\"\nssh-add \"~/.ssh/id_github\"\n", "delta": "0:00:00.013892", "end": "2023-09-06 09:51:48.993168", "msg": "non-zero return code", "rc": 1, "start": "2023-09-06 09:51:48.979276", "stderr": "~/.ssh/id_github: No such file or directory", "stderr_lines": ["~/.ssh/id_github: No such file or directory"], "stdout": "Agent pid 49956", "stdout_lines": ["Agent pid 49956"]}

My concern is that I might be able to go to the command line in the terminal and solve this but how will it withstand re-creation of the server. Any help gratefully received.

0

There are 0 best solutions below