Accessing Terraform variables within user_data provider template file

Timothy T. picture Timothy T. · Jun 13, 2018 · Viewed 9k times · Source

I am launching a aws_launch_configuration instance using terraform.

I'm using a shell script for the user_data variable, like so:

resource "aws_launch_configuration" "launch_config" {
    ...
     user_data                     = "${file("router-init.sh")}"
    ....  
}

Within this router-init.sh, one of the things I would like to do, is to have access to the ip addresses for other instances I am launching via terraform.

I know that I can use a splat to access all the ip addresses of that instance, for instance:

output ip_address {
    value = ${aws_instance.myAWSInstance.*.private_ip}"
}

Is there a way to pass / access these ip addresses within the router-init.sh script?

Answer

Brandon Miller picture Brandon Miller · Jun 13, 2018

You can do this using a template_file data source:

data "template_file" "init" {
  template = "${file("router-init.sh.tpl")}"

  vars = {
    some_address = "${aws_instance.some.private_ip}"
  }
}

Then reference it inside the template like:

#!/bin/bash

echo "SOME_ADDRESS = ${some_address}" > /tmp/

Then use that for the user_data:

 user_data = ${data.template_file.init.rendered}