Mr. 14
Mr. 14

Reputation: 9528

Gitlab CI - Setup SSH Key In Bash

I followed gitlab's documentation on SSH keys when using the Docker executor to setup connection to my remote server, which works as expected.

before_script:
  - which ssh-agent || ( apt-get update -y && apt-get install openssh-client -y )
  - eval $(ssh-agent -s)
  - ssh-add <(echo "$SSH_PRIVATE_KEY")
  - mkdir -p ~/.ssh
  - '[[ -f /.dockerenv ]] && echo -e "Host *\n\tStrictHostKeyChecking no\n\n" > ~/.ssh/config'

However, I'd like to put those commands in a separate script like this:

before_script:
  - bash ./scripts/ssh-config.sh

ssh-config.sh

#!/bin/bash
which ssh-agent || ( apt-get update -y && apt-get install openssh-client -y )
eval $(ssh-agent -s)
ssh-add <(echo $SSH_PRIVATE_KEY)
mkdir -p ~/.ssh
[[ -f /.dockerenv ]] && echo -e "Host *\n\tStrictHostKeyChecking no\n\n" > ~/.ssh/config

When trying to connect to the remote server, it gives the following error:

$ bash scripts/ssh-config.sh
/usr/bin/ssh-agent
Agent pid 15
Identity added: /dev/fd/63 (/dev/fd/63)
$ ssh [email protected] "touch test"
Warning: Permanently added 'example.com' (ECDSA) to the list of known hosts.    
Permission denied, please try again.
Permission denied, please try again.
Permission denied (publickey,password).

The script seemed to have been executed correctly and have output the same logs as that by the previous method. Any ideas?

Upvotes: 1

Views: 954

Answers (1)

Clive Makamara
Clive Makamara

Reputation: 3035

When running ssh-add either use source or . so that the script runs within the same shell, if you don't the ssh-agent in your current shell will not have the new key. So in your case you would do the following.

before_script:
  - . ./scripts/ssh-config.sh

or

before_script:
  - source ./scripts/ssh-config.sh

Adapted answer from a similar question that was poorly worded. Here is the original.

NOTE: There's no need for bash because you are already using #!/bin/bash within your script

Upvotes: 2

Related Questions