Auto Deploy a project with leveraging gitlab CI/CD

By yuseferi, 13 January, 2017
Drupal CI/CD with Gitlab

A few days ago Github again, prevents access to my personal private project on Github because I visited GitHub from Iran's IP.

I decided to move my private repositories from Github to Gitlab. after migrating my project I noticed I haven't work with Gitlab for a long time and during this time it has added a lot of tools. like Bitbucket and Github it server very convenient CI/CD development that developers easily deploy their projects to servers without any cover.

In the following, I'm going to. explain how I deployed a Drupal project with Gitlab CI/CD. in summary, this article is about how to create a simple pipeline with Gitlab to deploy a Drupal project to a server via ssh.


Step 1: Check your SSH connection:

in order to deploy the codes and run the drupal command on deployment, you need a ssh key to connect to the server.
if you don't have an ssh key on the server, generate a new one. create a ssh key
after creating a ssh key ( or in case you already have it),  define a variable SSH_PRIVATE_KEY within Settings > CI/CD > Variables with the content of your private key on your project on Gitlab.

Step 2: Set Gitlab CI over SSH:

in this step, the Gitlab CI/CD will be created. create ".gitlab-ci.yaml" file on the root of your project.

Notes:
be sure set  GIT_ROOT to your project path on the server.
- change SSH_USER and SERVER_IP_OR_HOST  on  "ssh -p22 -oStrictHostKeyChecking=no SSH_USER@SERVER_IP_OR_HOST"

 

# Save $SSH_PRIVATE_KEY first in GitLab CI variables.
variables:
  GIT_ROOT: "/opt/bitnami/apps/test_app/web"
  SSH_LOGIN: "ssh -p22 -oStrictHostKeyChecking=no SSH_USER@SERVER_IP"
  DRUSH: "drush"
  COMPOSER: "composer"
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
auto_deploy_to_server_on_master:
  when: always
  only:
    - master
  script:
    - $SSH_LOGIN "cd $GIT_ROOT && git fetch --tags"
    - $SSH_LOGIN "cd $GIT_ROOT && git pull"
    - $SSH_LOGIN "cd $GIT_ROOT && $COMPOSER install"
    - $SSH_LOGIN "cd $GIT_ROOT && $DRUSH updatedb -y"
    - $SSH_LOGIN "cd $GIT_ROOT && $DRUSH config-import -y"
    - $SSH_LOGIN "cd $GIT_ROOT && $DRUSH core-cron"
    - $SSH_LOGIN "cd $GIT_ROOT && $DRUSH cache-rebuild -y"


after that, try to commit something on master branch.
you will see the pipeline on Gitlab CI/CD will be triggered automatically and the result of the job will be email to you.
so in any failure and success job result you will be informed.