How to add ssh private key from Gitlab CI variable with ssh-add?

Viewed 329

According to the docs at https://docs.gitlab.com/ee/ci/ssh_keys/

I can add a private ssh key as CI Variable and add it for my pipeline with

- eval $(ssh-agent -s)
- echo "$SSH_PRIVATE_KEY" | tr -d '\r' | ssh-add -

However, I get an error

Error loading key "(stdin)": incomplete message

I used following command to generate the key pair:

ssh-keygen -t rsa -b 2048

and tried several things to resolve the issue:

a) With and without blank line at the end of the variable
b) Change type of variable to file
c) Change the way the key is generated (different -t and -b options)
d) First write to file and then add from file
e) Change encoding
f) Edit /etc/ssh/ssh_config and add the lines

HostKeyAlgorithms +ssh-rsa
PubkeyAcceptedKeyTypes +ssh-rsa 

=> Could not solve the issue until now.

Related question:

Error loading key "(stdin)": invalid format Gitlab CI

Some alternative commands that did not work:

echo "$SSH_PRIVATE_KEY" | tr -d '\r' | ssh-add - > /dev/null

echo "$SSH_PRIVATE_KEY" | base64 -d | ssh-add -

Another error message that I got while trying:

Error loading key "(stdin)": error in libcrypto

Edit

As a workaround, instead of adding the private key as CI variable, I use a shell executor and manually logged in on the gitlab runner host, changed user to "gitlab-runner" and established an ssh connection. My corresponding CI Job looks like this (you need to replace remote-server.de and user@remote-server.de):

job_back_end_deploy:
  stage: deploy
  #variables:
  #  CI_DEBUG_TRACE: "true"  # uncomment this to get more detailed console output
  before_script:
  # In order for this to work, an SSH connection already needs to be manually prepared
  # between the user "gitlab-runner" on the host of the gitlab-runner and on the target server
  # you would like to connect to
  # Also see https://docs.gitlab.com/ee/ci/ssh_keys/#ssh-keys-when-using-the-shell-executor
  # -------------------------------------
  ## change to user "gitlab-runner"
  # su - gitlab-runner
  ## generate ssh key-pair
  # ssh-keygen -t rsa -b 2048
  ## copy public key to the remote server you would like to connect to (asks for password)
  # ssh-copy-id -p 222 -i /home/gitlab-runner/.ssh/id_rsa.pub user@remote-server.de
  # -----------------------------  
  #
  # verify SSH host keys, also see
  # https://docs.gitlab.com/ee/ci/ssh_keys/#verifying-the-ssh-host-keys
  - ssh-keyscan 'remote-server.de' >> ~/.ssh/known_hosts
  script:    
  - echo 'Copying files to remote server...'
  - scp -P 222 -r ./back_end/ user@remote-server.de:./public_html/back_end/   # add -v option to see more output if you want
  tags:
    - visualization 
1 Answers
Related