GitLab Pipeline: Works in YML, Fails in Extracted

2019-08-22 23:20发布

I followed the GitLab Docs to enable my project's CI to clone other private dependencies. Once it was working, I extracted from .gitlab-ci.yml:

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'

into a separate shell script setup.sh as follows:

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

leaving only:

before_script:
- chmod 700 ./setup.sh
- ./setup.sh

I then began getting:

Cloning into '/root/Repositories/DependentProject'...
Warning: Permanently added 'gitlab.com,52.167.219.168' (ECDSA) to the list of known hosts.
Permission denied (publickey).
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

How do I replicate the original behavior in the extracted script?

1条回答
Evening l夕情丶
2楼-- · 2019-08-23 00:20

When running ssh-add either use source or . so that the script runs within the same shell, in your case it would be:

before_script:
  - chmod 700 ./setup.sh 
  - . ./setup.sh

or

before_script:
  - chmod 700 ./setup.sh 
  - source ./setup.sh

For a better explanation as to why this needs to run in the same shell as the rest take a look at this answer to a related question here.

查看更多
登录 后发表回答