Gitlab CI/Docker: ssh-add keeps asking for passphr

2019-08-21 17:50发布

What I'm currently trying to do, is triggering an script on a remote machine from the Gitlab CI/CD Docker container. The job is configured as follows:

stages:
  - deploy

image: maven:3.3.9

server-deploy:
  stage: deploy
  allow_failure: false
  script:
    ## Install ssh agent
    - apt update && apt install openssh-client -y
    - eval $(ssh-agent -s)
    ## Create SSH key file
    - "echo \"-----BEGIN OPENSSH PRIVATE KEY-----
b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW
QyNTUxOQAAACByjJBGT21Arna/pirWVXQqGAr/aszqQ5HzvrA2MzVDZAAAAJiGKEEKhihB
CgAAAAtzc2gtZWQyNTUxOQAAACByjJBGT21Arna/pirWVXQqGAr/aszqQ5HzvrA2MzVDZA
AAAEAKbObQgJGXbrKQt4wdCy3YQfpVBqkT5RNEt2IYU5pv3HKMkEZPbUCudr+mKtZVdCoY
Cv9qzOpDkfO+sDYzNUNkAAAAFHN2ZW5AREVTS1RPUC0xTjVKUjRSAQ==
-----END OPENSSH PRIVATE KEY-----\" > deploy-key"
    ## Fix permissions on key file and .ssh folder
    - chmod 700 deploy-key; mkdir -p ~/.ssh; chmod 700 ~/.ssh
    ## Import SSH key
    - ssh-add -k deploy-key
    ## Make sure that ssh will trust the new host, instead of asking
    - echo -e "Host *\n\tStrictHostKeyChecking no\n\n" > ~/.ssh/config
    ## Run script on the remote server
    - ssh -t user@255.255.255.255 "./deploy-master"

(The SSH key is just a temporary one, specifically generated for the SO question) Now the job fails when it arrives at the "ssh-add -k deploy-key" command, asking for a passphrase, as such:

$ ssh-add -k deploy-key
Enter passphrase for deploy-key: ERROR: Job failed: exit code 1

The SSH key obviously has no passphrase attached to it, I can verify this by running the exact same commands on my own Linux machine, where they just work as they should.

So my question is: how can I prevent ssh-add from asking for a passphrase? And I'm also quite curious why this is only occurring on the Gitlab CI Docker container and not on my own PC.

Thanks in advance!

1条回答
仙女界的扛把子
2楼-- · 2019-08-21 18:37

Okay, I got it working. It turns out that ssh-add is very picky about the format of the file and especially the newlines. The newlines in the .gitlab-ci.yml are not transferred directly to the command and so the key ended up being one big line.

Here is how I solved it:

- echo -----BEGIN OPENSSH PRIVATE KEY----- >> deploy-key
- echo b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW >> deploy-key
- echo QyNTUxOQAAACByjJBGT21Arna/pirWVXQqGAr/aszqQ5HzvrA2MzVDZAAAAJiGKEEKhihB >> deploy-key
- echo CgAAAAtzc2gtZWQyNTUxOQAAACByjJBGT21Arna/pirWVXQqGAr/aszqQ5HzvrA2MzVDZA >> deploy-key
- echo AAAEAKbObQgJGXbrKQt4wdCy3YQfpVBqkT5RNEt2IYU5pv3HKMkEZPbUCudr+mKtZVdCoY >> deploy-key
- echo Cv9qzOpDkfO+sDYzNUNkAAAAFHN2ZW5AREVTS1RPUC0xTjVKUjRSAQ== >> deploy-key
- echo -----END OPENSSH PRIVATE KEY----- >> deploy-key

This way the newlines in the file automatically get created, and now ssh-add pick up the format.

查看更多
登录 后发表回答