Automating Infrastructure on AWS Using Terraform

Reading Time: 2 minutes

In this blog, I am going to showcase how to create an infrastructure on AWS using Terraform.  Let’s have a brief introduction of Terraform before jumping to the particular use-case.

What is Terraform?

Terraform is an infrastructure provisioning tool created by HashicorpIt allows you to describe your infrastructure as code, creates execution plans that outline exactly what will happen when you run your code, builds a graph of your resources, and automates changes with minimal human interaction.

In order to create infrastructure, we have to run following commands in the given sequence.

  1. terraform init: This command is used to initialize the working directory containing terraform script. The desired specification of an infrastructure is configured here.
  2. terraform plan: This command creates an execution plan.  It confirms that the set of changes matches your expectations without making any changes to real resources or to the state
  3. terraform apply:  This command creates a real infrastructure.
  4. terraform destroy: This command is used to destroy infrastructure.

How Syntax looks like?

What is the use-case which needs to be solved?

“Launch an AWS EC-2 instance and host a web page on the Nginx server.” : This is main terraform script.

provider "aws" {
access_key = "${var.access_key}"
secret_key = "${var.secret_key}"
region = "us-west-2"
resource "aws_instance" "awsInstance" {
ami = "ami-c0f936b8"
instance_type = "t2.micro"
key_name = "${var.key_name}"
connection {
user = "ec2-user"
private_key = "${file(var.private_key_path)}"
provisioner "remote-exec" {
inline = [
"sudo yum install nginx -y",
"sudo service nginx start",
"echo '<html><head><title>Learning terraform</title></head><body><h1>Automating Infrastructure on AWS Using Terraform</h1></body></html>' | sudo tee /usr/share/nginx/html/index.html"
view raw hosted with ❤ by GitHub : This file contains all the environment variables used by our main script.

variable "access_key" {}
variable "secret_key" {}
variable "private_key_path" {}
variable "key_name" {
default = "dummy"
view raw hosted with ❤ by GitHub

terraform.tfvars : In this file we add values of the variables which will be used by Before running a script.

# Fill all the varibles before executing the deployment.
access_key = "<< Access Key >>"
secret_key = "<<Secret Key>>"
private_key_path = "<<Private Key Path>>"

Run terraform init, terraform plan and terraform apply to deploy on AWS. : This is our output file through which we get various resource information.

output "instance_id" {
value = "${}"
output "public_dns" {
value = "${aws_instance.awsInstance.public_dns}"
view raw hosted with ❤ by GitHub

When apply finishes, the public dns output variable will show the public dns of an instance.

Open this public dns in your web browser. To see a similar web page as below.

image (2)