I want to use the Slack plugin in Jenkins to ping notifications to a Slack channel.
Jenkins says success when I test the connection, but I don\'t receive any notificatio
I didn't use the Slack Notification because I wanna customize style/state/message, etc. So I wrote a job
called send_slack_notification
instead. Every time I want to notify slack API I just call this job after build.
Here's the code in "Execute Shell", I used curl
, sed
and jsawk
to do the job:
# URL to get the built info json
# will get "http://JENKINS_PATH/job/JOB_NAME/97/api/json"
NEW_URL="http://jks_username:jks_password@"$(echo ${BUILD_URL} | sed -r 's/http:\/\///g')"/api/json"
# Cut the JOB_NAME part from BUILD_URL
JOB_NAME=$(echo ${BUILD_URL} | sed -n 's/.*\/job\/\(.*\)\/[0-9].*/\1/p' | sed "s@+@ @g;s@%@\\\\x@g" | xargs -0 printf "%b")
# Get the built info json
JSON=$(curl $NEW_URL)
STATUS=$(echo $JSON | /usr/local/bin/jsawk "return this.result")
BUILD_INFO=$(echo $JSON | /usr/local/bin/jsawk "return this.displayName")
TIME=$(echo $JSON | /usr/local/bin/jsawk "return this.duration")
TIME=$(echo "scale=4; $TIME/1000" | bc -l)
# Cut the username
USER=$(echo $JSON | /usr/local/bin/jsawk "return this" | sed -n "s/.*Started\ by\ \([^\"]*\).*/\1/p")
# Customize the message sending to slack
TEXT=$JOB_NAME" Built by "$USER", it took "$TIME" seconds."
# Send notification using Slack API
# will send to https://hooks.slack.com/services/BLABLABLA/BLABLABLA
curl -X POST -H 'Content-type: application/json' --data '{"channel": "#production_info","username": "jenkins-bot","icon_emoji": ":lol:","text": "'"$TEXT"' (<'"$BUILD_URL"'|Open>)", "attachments": [{"color": "#36a64f", "fields": [{"title":"UPDATE INFO","value":"'"$BUILD_INFO"'","short":true},{"title":"RESULT","value":"'"$STATUS"'","short":true}]}]}' https://hooks.slack.com/services/BLABLABLA/BLABLABLA/BLABLABLABLABLABLA