AWS UserData Using Terraform

AWS userdata is the set of commands/data you can provide to a instance at launch time. For example if you are launching an ec2 instance and want to have docker installed on the newly launched ec2, than you can provide set of bash commands in the userdata field of aws ec2 config page.

In this blog, we are going to assign user-data to AWS instance with the help of terraform.

lets create a file named script.sh with the below content.

#!/bin/bash
apt-get update
apt-get install nginx -y
echo "Hi Gaurav" >/var/www/html/index.nginx-debian.html

now modify instance.tf file with the below content, so we can use this script as user data.

resource "aws_instance" "web" {
  ami                    = var.image_id
  instance_type          = var.instance_type
  key_name               = aws_key_pair.key-tf.key_name
  vpc_security_group_ids = ["${aws_security_group.allow_tls.id}"]
  tags = {
    Name = "first-tf-instance"
  }
  user_data = file("${path.module}/script.sh")
}

now we can run terraform apply command and verify that the instance created and Nginx is also installed in that instance with the help of userdata.

you can access it on port 80 by default.

Demo Video