templatefile

Stores small snippets of code or other types of data that can be easily referenced in the future

templatefile

Used to generate a formatted string by processing a template file with variables. The terraform.user_data attribute is used to specify user data that is passed to an EC2 instance when it is launched.

The syntax for using templatefile() function to set the terraform.user_data attribute is as follows:

terraform {
  required_providers {
    aws = {
      source = "hashicorp/aws"
      version = "3.50.0"
    }
  }
}

provider "aws" {
  region = "us-west-2"
}

resource "aws_instance" "example" {
  ami           = "ami-0c55b159cbfafe1f0"
  instance_type = "t2.micro"
  
  user_data = templatefile("user-data.sh")
}

In this example, the templatefile() function is used to read the contents of the user-data.sh file, process any variables in the file, and return the resulting string. The terraform.user_data attribute is then set to the resulting string, which will be passed to the EC2 instance when it is launched.

The user-data.sh file could contain a shell script or cloud-init script that will be executed on the EC2 instance during its first boot. Any variables that need to be passed to the script can be defined using Terraform variables and passed to the script using the templatefile() function.

Create a script file called user-data.sh and put it in the Terraform working directory.

#!/bin/bash
cat > index.html <<EOF
<h1>Hello World</h1>
EOF

nohup busybox httpd -f -p 8080 &
Last modified July 21, 2024: update (e2ae86c)