How to send a message to Slack using curl from gitlab-ci.yml?

Viewed 4408

I am using GitLab for a CI/CD process. I want to send messages to my channel in Slack. Following the API works from the terminal:

curl -X POST -H 'Content-type: application/json' --data '{"text":"Hello, World!"}' https://hooks.slack.com/services/xxx/yyyy/zzzz

However, when I put this line into my .yml file, it gives me a "yaml invalid error". Complete block is here:

slack_jar:
  stage: slack
  before_script:
    - echo "hi there"
  script:
    - curl -F file=@target/springApp-0.0.1.jar -F channels=#application_dev_backend -F token='xoxb-1111-2222-yyyyyy' https://slack.com/api/files.upload
  only:
    - dev
    
slack_message:
  stage: slack
  script:
    - echo "Send Slack Messages"
    - curl -X POST -H 'Content-type: application/json' --data '{"text":"Hello, World!"}' https://hooks.slack.com/services/xxxx/yyyy/zzzz
  only:
    - dev

The first stage (sending file) is correct, but the second one is not working. This is the error message I get:

Status: syntax is incorrect Error: jobs:slack_message:script config should be a string or an array of strings

1 Answers

Based on your error message, the curl command in slack_message is incorrect. Try wrapping the entire command in quotes and escaping the internal quotes. The way you have it, the YAML parser thinks the Content-type: application/json is a key:value pair of a dictionary.

Try this instead:

slack_message:
  stage: slack
  script: 
    - echo "Send Slack Messages"
    - "curl -X POST -H 'Content-type: application/json' --data '{\"text\":\"Hello, World!\"}' https://hooks.slack.com/services/xxxx/yyyy/zzzz"
  only:
    - dev

Pro Tip

You can use the CI Lint tool to validate the contents of gitlab-ci.yaml. You can access this in the CI/CD > Pipelines screen. See CI Lint.

There is also a useful website http://www.yamllint.com/ where you can input YAML, and it will (a) validate it, and (b) return a UTF-8 version. If you have string problems, the UTF-8 version will look mangled (which is what happens with your YAML).

Related