Search code examples
curlgitlabgitlab-cislack

How to use variable in gitlab-ci to send notification in a slack channel


I'am adding a new stage to my gitlab-ci process to send a notification when I starting or ending a new realease deployment. I've started by creating an incoming webhook in Slack, then I've updated the gitlab-ci.yml file.

This the parent stage from which the child steps will inherit.

#------------------------------------------
# Slack stage, used by slack-start stage and slack-end stage.
#------------------------------------------
.slack:
  stage: slack
  image:
    name: curlimages/curl
  script:
    - "curl -X POST -H 'Content-type: application/json' --data '{\"text\":\"${SLACK_MESSAGE}\"}' https://hooks.slack.com/services/TH6L32SAC/B2B0LA77/UR63paW7kHNUoTgSL2LRy"
  tags:
    - kubernetes

And here is a child step, (sending a start message)

#------------------------------------------
# Notify on the start of a new test release
#------------------------------------------
slack-start-staging:
  stage: slack-start-staging
  extends:
    - .slack
  variables:
    SLACK_MESSAGE: We are starting the deployment of a new test release on the QA environnement
  rules:
    - if: $CI_COMMIT_BRANCH == "develop" && $CI_PIPELINE_SOURCE == "push"

I receive the message on the dedicated channel, but the variable ${SLACK_MESSAGE} is not interpreted.

Here is what I excatly get on Slack : the_app_name: ${SLACK_MESSAGE}


Solution

  • You have to use double quotes in order to have the environment variable resolved:

    script:
        - 'curl -X POST -H "Content-type: application/json" --data "{\"text\":\"${SLACK_MESSAGE}\"}" https://hooks.slack.com/services/TH6L32SAC/B2B0LA77/UR63paW7kHNUoTgSL2LRy'