Send Terraform Drift Status To Slack Channel
In this post, we’ll see how we can schedule a shell script to check for Terraform drift and send notifications to a Slack channel.
Step1: Create a test environment following https://github.com/vinycoolguy2015/terraform_ansible/tree/master/ques4
Step2: Go to https://api.slack.com and create an App. Enable Incoming Webhooks for this App. Then click Add New Webhook to Workspace.
Select a channel where you want to publish the message.
Once you are done, you’ll get a sample curl request to post a message to the Slack channel.
Step3: Save the following script as drift. sh.Replace <Slack_Webhook_URL> with the webhook URL we got from Step2.
#!/bin/bash
terraform plan --detailed-exitcode -out=tf.plan 2> /dev/null || ec=$?
case $ec in
0) echo "No Changes Found": exit 0;;
1) printf '%s/n' "Command exited with non-zero";exit 1;;
2) echo "Changes found";
MESSAGE=$(terraform show -no-color tf.plan| awk '/#/,EOF { print $0 }');
curl -X POST -H 'Content-type: application/json' --data "{'text':'$MESSAGE'}" <Slack_Webhook_URL>
esac