如何在 gitlab-ci 中使用变量在松弛通道中发送通知

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

我正在向我的 gitlab-ci 进程添加一个新阶段,以便在我开始或结束新的发布部署时发送通知。我首先在 Slack 中创建了一个传入的 webhook,然后更新了 gitlab-ci.yml 文件。

这是子步骤将从中继承的父阶段。

#------------------------------------------
# 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

这是一个子步骤,(发送开始消息)

#------------------------------------------
# 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"

我在专用频道上收到消息,但变量 ${SLACK_MESSAGE} 未被解释。

这是我在 Slack 上得到的惊喜:the_app_name: ${SLACK_MESSAGE}

您必须使用双引号才能解析环境变量:

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