GitLab CI / CD deploy script via SSH not working -> UNPROTECTED PRIVATE KEY FILE

Viewed 1488

I've a problem with my GitLab CI / CD pipeline: It's not connecting to my server during the deployment.

I've followed the instructions on the GitLab page and created a key pair for my server locally and tried it out - works perfectly.

Now I've switched to GitLab and created a file variable with the content of my private key file:

enter image description here

After that I've added a deployment section to my .gitlab-ci.yml file:

stages:
    - deploy

deploy:
    stage: deploy
    before_script:
        - mkdir -p ~/.ssh
        - chmod 700 ~/.ssh
        - touch ~/.ssh/known_hosts
        - ssh-keyscan 136.xxx.xxx.xx >> ~/.ssh/known_hosts
        - chmod 644 ~/.ssh/known_hosts
    script:
        - echo "Deploying to server..."
        - ssh -i $IDENTITY ftp@136.xxx.xxx.xx "echo Hallo"
    only:
        - master

But when I execute the script, I'm getting this error:

$ ssh -i $IDENTITY ftp@136.xxx.xxx.xx "echo Hallo"
 @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
 @         WARNING: UNPROTECTED PRIVATE KEY FILE!          @
 @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
 Permissions 0666 for '/builds/john/test-website.tmp/IDENTITY' are too open.
 It is required that your private key files are NOT accessible by others.
 This private key will be ignored.
 Load key "/builds/john/test-website.tmp/IDENTITY": bad permissions
 Permission denied, please try again.
 Permission denied, please try again.
 ftp@136.xxx.xxx.xx: Permission denied (publickey,password).
 ERROR: Job failed: exit code 1

What I'm doing wrong here? I don't get it.

2 Answers

You might want to consider a custom variable of type Variable instead of type file.

That way, GitLab won't create a temporary file with the wrong permission.
But your pipeline can:

  • create the relevant file (with the right permission 600),
  • use it in ssh -i, and
  • delete it immediately.

Thanks to VonC. This is how I solved the problem with his help:

First I've changed the variable from file to variable. After that I've modified my deploy script:

deploy:
    stage: deploy
    before_script:
        - 'which ssh-agent || ( apt-get update -y && apt-get install openssh-client -y )'
        - eval $(ssh-agent -s)
        - echo "$SSH_PRIVATE_KEY" | tr -d '\r' | ssh-add - > /dev/null
        - mkdir -p ~/.ssh
        - chmod 700 ~/.ssh
        - touch ~/.ssh/known_hosts
        - ssh-keyscan 136.xxx.xxx.xx >> ~/.ssh/known_hosts
        - chmod 644 ~/.ssh/known_hosts
    script:
        - echo "Deploying to server..."
        - cd /builds/john/test-website/frontend/
        - ls
        - ssh ftp@136.xxx.xxx.xx "ls"
    only:
        - master
Related