Run ssh-add in gitlab-ci.yml

Viewed 361

I have a Gitlab pipeline, in which I want to create a connection to a server with ssh:

stages:
  - connect

connect-ssh:
  stage: connect
  script:
    - mkdir ~/.ssh
    - echo -e "$PROD_SSH_KEY" > file_rsa        # SSH PRIVATE KEY
    - echo -e "$PROD_SSH_PASSPHRASE" > passfile # PASSPHRASE
    - chmod 600 file_rsa
    - cat passfile | ssh-add file_rsa           # DOESN'T WORK
    - ssh -i $PROD_USER@$PROD_HOST
    - pwd

$ cat passfile | ssh-add group-5_rsa
Could not open a connection to your authentication agent.

I have seen few answer, but they weren't appropriate with gitlab jobs. What solution do I have for this situation?

1 Answers

Another approach was illustrated in gitlab-org/gitlab-runner issue 2418

  • putting the commands in a script, including the eval $(ssh-agent -s)
  • sourcing said script

calling a script like you did, opens a sub-shell. The ssh agent environment is therefore not available in the outer shell.
Sourcing the scripts, however, executes it in the current shell. This also means you should be careful with what you do in that scripts. You can overwrite environment variables, exit the main shell, etc.

In your case, just adding eval $(ssh-agent -s) might be enough, since sourcing the script would be the same as running those commands line by line in .gitlab-ci.yml itself.

Related