0

I am using a Groovy script to send a POST using the Slack API, at present I am getting invalid_payload returned and I think this is most likely due to the formatting of my JSON. I know the Slack API expects it JSON with double quotes but I can't seem to be able to pass a variable into the JSON object:

SUCCESS_MESSAGE = '{"attachments": [{"color": "#2A9B3A", "author_name": ${DEV_NAME}, "title": "Build Status", "title_link": ${BUILD_URL}, "text": "Successful Build" }]}'
def response = ["curl", "-X", "POST", "-H", "Content-Type: application/json", "-d", "${SUCCESS_MESSAGE}", "https://hooks.slack.com/services/${SLACK_WEBHOOK}"].execute().text

How should I correctly format my SUCCESS_MESSAGE var so I don't get the error?

halfer
  • 19,824
  • 17
  • 99
  • 186
Richlewis
  • 15,070
  • 37
  • 122
  • 283

1 Answers1

2
  1. You need to quote your DEV_NAME and BUILD_URL variable expansions so the JSON string is valid.
  2. Your whole string needs to be enclosed in " instead of ' so the variables are actually expanded
  3. And you need to escape the " inside your string so they appear in your JSON string.

    SUCCESS_MESSAGE = "{\"attachments\": [{\"color\": \"#2A9B3A\", \"author_name\": \"${DEV_NAME}\", \"title\": \"Build Status\", \"title_link\": \"${BUILD_URL}\", \"text\": \"Successful Build\" }]}"`

Alternatively you can generate the JSON in much nicer programmatic way. Which would be helpful if your notifications got a bit more complicated:

def notification = [
  attachments: [
    [
      color: "#2A9B3A",
      author_name: DEV_NAME,
      title: "Build Status",
      title_link: BUILD_URL,
      text: "Successful Build"
    ]
  ]
]

def response = ["curl", "-X", "POST", "-H", "Content-Type: application/json", "-d", JsonOutput.toJson(notification), "https://hooks.slack.com/services/${SLACK_WEBHOOK}"].execute().text
Strelok
  • 50,229
  • 9
  • 102
  • 115
  • I have tried that, and all that gets passed through is "${DEV_NAME}" for example and not the actual value – Richlewis Apr 03 '17 at 08:20
  • ah brilliant, that works and thanks for the explanation :-) – Richlewis Apr 03 '17 at 08:35
  • 1
    @Richlewis I've also added another way for you to build JSON that can be useful if the notifications get larger and more complicated. You can easily generate them programmatically in Groovy. – Strelok Apr 03 '17 at 08:42