Search code examples
gitlabcontinuous-integrationgitlab-cigitlab-ci-runner

Gitlab ci/cd how to have the same pipeline with two different stages: dev/prod


I'm using gitlab ci/cd.

Goal

So I have two environments: prop and dev.
When I publish to the develop branch, it should trigger the pipeline and deploy to dev, and when I publish to the main branch do the same thing but to the prod environment.
Their gitlab pipeline should do the same thing, the difference is one is going to be published with the develop stage and the other the main stage. They have different environments variables and that should be taken to account for.

What have I tried ?

So I have an pipeline working and running flawless, but it only works for the dev stage, here it is:

image: node:16.13-stretch

stages:
  - install_dependencies
  - database_migration
  - deploy

variables:
  npm_config_cache: '$CI_PROJECT_DIR/.npm'

.dependencies_cache:
  cache:
    key:
      files:
        - package-lock.json
    paths:
      - .npm
    policy: pull

install_dependencies:
  stage: install_dependencies
  extends: .dependencies_cache
  environment:
    name: dev
  cache:
    policy: pull-push
  artifacts:
    expire_in: 6h
    paths:
      - node_modules
  script:
    - echo "Node:" && node -v
    - echo "NPM:" && npm -v
    - echo "Installing package dependencies"
    - if [ ! -d "node_modules" ]; then npm install; fi
    - echo "Running lint"
    - npm run lint
  only:
    - develop

database_migration:
  stage: database_migration
  environment:
    name: dev
  script:
    - npx prisma migrate deploy
  only:
    - develop

deploy:
  stage: deploy
  environment:
    name: dev
  cache:
    key: $CI_COMMIT_REF_SLUG-$CI_PROJECT_DIR
    paths:
      - node_modules/
    policy: pull
  script:
    - echo "Installing serverless globally"
    - npm i -g serverless@2.64.1
    - echo "Setting up serverless credentials"
    - npx serverless config credentials --provider aws --key $AWS_ACCESS_KEY_ID --secret $AWS_SECRET_ACCESS_KEY
    - echo "Preparing package"
    - npx serverless package --stage dev
    - echo "Deploying application"
    - npx serverless deploy --stage dev
  only:
    - develop


Solution

  • Define two environments: dev and prop.

    1. Go to Deployments
    2. Then Environments and create two new environments for dev and prop.
    3. Redefine each ci envs for two different environments.

    You can also define rules to trigger jobs based on branches. More details