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?
A terraform template is a collection of files that, together, define the state of your infrastructure to be achieved. They include different configuration files such as variables, resources, and modules.
User data inserted in the tf file Open the file that contains your terraform resource parameters, in our case it's a main.tf file. Paste the script to the resource specification and use the format shown in the example. << EOF and EOF frame the script within the user_data argument.
rendered - The final rendered template. The value of the policy will be the content of the template after terraform renders it.
User data is commonly used in launch configuration to run scripts during instance initialization. Launch configuration is usually used along with auto scaling groups to launch instances with similar instance settings. Userdata can be templatized in terraform.
Within the block (the { }) is configuration for the data instance. The configuration is dependent on the type; as with resources, each provider on the Terraform Registry has its own documentation for configuring and using the data types it provides.
You can pass terraform variables to EC2 user data. Then you can access to efs_name in ./elk/user_data/init_esearch.tpl like the following What happens if you need to create a script which has some shell variables with cat ? You need to add \$ to the variables in a shell script like below.
3 Define: Terraform - AWS - aws_instance - user_data 25 Terraform variables within variables 1 How to access terraform provider attributes within resources in terraform script?
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With