There is no variable named "REGION"

Viewed 645

The ec2 launch tempate userdata definition using the template provider is about to be replaced with a templatefile function as it is deprecated.

The definition itself can be done without any problems, but an error occurs during the planning process saying that the processing variables for getting instance metadata etc. are undefined, is there any way to avoid this?

  $ terraform version
  Terraform v0.13.5
data "template_file" "userdata" {
  template = templatefile("${path.module}/userdata.sh.tpl",
    vars....
  )
}

resource "aws_launch_template" "sample" {
....
   user_data = base64encode(data.template_file.userdata.rendered)
....
}

The following definitions are applicable processing

export LOCAL_IP=$(ec2metadata --local-ipv4)
export GLOBAL_IP=$(ec2metadata --public-ipv4)
export REGION=$(curl -s http://169.254.169.254/latest/meta-data/placement/availability-zone | sed 's/[a-z]$//')
export AWS_DEFAULT_REGION="$${REGION}"
$ terraform plan
Error: failed to render : <template_file>:13,30-36: Unknown variable; There is no variable named "REGION"., and 4 other diagnostic(s)

thanks

1 Answers

It doesn't make sense to use the template_file data source and the templatefile function together, because these both do the same thing: render a template.

In your current configuration, you have the templatefile function rendering the template to produce a string, and then the template_file function interpreting that result as if it were a template, and so your template is being evaluated twice.

The first evaluation will turn $${REGION} into ${REGION} as expected, and then the second evaluation will try to handle ${REGION} as a template interpolation.

Instead, remove the template_file data source altogether (it's deprecated) and just use the templatefile function:

   user_data = templatefile("${path.module}/userdata.sh.tpl, {
     # ...
   })

(I removed the base64encode function here because user_data expects an unencoded string value where the provider itself will do the base64 encoding. If you call base64encode yourself here then you'll end up with two levels of base64 encoding, which I imagine is not what you intended.)

Related