How to Create EC2 Instance using Terraform on AWS

How to Create EC2 Instance using Terraform on AWS

How to Create EC2 Instance using Terraform on AWS

There are many ways in which you can create resources on AWS. Terraform is one such amazing tool that lets you create your infrastructure as a code to manage them better.

In this post, I will show you how to create EC2 instance using terraform on AWS. You can also checkout other ways to create an instance such as-

Before we get into the details, let’s try to understand what is Terraform and how do you create a resource such as EC2 on AWS using it.

Don’t want to miss any posts from us? join us on our Facebook group, and follow us on Facebook, Twitter, LinkedIn, and Instagram. You can also subscribe to our newsletter below to not miss any updates from us.

What is Terraform?

Terraform is a popular open-source Infrastructure as Code(IaC) tool by HashiCorp. It lets you provision your infrastructure as code.

  • You can provision, update and version your infrastructure in an efficient manner using Terraform.
  • You declare your required infrastructure in a configuration file and terraform creates it in the correct order.
  • Configuration files are in a human-readable format using HashiCorp Configuration Language(HCL) or even JSON is supported.
  • Terraform is Cloud Agnostic and supports numerous cloud providers like AWS, Azure, GCP etc.

What is EC2?

Amazon EC2 or Elastic Compute Cloud is a compute service provided by AWS. It lets you rent virtual servers or computers known as EC2 instances that you can use to run your workloads such as websites on AWS.

In very simple words If I say, Instead of buying your own computer to run your website, you rent a computer that exists in some other part of the world and you access it virtually using the internet. You can customize the configuration of this virtual machine or EC2 instance and pay only for what you use.

EC2 Instances can be created in various ways like console, CLI, SDK, CloudFormation, CDK, Terraform etc. This tutorial discusses launching an Instance using Terraform.

How Do you Create a Resource Using Terraform on AWS?

Unlike CloudFormation, you need to install terraform in your system before you can use it to create a resource like EC2 instance on your cloud provider(In our case AWS).

Once installed, you create your configuration file(filename.tf – they have .tf extension) and use the below set of commands to deploy your resources.

$ terraform init
$ terraform plan
$ terraform apply
$ terraform destroy

I highly recommend you check my step-by-step guide to help you get started with terraform on AWS in the right way. Here is the link-

Once you go through that post you will already have an idea on-

  • Installing Terraform
  • Creating a Terraform IAM user
  • Setting up AWS CLI to allow Terraform to authenticate to AWS
  • Setting up your workspace using Visual Studio Code(VS Code) IDE
  • Deploying Your First Resource on AWS using Terraform

By this time, I assume you already know how to deploy a resource on AWS using Terraform.

Alright, let’s get started with EC2 Instance creation.

Prerequisite:

How to Create EC2 Instance using Terraform on AWS

In this article, I will launch a very simple EC2 or Elastic Compute Cloud Instance using terraform. Later, in this tutorial, we’ll also learn how to update the instance with some additional configuration.

To create an EC2 instance using terraform, you will need an aws_instance Terraform resource. Feel free to refer to the official documentation for up-to-date properties.

Here is what a simple EC2 instance resource looks like-

resource "aws_instance" "demo_instance" {
  ami = "ami-06489866022e12a14"
  instance_type = t2.micro
}
  • ami: An AMI or Amazon Machine Image is an image or template that contains the software configurations like operating system, application servers etc. For example, Amazon Linux 2 is a frequently used AMI. AMI is different for all regions. So grab the AMI for your region before launching the instance.
  • instance_type: instance_type to use for your instance. For example t2.micro

Some Other Important Parameters:

  • key_name: Name of the Key Pair to use for your instance. If you don’t specify it you won’t be able to SSH into your instance from your local system.
  • subnet_id: VPC Subnet ID to launch your instance in. If you want to launch your instance in the choice of your VPC, then you use this parameter. There is no vpc_id attribute. The subnet_id only decided which VPC to launch your instance in.
  • tags: Tags to assign to your instance
  • user_data: To bootstrap your EC2 instance on start. You specify the commands you want to run on start to prep your instance before using it. See a detailed article on setting up user_data for Ec2 using terraform
  • iam_instance_profile: You use it to attach an IAM role to your EC2 instance. Here is an article on how to attach a role using Terraform.
  • vpc_security_group_ids: You can specify all the security group Ids you want to associate with your instance. If you don’t specify it, by default a default security group gets attached to the instance.

Steps to Create EC2 Instance using Terraform on AWS

  1. Create a Working Directory/Folder
  2. Create your EC2 Instance Configuration File
  3. Initialize Your Directory to Download AWS Plugins
  4. Plan and Deploy
  5. Validate

Step 1: Create a Working Directory/Folder

Create a folder in which you will keep your EC2 instance terraform configuration file.

EC2 folder

Step 2: Create your EC2 Instance Configuration File

Navigate inside the folder and create your instance configuration file. You can name it as per your wish, but to keep things simple, I will name it main.tf

First of all, add the provider declaration and how Terraform will authenticate with the provider(AWS in our case). Here is how it looks-

terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 3.27"
    }
  }
}

provider "aws" {
  profile = "default"
  region  = "ap-south-1"
}

Next, add the EC2 instance resource. The simplest resource to create an EC2 looks like below-

resource "aws_instance" "demo_instance" {
  ami = "ami-06489866022e12a14"
  instance_type = "t2.micro"
}

However, you can customize it by adding more parameters like those shown below-

resource "aws_instance" "demo_instance" {
  ami                    = "ami-06489866022e12a14"
  instance_type          = "t2.micro"
  key_name               = var.key-name
  vpc_security_group_ids = [aws_security_group.allow_port80.id]
  iam_instance_profile   = aws_iam_instance_profile.demo-profile.name
  user_data              = <<EOF
		#!/bin/bash
		yum update -y
		yum install -y httpd.x86_64
		systemctl start httpd.service
		systemctl enable httpd.service
		echo ?Hello World from $(hostname -f)? > /var/www/html/index.html
	EOF
  tags = {
    Name = "Demo_Instance"
  }
}

However, to start with I will use the bare minimum and create an instance.

Make sure to change the AMI and instance_type based on your need. Save the file into a file with .tf extension. You can name as per your wish it main.tf conventionally as well.

Note: In the configuration file above. If you notice, instead of hardcoding credentials in the provider, I am using a CLI profile. This way is more secure to authenticate to AWS. Wanna know why? Read this

Step 3: Initialize Your Directory to Download AWS Plugins

You only do this step once per folder/directory. This basically means you are downloading relevant codes/plugins for your mentioned provider which in our case is AWS.

terraform init
How to Create EC2 Instance using Terraform on AWS 1

Step 4: Plan and Deploy

The configuration file is created and the directory is initialized. That means we are all ready to deploy our EC2 instance.

Now, if you want, you can run the command terraform plan to see what’s actually being created.

terraform plan

terraform plan
How to Create EC2 Instance using Terraform on AWS 2
How to Create EC2 Instance using Terraform on AWS 3

Ideally, it shows what is going to be created once you run terraform apply. So in case you see something unintentional, you can review your template and correct it. If all looks well to you, go ahead and apply hit terraform apply.

terraform apply

terraform apply

Type terraform apply and hit enter.

The prompt asks you – Do you want to perform these actions?

Type yes and hit enter.

If everything is well, your resource is created and you see a success message as seen below-

How to Create EC2 Instance using Terraform on AWS 4

You can see that our EC2 instance is created and You can so see the create instance Id.

Behind the scene:

Ideally, terraform runs terraform plan every time you hit the command terraform apply. Once you review the plan and confirm yes then only resources will be created.

Terraform looks for .tf file and shows you what’s being created.

Review the output and if all is fine say yes to the prompt.

Once you confirm, terraform starts creating your resource and in a matter of seconds, your instance is created.

Therefore, it’s not always necessary to run terraform plan. You can directly run terraform apply as it will run terraform plan anyway behind the scene.

Step 5: Validate

Login to AWS Management Console and navigate to EC2. Validate your Instance and its setting. This is what it looks like for our use case.

How to Create EC2 Instance using Terraform on AWS 5

By now, we have successfully created an EC2 Instance using Terraform on AWS.

Let’s see how to update the instance configuration we just created using Terraform.

Update an EC2 Resource using Terraform

You might have questions like, well we created the instance but what if we want to update its configurations? For example, I want to add a tag to my instance- how to go ahead with it.

How do we do it?

Well, it’s very simple, my friend. Update the configuration file with desired settings and run terraform apply once more.

And that’s it- if your setting is correct- your EC2 will be updated with the tag.

Clean Up

Finally, if you are doing this exercise for learning purposes, you can clean up by destroying the created resource ie our EC2 instance as you don’t wanna be charged for it.

terraform destroy
How to Create EC2 Instance using Terraform on AWS 6

Very Important Note: Always keep a budget set in your AWS account. You can say as soon as $1 is spent, notify me. And AWS budget will do so. Here is a detailed tutorial on how to setup AWS budget to avoid unnecessary billing shocks.

Conclusion

In this article, we learnt how to create EC2 Instance using Terraform on AWS.

Firstly, we learnt how to create any resource using terraform then we learnt a bit about EC2 or Elastic Compute Cloud.

Secondly, we created a configuration file to create an EC2 instance of t2.micro type. Later we updated the configuration to add tags to the instance. That means we learnt to create as well as update an EC2 instance using Terraform.

Finally, we learnt to destroy everything and delete the instance we created, so that we are not billed unnecessarily.

Well, that was my take on “How to Create EC2 Instance using Terraform on AWS“. Please let me know if the post was useful to you.

Enjoyed the content?

Subscribe to our newsletter below to get awesome AWS learning materials delivered straight to your inbox.

If you liked reading my post, motivate me by

  • Adding a comment below on what you liked and what can be improved.
  • Follow us on
  • Share this post with your friends and colleagues.

Suggested Read:

Leave a Reply

Your email address will not be published. Required fields are marked *