Terraform | User Data Script, multiple mode

Hello, I can not find any possible combination, where I can use data template_file variables and after init variables.

Basically I’m using Launch Template to manage the user data, but currently I can not use as mentioned above both types of variables, so what I’m looking for is, something like this.

#!/bin/bash

export ID=$(curl -s http://169.254.169.254/latest/meta-data/instance-id)


aws ec2 create-tags --resources ${ID} --tags Key=Name,Value="dev instance: ${region}-${zone}"

So in my bash script, I’m fetching the newly created instance id so I can tag it, however this action is not possible while terraform apply, but variables like region and zone I would like to pass through data template_file like:

data "template_file" "launch_template_userdata" {
  template = file("${path.module}/templates/userdata.sh.tpl")

  vars = {
    zone   = local.zone
    region = local.region
  }
}

How can I combine this actions, or it even possible?

Hi @unity-unity,

I think what you are asking here is how you can use the bash variable ID in your aws ec2 create-tags command line without Terraform thinking it’s intended as a template interpolation sequence.

If so, a relatively straightforward answer is to escape that ${ sequence by doubling the $, like this:

aws ec2 create-tags --resources $${ID} --tags Key=Name,Value="dev instance: ${region}-${zone}"

Terraform’s template language understands $${ as an escape for a literal ${, so the rendered template result should contain just ${ID} for bash to then interpret.

1 Like

Hello, @apparentlymart! I’m so grateful for your answer, this is exactly what I was looking for