Hello!

In this article, I will show how in terraform you can use static files or generate files dynamically. I will show it on the example of user_data in EC2. With the help of user_data, you can transfer a script that will be executed on the server at the time of creation. This file can be predefined with static content and transferred using terraform to user_data, or the content can be dynamically generated and transferred.

Terraform file

I will create a file called setup_httpd.sh, which will contain the following content

#!/bin/bash
yum install httpd -y
/sbin/chkconfig --levels 235 httpd on
service httpd start
echo "<h1>Maksym Website</h1>" > /var/www/html/index.html

This script will install httpd and create an html page. Now how can I use this file? I will take the terraform code from the previous article and add user_data to it.

resource "aws_instance" "foo" {
  ami                    = "ami-0cff7528ff583bf9a"
  instance_type          = "t2.micro"
  subnet_id              = "subnet-222a93327f9a744ed"
  vpc_security_group_ids = ["sg-2220a119757753b6e"]
  user_data              = file("setup_httpd.sh")
  tags = {
    Env = "Dev"
  }
  volume_tags = {
    "Env" = "Dev"
  }
}

And now I will start terraform. Once server is created I can check generated script in the AWS console.

file

And if you open the IP address of the server in the browser, you will see this

file-website

Terraform Template

But this file was static and if it is necessary to change, for example, the content of a web page, the file must be changed. Terraform provided method templatefile() that allows you to generate the content of the file dynamically. To do this, I will create a new file called `setup_httpd.sh.tpl’, the content of file will be almost the same as in the previous one, but with one difference. In the last line, instead of the text Maksym Website, I use ${user} Website. Where ${user} is a parameter that terraform will replace with the appropriate value.

#!/bin/bash
yum install httpd -y
/sbin/chkconfig --levels 235 httpd on
service httpd start
echo "<h1>${user} Website</h1>" >/var/www/html/index.html

You also need to change the terraform code itself. I will replace the file method with templatefile and add the user parameter in addition to the file itself.

resource "aws_instance" "foo" {
  ami                    = "ami-0cff7528ff583bf9a"
  instance_type          = "t2.micro"
  subnet_id              = "subnet-222a93327f9a744ed"
  vpc_security_group_ids = ["sg-2220a119757753b6e"]
  user_data = templatefile("setup_httpd.sh.tpl", {
    user = "Jhon"
  })
  tags = {
    Env = "Dev"
  }
  volume_tags = {
    "Env" = "Dev"
  }
}

Just like the previous time, I will look at the generated script

templatefile

And open the IP address of the server

template-site

Video