Automating with GitHub Actions & GitLab CI
Hosting platforms don't just store code, they can run it. Every push or pull request can automatically trigger tests, builds and deployments. Nana's two videos build the same kind of pipeline on GitHub Actions and on GitLab CI/CD; the ideas are identical, only the file names and keywords differ.
GitHub Actions: the pieces
needs another.- An event starts everything: a push, a pull request, a new tag, a schedule, or a manual button.
- A workflow is a YAML file in
.github/workflows/describing what should happen for which events. - A workflow has one or more jobs. Jobs run in parallel unless one
needsanother. - Each job is a list of steps: either a shell command (
run:) or a ready-made action from the marketplace (uses:), like checking out the code or logging in to Docker Hub. - Jobs run on a runner: a fresh virtual machine GitHub starts for you (
ubuntu-latest), or your own self-hosted server. - Secrets (passwords, tokens) are stored in the repo's settings and injected as
${{ secrets.NAME }}, never written in the file.
# .github/workflows/ci.yml
name: CI
on:
push:
branches: [main]
pull_request:
jobs:
test-and-build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4 # get the code
- uses: actions/setup-python@v5
with:
python-version: "3.12"
- run: pip install -r requirements.txt
- run: pytest # a failing test stops the job here
- uses: docker/login-action@v3
with:
username: ${{ secrets.DOCKERHUB_USER }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- run: |
docker build -t demee/app:${{ github.sha }} .
docker push demee/app:${{ github.sha }}
GitLab CI/CD: the same ideas
GitLab keeps the pipeline in one file at the top of the repo, .gitlab-ci.yml. Jobs are grouped into stages that run in order (all test jobs, then all build jobs, then deploy); a failure in one stage stops the later ones. Jobs are picked up by GitLab Runners, which use an executor (shell, Docker…) to run them. CI/CD variables in the project settings hold secrets, either as plain values or as files (handy for SSH keys).
# .gitlab-ci.yml
stages: [test, build, deploy]
run_tests:
stage: test
image: python:3.12
script:
- pip install -r requirements.txt
- pytest
build_image:
stage: build
image: docker:24
services: [docker:24-dind] # "Docker in Docker" so the job can build images
script:
- docker login -u $REGISTRY_USER -p $REGISTRY_PASS
- docker build -t demee/app:$CI_COMMIT_SHORT_SHA .
- docker push demee/app:$CI_COMMIT_SHORT_SHA
deploy:
stage: deploy
script:
- ssh -o StrictHostKeyChecking=no deploy@$SERVER_IP "docker pull demee/app:$CI_COMMIT_SHORT_SHA && docker compose up -d"
only: [main]
Both pipelines follow the same shape: test the code, build it into a Docker image tagged with the commit ID, push the image to a registry, and deploy it to a server. The next topic, DevOps, explains why pipelines are organised that way.