How to dynamically change the environment name in gitlab

Viewed 2046

I need to setup the name of the environment in gitlab-ci.yml with the current date and time.

Is this possible? This is what I tried.

stages:
  - RUN_TESTS
  # - CLEAN
 
run-test:
  stage: RUN_TESTS
  before_script:
    - echo "Running the tests..."
    - aws configure set aws_access_key_id ${SPOT_RUNNER_ACCESS_KEY} 
    - aws configure set aws_secret_access_key ${SPOT_RUNNER_SECRET_KEY}
    - aws configure set default.region ap-southeast-2
    - $(aws ecr get-login --no-include-email --region ap-southeast-2)   
    - export BUCKET_NAME="effi-allure-reports"   
    - export date=$(date)
  script:
    - echo "test"
  only:
    - develop
  tags:
    - itela-spot-runner
  environment: 
    name: $date

But when the pipeline runs, it says

This job is creating a deployment to .

that means that value has not been set. Can someone please help me on this?

3 Answers

You can have a prepare stage before deploy to parse your env variables

prepare_release:
  variables:
    GIT_STRATEGY: none
  stage: prepare   
  rules:
  - if: '($CI_PIPELINE_SOURCE == "merge_request_event") && ($CI_MERGE_REQUEST_TARGET_BRANCH_NAME == "master")'
    when: on_success
  script:
    - echo "DATE=`date -u +%d_%b_%Y`" >> variables.env
  artifacts:
    reports:
      dotenv: variables.env

Through which you can access the date in next job using needs

needs:
  - job: prepare_release
    artifacts: true
script:
  - echo "Running release at $DATE"

If you can't afford an additional job then you've to live with predefined date env variables

If you want to create a dynamic environment name use a Predefined CI variable,

stages: 
  - deploy

deploy:
  stage: deploy
  script:
    - echo "This is a test Deploy"
  environment:
    name: $CI_JOB_STARTED_AT

depending on the datetime you want to register the name of the environment you got three options:

  1. CI_JOB_STARTED_AT. "The UTC datetime when a job started".
  2. CI_PIPELINE_CREATED_AT. "The UTC datetime when the pipeline was created".
  3. CI_COMMIT_TIMESTAMP. "The timestamp of the commit."

worth mentioning they are in ISO8601 format. Complete reference for more details.

Related