Skip to main content

GitLab CI/CD

GitLab CI/CD is a powerful, built-in toolchain for continuous integration, continuous delivery, and continuous deployment. It is entirely controlled via a single YAML file stored in the root of your repository.

Core Concepts

  • .gitlab-ci.yml: The file where you define your pipelines and jobs.
  • Runners: Agents that run your jobs. GitLab provides shared runners, or you can install a GitLab Runner on your own servers (essential for internal infrastructure deployment).
  • Pipelines: The top-level component, consisting of jobs and stages.
  • Stages: Define when to run jobs (e.g., build, then test, then deploy). Jobs in the same stage run in parallel.
  • Jobs: The actual scripts and instructions to execute.
  • Artifacts: Files generated by a job (like compiled binaries or test reports) that can be passed to subsequent jobs or downloaded.

Basic Pipeline Example

This example defines a pipeline with three stages.

stages:
- lint
- test
- deploy

variables:
DEPLOY_DIR: "/opt/myapp"

# Job 1
shellcheck_job:
stage: lint
image: koalaman/shellcheck-alpine
script:
- shellcheck myscript.sh

# Job 2
run_tests:
stage: test
script:
- echo "Running unit tests..."
- ./run_tests.sh

# Job 3
deploy_to_production:
stage: deploy
script:
- echo "Deploying to production server..."
- rsync -avz ./ $DEPLOY_DIR
environment: production
only:
- main # Only run this job when pushing to the main branch

Key Features and Best Practices

  1. Docker Integration: GitLab CI is heavily optimized for Docker. You can easily specify different base images (image: python:3.9) for different jobs, ensuring clean, reproducible environments.
  2. GitLab Runners: For sysadmins, installing your own GitLab Runners on secure network segments allows the CI pipeline to safely SSH into internal servers or deploy to internal Kubernetes clusters without exposing them to the internet.
  3. Environments: Use the environment keyword to track deployments. GitLab provides a dashboard showing exactly which commit is currently deployed to "staging" or "production."
  4. Manual Gates: For critical deployments, you can set a job to require manual intervention (when: manual), requiring a human to click a button in the UI before deploying to production.