How to send Terraform plan output to a Slack Channel

I am using the below script to run terraform plan within a CircleCI pipeline. The script would send the output to slack channel.

While this worked successfully with $MESS variable, it failed with $MESSAGE variable which is precisely what I need to send to slack. Obviously, the curl command is unable to understand the formatting of the terraform plan output. The error message is invalid payload.

Can somebody please help me how to get over this error?

#!/bin/bash
terraform plan --detailed-exitcode -out=tfplan -target module.strongdm 2> /dev/null || ouput=$?
case $ouput 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 tfplan);
   MESS="This is Not tf output"
   curl -X POST -H 'Content-type: application/json' --data "{'text':'$MESSAGE'}" <WEBHOOK_URL>

esac

Is there anyone who can help with this?

Hi @barywhyte !

My guess is the output will need to be formatted in some capacity to allow the cURL to accept the values. I actually sort of ran into a similar situation when setting up the following guide:

It’s using our CircleCI Slack orb, not a cURL, but you’ll see I needed to massage the output a bit to get it into the right format:

      sed -i 's/\r$//g' slack_response.txt
      SLACK_MESSAGE=$(cat slack_response.txt | tail -n 10 | sed '$!s/$/\\n/' | tr -d '\n')

With the above in mind, you’ll likely need to do something similar to the terraform output before you can pass it along. I think it essentially just needs to be formatted into valid JSON for that cURL to accept it.

I hope the above helps and if I can assist with anything else please let me know!

Regards,
-Nick

Hi @nbialostosky

This is very useful! I am going to start implementing this in a couple of hours. I will provide feedback on progress. Thank you.

Seun

1 Like