Hi @akrypto!
I think your question suggests a small misunderstanding of which components are responsible for evaluating which parts of your configuration here, and in what order.
The most important thing to understand is that the templatefile
call is rendering your template before assigning the result to user_data
, and so the data sent to the remote system is the result of rendering the template, not the template itself.
You seem to be trying to use Terraform’s template language to access data decided only by a shell eventually running the script which was generated by the template. That data isn’t visible to the templatefile
function and all of the template directives will have already been interpreted and thus removed by the time a shell is running these commands.
Because you used the escaping syntax $${
, Terraform understands "$${?}"
as the literal string ${?}
, and so your condition is asking if that string is different from zero, which is always true because a string can never be equal to a number in the Terraform language. Therefore the result always includes that curl
line; the resulting script would always be the following:
inspec exec ./inspec/test
curl -X POST --data-urlencode "payload={\"channel\": \"#somechannel\", \"username\": \"bot\", \"text\": \"hello\", \"icon_emoji\": \":someemoji:\"}" https://slack.webhook
If you want to make a dynamic decision at runtime in your script you will need to write that condition in the language of whichever shell you are using. Assuming this is a Unix-style shell, that might look something like this (but I’m no shell expert, so please refer to the relevant docs for your shell for more detail and other approaches):
inspec exec ./inspec/test
if [ "$?" -ne "0" ]; then
curl -X POST --data-urlencode "payload={\"channel\": \"#somechannel\", \"username\": \"bot\", \"text\": \"hello\", \"icon_emoji\": \":someemoji:\"}" https://slack.webhook
fi
Note that this doesn’t include any Terraform template syntax at all anymore, so there’s no need to use templatefile
; you can instead include this file directly with the file
function and avoid the need to escape any sequences that might normally confuse Terraform’s template file parser.