22nd Oct 2021

Unlock the magic of Terraform — launching Nginx webserver🚀


Written By, Nipun Parekh


The first question that comes to your mind is what is terraform and why use it?

So, Terraform is a tool for building, changing, and versioning infrastructure safely and efficiently. Terraform can manage existing and popular service providers as well as custom in-house solutions.

By just writing code you will get your infrastructure ready, Isn’t it amazing?

Graphic Image

We are going to divide terraform code into 3 sections that are:

  1. Provider
  2. Resource
  3. Output

Section-1: Provider

In the provider section, we have to mention which provider we are going to use and their credentials, We are going to use AWS Cloud

Let’s write the terraform code:

Don’t try to use access_key and secret_key because it is wrong 🙂

You have to put your secret_key and access_key

I am using was region [ap-south-1], you can use other regions as well.


Section-2: Resource

This is the main section in this section we are going to create an EC2 instance and we are going to install Nginx also.

Terraform code:

In this we are going to use the ec2 server as a resource, that’s why we have written resource “aws_instance” “ec2”

ami -> if you want to use centos, ubuntu, SUSE Linux just give that aim id over here in ami. I am using Ubuntu OS

instance_type -> type of server that you want to use, I am going to use t2.micro. you can also use other server types like [t3.medium, t2.nano &, etc.]

key_name -> your key through that terraform will go into your server and install Nginx. 

security_groups -> In the Security group you must allow port 80 to access by [Port 80 must be publicly accessible]. You have to enter that security group name

provisioner “remote-exec” -> This module will run our script into our Server/ EC2 instance. What it will be going to install.

  1. sudo apt-get update -y -> it will update the server
  2. sudo apt install nginx -y -> this command will install Nginx in our server.

Connection -> Is going to connect server so through this connection terraform can install Nginx. 

Don’t forget to put your private key inside your project folder

Section-3: Output

We want our Server IP as an output for that we have to write this terraform code:


So our whole terraform code will be like this:

file name: ec2.tf

Thanks for reading. Hope this content will help you.

Written By,

DevOps at Yudiz Solutions Pvt. Ltd