GitLab CI/CD Auto-Pull is a technique that allows your remote server to automatically pull the latest code changes whenever updates are pushed to a GitLab repository. This eliminates the need for manual intervention in deployments, making the process seamless and efficient.

Image description

Why Use Auto-Pull in GitLab CI/CD? 🚀

Manually logging into a server and pulling new code updates can be tedious and error-prone. Automating this process offers several benefits:

  • ✅ Efficiency – No need to manually pull changes after every commit.
  • ✅ Consistency – Ensures that the correct version of the code is deployed.
  • ✅ Reduced Human Error – Eliminates the risk of forgetting to pull updates.
  • ✅ Faster Deployments – Code updates are available on the server as soon as they are pushed.

1. Get SSH Access:

How to get openssh-private-key

Test SSH Access

ssh @

Get openssh-private-key

ssh -o StrictHostKeyChecking=no ssh @ "cat ~/.ssh/id_rsa"

Value should be:

-----BEGIN OPENSSH PRIVATE KEY-----
....
-----END OPENSSH PRIVATE KEY-----

2. Set variables credential:

Go to GitLab ProjectSettingsCI/CDVariables
You can add credential variable there.
For example: openssh-private-key (PROD_SSH_PRIVATE_KEY).

PROD_SSH_PRIVATE_KEY: Should openssh-private-key of which accessable to project directory, should not be root user.

Key: PROD_SSH_PRIVATE_KEY
Value: 
Type: Variable
Environment scope: All (default)
Protect variable: Checked
Mask variable: Checked

Create .gitlab-ci.yml

Go to GitLab ProjectBuildPipeline editor

variables:
  DOCKER_HOST: tcp://docker:2375
  SSH_USER: 
  PRODUCTION_IP: 

services:
  - docker:dind

stages:
  - deploy_production

deploy-prod:
  stage: deploy_production
  image: alpine:latest
  before_script:
    - apk add openssh-client openssh
    - eval $(ssh-agent -s)
    - echo "$PROD_SSH_PRIVATE_KEY" | tr -d '\r' | ssh-add -
    - mkdir -p ~/.ssh
    - chmod 700 ~/.ssh
  script:
    - echo -e "This CI job deploys Stage= [$CI_JOB_STAGE], Branch= [$CI_COMMIT_BRANCH], Server IP= [$PRODUCTION_IP]"
    - ssh -o StrictHostKeyChecking=no ${SSH_USER}@${PRODUCTION_IP} -p 22 "cd  && git pull origin "
    - echo -e "\033[0;32mPulled [$CI_COMMIT_BRANCH] \033[0m"
  rules:
    - if: '$CI_COMMIT_BRANCH == ""'
      when: manual

🌟 Stay tuned 🌟