Chris McKee
Chris McKee

Reputation: 4387

How can I read in a service status and pass it on to Slack via JSON in bash

I have this script currently...

#!/bin/bash
# Check NGINX
nginxstat=$(service nginx status)

# Checking Sites
hostsite="localhost:81 - "$(curl --silent --head --location --output /dev/null --write-out '%{http_code}'  http://localhost:81 | grep '^2')

##########
# Send to Slack
curl -X POST --data '{"channel":"#achannel","username":"Ansible", "attachments": [{"fallback":"NGINX Reload","pretext":"'"$HOSTNAME"'","color":"good","fields":[{"title":"nginx localhost","value":"'"$hostsite"'","short":true},{"title":"NGINX","value":"'"$nginxstat"'","short":true}]}]}' -i https://xxx.slack.com/services/hooks/incoming-webhook?token=xxx

I've tried and tried and failed; I want to grab the result of a nginx configtest and push it in. At the moment an nginx reload kicks in prior to this being ran, the reload does a configcheck itself so the server stays up if the config is wrong. So my nginx status command (which works) displays

NGINX
----------------
nginx (pid  1234) is running...

but I can't get the same to work with config test, which i expect is due to the nature of the escaping required and the other junk it pumps out ala

nginx: [warn] "ssl_stapling" ignored, issuer certificate not found
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

Upvotes: 2

Views: 1367

Answers (1)

zerodiff
zerodiff

Reputation: 1700

Transform your variable into a JSON string with jq before you embed it in the POST data:

$ echo '"some quoted stuff"' | jq @json
"\"some quoted stuff\""

For example:

nginxstat=$(service nginx status | jq @json)

Then embed unquoted. See also the manual.

Or, if you want it JSON escaped then bash escaped:

echo '"some quoted stuff"' | jq "@json | @sh"
"'\"some quoted stuff\"'"

Did I mention that jq is my new favorite thing?

http://stedolan.github.io/jq/

Upvotes: 3

Related Questions