Search code examples
bashamazon-web-servicesterraformterraform-provider-awsterraform-template-file

Parse error dealing with Terraform template file and Bash script


I'm not sure where I'm going wrong with this error. I have a Terraform resource that creates a template_file used in a launch configuration. The resource is below:

Template File

data "template_file" "user_data" {
  count    = "${(var.enable ? 1 : 0) * var.number_of_zones}" // 3 templates being created
  template = "${file("userdata.sh")}"

  vars {
    ebs_volume = "${count.index == 0 ? ${var.EBS_VOLUME1} : ${var.EBS_VOLUME2}}"
  }
}

The template_file is being used to launch a script that mounts an EBS to an instance upon startup via autoscaling events. Below is the script:

userdata.sh

#!/bin/bash
# Attach EBS volume
aws ec2 attach-volume --volume-id "${EBS_VOLUME}" --instance_id `curl http://169.254.169.254/latest/meta-data/instance-id` --device /dev/sdf

EBS_VOLUME=${ebs_volume}

Upon executing this code, I am getting the following error and cannot understand why:

Error

Error: Error loading autoscaling-group.tf: Error reading config for template_file[user_data]: parse error at 1:22: expected expression but found invalid sequence "$"

Any advice on how I can resolve this would be helpful.


Solution

  • TF 0.11 is very old, and you should consider upgrading. But anyway, there are few mistakes in your code (wrong interpolation, userdata). The following should work:

    variable "number_of_zones" {
      default = 3
    }
    
    variable "EBS_VOLUME2" {
      default = "2222"
    }
    
    variable "EBS_VOLUME1" {
      default = "1111"
    }
    
    
    variable "enable" {
      default = "true"
    }
    
    data "template_file" "user_data" {
      count    = "${(var.enable ? 1 : 0) * var.number_of_zones}"
      template = "${file("userdata.sh")}"
    
      vars {
        ebs_volume = "${count.index == 0 ? var.EBS_VOLUME1 : var.EBS_VOLUME2}"
      }
    }
    
    output "test" {  
      value    = "${data.template_file.user_data.*.rendered}"
    }