Programster's Blog

Tutorials focusing on Linux, programming, and open-source

Gitlab Pipeline - Environment Builds

One of the things that keeps coming up is that I need to perform a different set of build and deploy instructions for each of my staging and production builds.
E.g. when I have pushed to the staging branch, I only want the staging-build and staging-deploy tasks to run, and when I push to the production branch, I want the production-build and production-deploy tasks to run instead.

Luckily this is as easy as the working example below where we only have build and deploy stages, but perform different actions for the two different branches.

stages:
    - build
    - deploy


staging-build:
    image: php:7.4-cli-buster
    stage: build
    environment:
        name: staging
    only:
        - staging
    variables:
        DOCKER_HOST: $STAGING_DOCKER_HOST
    script:
        - apt-get update -qq
    when: manual
    allow_failure: false


production-build:
    image: php:7.4-cli-buster
    stage: build
    environment:
        name: production
    only:
        - production
    variables:
        DOCKER_HOST: $PRODUCTION_DOCKER_HOST
    script:
        - apt-get update -qq
    when: manual
    allow_failure: false


staging-deploy:
    image: php:7.4-cli-buster
    stage: deploy
    environment:
        name: staging
    only:
        - staging
    variables:
        DOCKER_HOST: $STAGING_DOCKER_HOST
    script:
        - apt-get update -qq


production-deploy:
    image: php:7.4-cli-buster
    stage: deploy
    environment:
        name: production
    only:
        - production
    variables:
        DOCKER_HOST: $PRODUCTION_DOCKER_HOST
    script:
        - apt-get update -qq

It will still show as "build" and "deploy" in the UI (1), only when you hover over will you see whether it is the staging or production version of the stage (2) as shown in the image below.

Last updated: 5th March 2021
First published: 5th March 2021