Pass variable within json payload in shell script

7,924

Solution 1

With jq:

$ payload='{"channel": "#alerts", "username": "k8s-cronjobs-bot", "text": "", "icon_emoji": ":ghost:"}'
$ MY_ENV_VAR='"foo"'
$ echo "$payload" | jq --arg cmd "$MY_ENV_VAR" '.text = "Command " + $cmd + " run with success"'
{
  "channel": "#alerts",
  "username": "k8s-cronjobs-bot",
  "text": "Command \"foo\" run with success",
  "icon_emoji": ":ghost:"
}

So your script would look like:

#!/bin/bash

COMMAND=${MY_ENV_VAR}    
payload='{"channel": "#alerts", "username": "k8s-cronjobs-bot", "text": "", "icon_emoji": ":ghost:"}'
payload=$(echo "$payload" | jq -r --arg cmd "$COMMAND" '.text = "Command " + $cmd + " run with success"')
curl -X POST --data-urlencode "payload=$payload"  "${SLACK_WEBHOOK}"

Solution 2

Or, use printf to help with the mix of quotes:

printf -v payload '{"channel": "#alerts", "username": "k8s-cronjobs-bot", "text": "Command %s run with success", "icon_emoji": ":ghost:"}' "$MY_ENV_VAR"
curl -X POST --data-urlencode "payload=$payload" "$SLACK_WEBHOOK"
Share:
7,924

Related videos on Youtube

pkaramol
Author by

pkaramol

Updated on September 18, 2022

Comments

  • pkaramol
    pkaramol over 1 year

    In the following scenario, which is the way to pass ${MY_ENV_VAR} in the payload?

    I will have to escape:

    a) the single quotes of the payload

    b) the double quotes of the value of the text json field

    I need ${MY_ENV_VAR) to be interpolated of course.

    #!/bin/bash
    
    COMMAND=${MY_ENV_VAR}    
    
    curl -X POST --data-urlencode 'payload={"channel": "#alerts", "username": "k8s-cronjobs-bot", "text": "Command ${MY_ENV_VAR} run with success", "icon_emoji": ":ghost:"}' ${SLACK_WEBHOOK}
    
    • pkaramol
      pkaramol almost 5 years
      You are right, I fixed this
    • muru
      muru almost 5 years
      Can you use the jq command?
    • pkaramol
      pkaramol almost 5 years
      Any suggestions how to go about it? You can post it as answer so that I also accept it