运行 在 gitlab 中添加 ssh-ci.yml

Run ssh-add in gitlab-ci.yml

我有一个 Gitlab 管道,我想在其中使用 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.

我看到的答案很少,但它们不适合 gitlab 作业。 对于这种情况,我有什么解决方案?

gitlab-org/gitlab-runner issue 2418

中说明了另一种方法
  • 将命令放入脚本中,包括 eval $(ssh-agent -s)
  • sourcing 说脚本

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.

在您的情况下,只需添加 eval $(ssh-agent -s) 可能就足够了,因为采购脚本与 运行 在 .gitlab-ci.yml 本身中逐行执行这些命令是一样的。