2017-10-09 195 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,因爲你已經腳本