Skip to content

Instantly share code, notes, and snippets.

@johnroyer
Last active July 12, 2019 06:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johnroyer/67dff49c4d584096c0406c172e34fd67 to your computer and use it in GitHub Desktop.
Save johnroyer/67dff49c4d584096c0406c172e34fd67 to your computer and use it in GitHub Desktop.
slack notifier for AWS EC2 deployment
#!/usr/bin/env bash
ID=`curl http://169.254.169.254/latest/meta-data/instance-id`
EC2_NAME=`aws ec2 describe-instances --instance-ids $ID | jq .Reservations[0].Instances[0].Tags[].Value | paste -sd ' ' - | sed -e 's/\"/ /g'`
HASH=`git rev-parse HEAD`
SHORT_HASH=`echo $HASH | head -c 6`
COMMENT=`git log --format=%B -n 1 HEAD`
BB_URL_PREFIX="https://bitbucket.org/team/project/commits"
HOST=`hostname`
REPO=$(basename `git rev-parse --show-toplevel`)
STR=`echo "commit $SHORT_HASH has been depoyed to $HOST"`
INFO=`echo "$SHORT_HASH : $COMMENT"`
URL=`echo "detail: $BB_URL_PREFIX"`
read -d '' JSON << EOD
{
"attachments": [
{
"color": "good",
"title_link": "$BB_URL_PREFIX/$HASH",
"title": "$SHORT_HASH has beeen deploy to $EC2_NAME",
"text": "commit message: \`$COMMENT\`
detail: $BB_URL_PREFIX/$HASH"
}
]
}
EOD
curl -X POST -H 'Content-type: application/json' --data "$JSON" \
https://hooks.slack.com/services/xxxx/xxxxx/xxxxxxxxxx
@yen3
Copy link

yen3 commented Jul 12, 2019

https://gist.github.com/johnroyer/67dff49c4d584096c0406c172e34fd67#file-notify-sh-L22

How about
"text": "$SHORT_HASH has been deploy to $EC2_NAME"

or

"text": "$(echo $SHORT_HASH) has been deploy to $(echo $EC2_NAME)"

@johnroyer
Copy link
Author

Seems better.
Thanks !!!

@johnroyer
Copy link
Author

script updated. Thanks to @yen3

@edentsai
Copy link

@edentsai
Copy link

edentsai commented Jul 12, 2019

jq 有幾個 options 可以幫忙處理 JSON escape 的問題

  • --arg
  • --argjson
  • --argfile
  • --slurpfile

https://stedolan.github.io/jq/manual/#Invokingjq

For example:

$ jq --null-input \
    --arg title 'deploy to "master"' \
    '{"title": "\($title)"}'

{
  "title": "deploy to \"master\""
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment