Rubans
Rubans

Reputation: 4478

Terraform Template_file and metadata_startup_script variables not working as expected

I have gce resource being created and bootstrapped with a startup script but seeing some weird issues with variables. I have gce resource being created and bootstrapped with a startup script but seeing some weird issues with variables. Created TF resources as per:

data "template_file" "init" {
  template = "${file("../../../Boomi/linux/test.sh")}"
  vars = {
    platform            = var.platform
  }
}

resource "google_compute_instance" "atom_instance" {
  machine_type = var.machine_type
  metadata_startup_script = "${data.template_file.init.rendered}"
...
test.sh script
#!/bin/bash
#set -e
echo "platform:${platform}"
if [ -z $platform ] ; then
  echo "parameter needed!"
if [ -n $platform ] ; then
  echo "parameter provided!"
fi

In the Serial Console output I got the following after the bash script was run:

Jan 15 20:44:25 debian google_metadata_script_runner[471]: startup-script: platform:gcp
Jan 15 20:44:25 debian google_metadata_script_runner[471]: startup-script: parameter needed!
Jan 15 20:44:25 debian google_metadata_script_runner[471]: startup-script: parameter provided!
Jan 15 20:44:25 debian google_metadata_script_runner[471]: startup-script: completed
Jan 15 20:44:25 debian google_metadata_script_runner[471]: startup-script exit status 0

This makes no sense as $platform variable is set so wouldn't expect "parameter needed!" in the output. It seems like the null check is not working? if [ -z $platform ] ; then Any ideas?

Upvotes: 1

Views: 659

Answers (1)

Helder Sepulveda
Helder Sepulveda

Reputation: 17574

There are a couple issues I can spot...

unclosed if statement

Your code

if [ -z $platform ] ; then
  echo "parameter needed!"
if [ -n $platform ] ; then
  echo "parameter provided!"
fi

You can have two if statements like:

if [ -z $platform ] ; then
  echo "parameter needed!"
fi
if [ -n $platform ] ; then
  echo "parameter provided!"
fi

another option is to use the elif to make

if [ -z $platform ] ; then
  echo "parameter needed!"
elif [ -n $platform ] ; then
  echo "parameter provided!"
fi

there is no $platform variable

This is a template file, if you need a variable you need to add that code:
export platform=${platform}

or just replace all the $platform with ${platform} to make the replacement


In general you want to troubleshoot these issues by outputting your code and run the script in isolation, that will save you a lot of time so you don't have to generate resources
Something like:

output "file" {
    value = data.template_file.init.rendered
}

Upvotes: 2

Related Questions