1

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?

1
  • I suspect it's to do with the fact you're running in a subshell the second way. After the script exits, ssh-agent probably does too. Commented Oct 9, 2017 at 4:56

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.