Quick Summary:

In the constantly evolving landscape of cloud computing, getting virtual servers up and running is essential and demanding. While Amazon Web Services (AWS) offers EC2 instances that function as powerful virtual computers, manually setting up and configuring each of these EC2 instances can be an intensive and complex process. This is where Terraform steps in as a game changer. The tool is all about using files containing instructions for consistent and repeatable deployments, streamlining the process, and saving time and effort.

This blog will explore how to create and provision a Terraform EC2 Instance on AWS. We’ll provide a comprehensive overview of the necessary prerequisites, guide you through the authentication process, explain the setup of Terraform configuration files, and walk you through each stage of the Terraform lifecycle, including initialization, planning, application, and deployment verification.

But, before we dive into the technicalities of a Terraform EC2 instance example, let’s briefly understand AWS EC2 and Terraform.

Table of Contents

What is AWS EC2 Instance?

Amazon Elastic Compute Cloud (EC2) is a service provided by Amazon Web Services (AWS) that lets users manage virtual servers seamlessly within a cloud-based environment. These virtual servers, known as instances, can be customized with different specifications like computing power, memory, storage, and network capacity. EC2 instances are like basic elements for running applications on AWS, offering scalable computing resources that can be accessed as needed.

Every EC2 instance functions as a virtual machine (VM) capable of running various operating systems and applications. Users can choose from different instance types, depending on their specific needs. These types include general-purpose, compute-optimized, memory-optimized, and storage-optimized instances.

What is Terraform?

Created by HashiCorp, Terraform is a tool enabling developers to automate the creation and management of cloud infrastructure. Using straightforward language, Terraform allows users to define the entire infrastructure setup, ensuring simplicity and reproducibility across different cloud providers.

When we specifically talk about creating Terraform EC2 instances, it streamlines the process by allowing developers to define their infrastructure needs in a declarative language with a clear code format, ensuring a smooth and consistent deployment process. It eliminates errors, enables easy management of changes, and provides an easy way to maintain version control. With Terraform, developers can express what they want, and the tool executes it, resulting in efficient and error-free provisioning and management of AWS EC2 instances.

Now that we have understood the basics of AWS EC2 instances and Terraform, let’s quickly go through the prerequisites.

Prerequisites

Before diving into the Terraform script, ensure the following requirements are met:

1. AWS Account: To utilize AWS services and manage resources in the cloud, you’ll need an AWS account. If you don’t have an account, sign up now and get a free EC2 instance for the first 12 months.
• 750 monthly hours allocated for free Linux usage (t2.micro or t3.micro, depending on region).
• 750 monthly hours allotted for free Windows usage (t2.micro or t3.micro, depending on region).

Remember, after the 12-month free period, running your EC2 instance will incur charges. To prevent unexpected expenses, delete unnecessary resources following the tutorial.

2. Install Terraform: Ensure you have Terraform installed on your computer to write and run Terraform code. Download the appropriate version to match your requirements, or check it out here. After downloading, unzip the file, place it in a folder on your computer, and add that folder to your computer’s PATH.

3. Install AWS CLI & IAM User With Permissions
To manage your EC2 instances and other AWS resources using your computer’s command line, install the AWS CLI by accessing it here. After installation, configure it using a terminal command. Also, ensure an IAM user with access and secret keys has the required permissions to create EC2 instances.

4. Create SSH Key Pair
Next, create an SSH key pair to associate with the Linux instance.

Copy Text
ssh-keygen -t rsa -b 4096

Executing this command will generate a key pair with a 4096-bit length. This command will generate two files: private and public keys. Keep the private key on your system, and the public key will be used to access the EC2 instance via SSH. Protocol.

Authentication with AWS

Now that all the prerequisites are met, the next step is to configure the AWS account on your local system, hence execute the following command:

Copy Text
aws configure

Ensure that you include the “aws_access_key_id” and “aws_secret_access_key” attributes. Additionally, you can configure the AWS region. This command will store the access keys and secret keys locally in the $HOME/.aws/config folder.

Assign a name to the profile, such as “test,” which will be used in your Terraform script for provider information.

Ready to elevate your AWS infrastructure?

Explore the seamless deployment of AWS EC2 instances using Terraform for your project needs. Hire AWS developers for expert assistance and optimization.

Creating an AWS EC2 instance using Terraform

Let’s look at the steps in creating the Terraform EC2 Instance.

1. Create Terraform Script for EC2 Instance

Terraform configuration files show how to connect to AWS and specify the resources you want Terraform to handle and create.

First, we will create a file “provider.tf” to manage interactions with AWS-supported resources. In this file, configure the provider with the appropriate credentials.

Consult the Terraform documentation to obtain the essential details about the required provider.

Copy Text
terraform {
  required_providers {
    aws = {
      source = "hashicorp/aws"
      version = "5.31.0"
    }
  }
}

provider "aws" {
  region = "us-east-1"  # Set the AWS region
  profile = "test"      # AWS profile 
}

Once we have added provider information, proceed by creating a file named “main.tf” and add the terraform script to create an EC2 instance in the AWS account.

Copy Text
resource "aws_instance" "test-instance" {
  ami           = "ami-0fc5d935ebf8bc3bc"  # Ubuntu 22.04 LTS
  instance_type = "t2.micro"
  key_name      = "test"  # SSH key pair

  tags = {
    Name = "test-server"
  }
}

In this setup, we’ve chosen the Ubuntu 22.04 LTS image. The instance size is set to “t2.micro,” and the EC2 instance will be created in the us-east-1 region.

2. Terraform Initialization

Initiate the Terraform working directory by utilizing the “terraform init” command. When you run “terraform init,” Terraform downloads the required provider plugins and configures the backend to store the Terraform state.

Copy Text
terraform init

Initializing the backend...

Initializing provider plugins...
- Finding latest version of hashicorp/aws...
- Installing hashicorp/aws v5.31.0...
- Installed hashicorp/aws v5.31.0 (signed by HashiCorp)

Terraform has created a lock file .terraform.lock.hcl to record the provider
selections it made above. Include this file in your version control repository
so that Terraform can guarantee to make the same selections by default when
you run "terraform init" in the future.

Terraform has been successfully initialized!

3. Terraform Plan

The execution plan is formulated by employing the “terraform plan” command. This plan details the modifications Terraform will make to apply to the infrastructure to reach the specified desired state outlined in the Terraform script.

Copy Text
terraform plan

Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols:
  + create

Terraform will perform the following actions:

  # aws_instance.test-instance will be created
  + resource "aws_instance" "test-instance" {
  	+ ami                              	= "ami-0fc5d935ebf8bc3bc"
  	+ arn                              	= (known after apply)
  	+ associate_public_ip_address      	= (known after apply)
  	+ availability_zone                	= (known after apply)
  
#.....

Plan: 1 to add, 0 to change, 0 to destroy.

─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────

Note: You didn’t use the -out option to save this plan, so Terraform can’t guarantee to take exactly these actions if you run “terraform apply” now.

4. Terraform Apply

Execute the “terraform apply” command to implement the modifications specified in the Terraform script onto the infrastructure.

Copy Text
terraform apply

Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols:
  + create

Terraform will perform the following actions:

  # aws_instance.test-instance will be created
  + resource "aws_instance" "test-instance" {
  	+ ami                              	= "ami-0fc5d935ebf8bc3bc"
  	+ arn                              	= (known after apply)
  	+ associate_public_ip_address      	= (known after apply)
  	+ availability_zone                	= (known after apply)
  	+ cpu_core_count                   	= (known after apply
#.....

Plan: 1 to add, 0 to change, 0 to destroy.

Do you want to perform these actions?
  Terraform will perform the actions described above.
  Only 'yes' will be accepted to approve.

  Enter a value:

After ensuring you are satisfied with the planned infrastructure changes, execute “terraform apply” and enter “yes” to proceed. Alternatively, you can use “Terraform Apply-Auto-approve” to approve the changes automatically without manual confirmation.

5. Verify EC2 Instance

Once the “apply” process concludes in your Terraform EC2 instance example, confirm by checking the AWS console or using the AWS CLI on your local system to ensure the EC2 instance has been successfully created in your AWS account.

These were the steps to create an EC2 instance using Terraform. While you are at it, you might also find interest in exploring AWS S3 Bucket creation using Terraform.

Takeaway

In this article, we’ve walked through the process of deploying a Terraform EC2 Instance. By leveraging IaC, you can efficiently manage your infrastructure, promote reproducibility, and automate the provisioning of resources in the AWS cloud. As for best practices, always check for the latest provider versions and exercise caution when applying changes to production environments. If you require assistance, consider exploring AWS consulting services for expert guidance and support in optimizing your cloud infrastructure. For more advanced cloud tutorials, visit our page and dive deeper into emerging technologies to enhance your knowledge.

Need Help Deploy Terraform EC2 Instance?

Ensure a seamless experience by simplifying these complexities handled with expertise.

GET IN TOUCH NOW!

Build Your Agile Team

Hire Skilled Developer From Us

Subscribe for
weekly updates

newsletter

What Makes Bacancy Stand Out?

  • Technical Subject Matter Experts
  • 2500+ Projects Completed
  • 90% Client Retention Ratio
  • 12+ Years of Experience

Our developers primarily focus on navigating client's requirements with precision. Besides, we develop and innovate to deliver only the best solutions to our clients.

get in touch
[email protected]

Your Success Is Guaranteed !

We accelerate the release of digital product and guaranteed their success

We Use Slack, Jira & GitHub for Accurate Deployment and Effective Communication.

How Can We Help You?