Deploying code from Gitlab repository into remote server

I’m trying to deploy code from a Gitlab repository into remote servers.

Running the pipeline, a Permission denied error shows up

$ ssh $SSH_USER@$SSH_HOST "cd $WORK_DIR && git checkout $PRELIVE_BRANCH && git pull && exit"
Load key "/root/.ssh/id_rsa": error in libcrypto
Permission denied, please try again.
Permission denied, please try again.
deployer@XXX: Permission denied (publickey,password).

For the deployer user I’ve created an SSH key and saved it into repository’s CI/CD variables (as SSH_PRIVATE_KEY).
I’ve also saved the public key into deployer’s .ssh/authorized_keys file.

This is the pipeline I’m running

stages:
  - deploy

deploy:
  image: alpine:latest
  stage: deploy
  only: 
    - prelive
  before_script:
    - apk update
    - apk add openssh-client
    - install -m 600 -D /dev/null ~/.ssh/id_rsa
    - echo "$SSH_PRIVATE_KEY" | base64 -d > ~/.ssh/id_rsa
    - ssh-keyscan -H $SSH_HOST > ~/.ssh/known_hosts
  script:
    - ssh $SSH_USER@$SSH_HOST "cd $WORK_DIR && git checkout $PRELIVE_BRANCH && git pull && exit"
  after_script:
    - rm -rf ~/.ssh

Am I missing something?

Hi there,

Logic looks good to me. Maybe you can check the following:

  • make sure you added public key to the correct user on the server (from your logs, you’re ssh-ing as root, so you need to put the public key in /root/.ssh/authorized_keys, even though I would advise you to rather use non-root user)
  • make sure your private key is in correct format and stored as “variable” (not “file”) in CI/CD variables - those do act a bit different

Good luck! :slight_smile:

Hi @paula.kokic
Thanks for your reply.

  1. ssh command is issuing a Load key "/root/.ssh/id_rsa": error in libcrypto error because the pipeline stores the private key into root account echo "$SSH_PRIVATE_KEY" | base64 -d > ~/.ssh/id_rsa (it’s the account the pipeline is running under).
    However what I’m trying to achieve is to ssh as deployer user (a non-root account in remote server).
    How can I achieve that?

  2. Private key is stored as variable in Gitlab repository settings

Then you have to store the public key on the server into the home of deployer user: /home/deployer/.ssh/authorized_keys (instead of /root/.ssh/authorized_keys) :slight_smile:

I would also double check that the vale of the SSH_PRIVATE_KEY variable is indeed base64 encoded and not a copy-n-paste of the of the private key file’s content.

BTW, personally I don’t really see a point in base64-encoding.