2017-10-09 173 views
0

我跟着gitlab的文档SSH keys when using the Docker executor来建立连接到我的远程服务器,它按预期工作。Gitlab CI - 在Bash中设置SSH密钥

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' 

不过,我喜欢把这些命令在一个单独的脚本是这样的:

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 

当试图连接到远程服务器,它给出以下错误:

$ 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). 

该脚本似乎已经正确执行,并且输出的记录与上一个方法相同。有任何想法吗?

+0

我怀疑这是与你在一个子shell运行的事实,第二种方式做内使用#!/bin/bash。脚本退出后,ssh-agent可能也会这样。 – IBam

回答

1

运行ssh-add时使用source或。以便脚本在同一个shell中运行,如果您不在当前shell中的ssh-agent不会有新的密钥。所以在你的情况下,你会做到以下几点。

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

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

从措辞不当类似的问题改编的答案。原来是Here

注:没有必要为bash,因为你已经脚本