Gitlab CI how to deploy an application via SSH
Dealing with ssh on gitlab.com is not straightforward.
That's why i've written a SSH helper for .gitlab-ci.yml.
You can check it out here https://gitlab.com/gitlab-cd/ssh-template
Just include: it to your .gitlab-ci.yml and then you can go with:
ssh_run root myhostname $MYHOST_PKEY "touch foo; cp foo bar; ls -al; rm foo bar; ls -al"
Use mirrors. Under Settings -> Repository -> Mirroring Repositories
.
It generates an ssh pubkey you should place on your server.
You can select direction (pull or push), and which branches get pulled or pushed. Also waits for pipelines.
Works fantastic.
You can store your SSH key as a secret variable within gitlab-ci.yaml
and use it during your build to execute SSH commands, for more details please see our documentation here.
Once you have SSH access you can then use commands such as rsync
and scp
to copy files onto your server. I found an example of this in another post here which you can use as a reference.
Just as an example, lets suppose you have a server with requirements already installed and you want to deploy to that server using ssh.
image: ubuntu:latest
stages:
- deploy
deploy_QA:
stage: deploy
environment:
name: Staging
url: "$QA_URL"
before_script:
- 'which ssh-agent || ( apt-get update -y && apt-get install openssh-client -y )'
- mkdir -p ~/.ssh
- eval $(ssh-agent -s)
- '[[ -f /.dockerenv ]] && echo -e "Host *\n\tStrictHostKeyChecking no\n\n" > ~/.ssh/config'
script:
- ssh-add <(echo "$PRIVATE_KEY")
- ssh -o StrictHostKeyChecking=no user@"$QA_SERVER" 'rm -rf /var/www/html/*'
- scp -P22 -r . ubuntu@"$QA_SERVER":/var/www/html
First, in this example we are using ubuntu image. Also notice that we are using some gitlab secret variables. $QA_URL, $PRIVATE_KEY, $DB_CONNECTION, $QA_SERVER. The important ones are $PRIVATE_KEY and QA_SERVER. Private key is the one you need to authenticate with the QA_SERVER (if you are using private key). And obviously QA_SERVER is the address that you want to deploy your code.
For creating new variable access gitlab->settings->CI/CD.
Within before_script what we are doing is creating and adding ssh key, also we are disabling command line to ask for password. 'StrictHostKeyChecking no'
ssh-add <(echo "$PRIVATE_KEY")
Add ssh key to the agent.
ssh -o StrictHostKeyChecking=no user@"$QA_SERVER" 'rm -rf /var/www/html/*'
Not required: this line uses ssh for deleting any file within /var/www/html scp -P22 -r . ubuntu@"$QA_SERVER":/var/www/html Finally, files are copied from current directory to /var/www/html
Be careful with permissions, it depends of the directory you want to copy.