Same steps for multiple named environments with GitLab CI

Viewed 16368

Is there a way to configure multiple specifically-named environments (specifically, test, stage, and prod)?

In their documentation (https://docs.gitlab.com/ce/ci/environments.html) they talk about dynamically-created environments, but they are all commit based.

My build steps are the same for all of them, save for swapping out the slug:

deploy_to_test:
    environment:
         name: test
         url: ${CI_ENVIRONMENT_SLUG}.mydomain.com
    scripts:
         - deploy ${CI_ENVIRONMENT_SLUG}

deploy_to_stage:
    environment:
         name: stage
         url: ${CI_ENVIRONMENT_SLUG}.mydomain.com
    scripts:
         - deploy ${CI_ENVIRONMENT_SLUG}

 deploy_to_prod:
    environment:
         name: prod
         url: ${CI_ENVIRONMENT_SLUG}.mydomain.com
    scripts:
         - deploy ${CI_ENVIRONMENT_SLUG}

Is there any way to compress this down into one set of instructions? Something like:

deploy:
    environment:
         url: ${CI_ENVIRONMENT_SLUG}.mydomain.com
    scripts:
         - deploy ${CI_ENVIRONMENT_SLUG}
4 Answers

Just in case: Gitlab offers (since 11.3) an extends keyword, which can be used to "templates" yaml entries (so far as I understand it):

See the official doc

Have you tried implementing variables for various environments and using different jobs for various environments? I've come up with a solution for you.

image: node:latest
variables:
  GIT_DEPTH: '0' 

stages:
  - build
  - deploy

workflow:
    rules:
      - if: $CI_COMMIT_REF_NAME ==  "develop"
        variables:
          DEVELOP: "true"
          ENVIRONMENT_NAME: Develop
          WEBSITE_URL: DEVELOP_WEBSITE_URL
          S3_BUCKET: (develop-s3-bucket-name)
          AWS_REGION: ************** develop
          AWS_ACCOUNT: ********develop

      - if: $CI_COMMIT_REF_NAME == "main" 
        variables:                                 
          PRODUCTION:  "true"
          ENVIRONMENT_NAME: PRODUCTION
          WEBSITE_URL: $PROD_WEBSITE_URL
          S3_BUCKET: $PROD-S3-BUCKET-NAME
          AWS_REGION: ************** (prod-region)
          AWS_ACCOUNT: ***********(prod-acct)
      - when: always 

build-app:
  stage: build
  script:
     #build-script
  environment: 
    name: $ENVIRONMENT_NAME

deploy-app:
  stage: deploy
  script:
     #deploy-script
  environment: 
    name: $ENVIRONMENT_NAME
Related