Open In App

How To Create AWS EC2 Using Terraform ?

AWS EC2 (Elastic Compute Cloud) is a web service provided by Amazon Web Services (AWS) that allows users to launch and oversee virtual servers, known as examples, in the cloud. It gives an adaptable and versatile foundation for running different sorts of applications and jobs. With Terraform EC2, clients have unlimited authority over their virtual servers, including the capacity to pick the sort, operating system, and storage options of each instance.

Terraform is an open-source framework and code instrument created by HashiCorp. It empowers clients to characterize and arrange framework assets using a definitive language. Terraform upholds numerous cloud suppliers, including AWS, Azure, and Google Cloud Platform, allowing users to deal with their infrastructure reliably across various stages.



Amazon EC2 (Elastic Compute Cloud)

Amazon EC2 is a web service presented by Amazon Web Services (AWS) that gives resizable compute capacity in the cloud. It permits clients to run virtual servers, known as EC2 instances, in a versatile and flexible manner. EC2 instances can be handily provisioned and designed to meet changing jobs, making them suitable for a wide range of applications.

EC2’s Key Features:

Terraform

Terraform is an open-source Infrastructure as Code (IaC) apparatus created by HashiCorp. It empowers clients to characterize and arrangement foundation utilizing a revelatory setup language. With Terraform, clients can oversee assets across numerous cloud suppliers, including AWS, Sky blue, and Google Cloud Stage, as well as on-premises conditions.



Key Features of Terraform:

Step by Step Process

Setting up AWS account

Now install and configuring Terraform

Go to browser and search for terraform official site in that official site is there terraform download link as shown in below commands and Open a terminal or command prompt and run the command terraform version to verify the installation

sudo yum install -y yum-utils shadow-utils
sudo yum-config-manager --add-repo https://rpm.releases.hashicorp.com/AmazonLinux/hashicorp.repo
sudo yum -y install terraform

Now after installed and configured terraform, Now make a new directory and navigate to it, Terraform file must should be save with filename.tf

Additional files can be created to modularize your code or to store provider-specific configurations. You will define the infrastructure resources you want to create in the main.tf file, such as VPCs, subnets, security groups, and AWS EC2 terraform instances. Terraforms declarative language is used to define each resource, allowing you to declare the desired state of the resource.

Defining an EC2 Instance

Now that we have the networking infrastructure and security groups set up, let’s define the EC2 terraform instance itself. Here’s an example:

resource "aws_instance" "my_instance" {
ami = var.ec2_ami
instance_type = var.ec2_instance_type
subnet_id = aws_subnet.my_subnet.id
vpc_security_group_ids = [aws_security_group.my_sg.id
tags = {
Name = "my-ec2-instance"
}
}

In the above code, we define an AWS EC2 terraform instance resource with the specified AMI (Amazon Machine Image), instance type, subnet, and security group. Also, we assigned a tag to the instance for identification.

Terraform block it was describe the cloud required version and the required credentials. The following example shows that aws provider:

terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 4.16"
}
}
required_version = ">= 1.2.0"
}
provider "aws" {
region = "us-west-2"
profile = "jack.roper"
}
resource "aws_instance" "example_server" {
ami = "ami-04e914639d0cca79a"
instance_type = "t2.micro"
tags = {
Name = "JacksBlogExample"
}
}

VPC (Virtual Private Cloud) is isolated section in aws cloud where your resources can be launched. We can create VPC by using terraform. For example to creating a VPC and Subnet, you would define a resource block like this:

resource "aws_vpc" "sada" {
cidr_block = "10.0.0.0/16"
instance_tenancy = "default"
tags = {
Name = "siva"
}
}

In this example, we specify the vpc with cidr block, subnet ID, and tags for the EC2 instance. Terraform will use this configuration to create the specified EC2 instance when you apply the configuration.


# provider block defines the cloud provider and its configuration
provider "aws" {
region = "us-east-1"
}
# variable block allows you to define variables for reusability
variable "instance_type" {
description = "Type of EC2 instance"
default = "t2.micro"
}
variable "ami" {
description = "Amazon Machine Image ID"
default = "ami-12345678"
}
# resource block defines the AWS resources to be created
resource "aws_vpc" "my_vpc" {
cidr_block = "10.0.0.0/16"
# other VPC configurations...
}
resource "aws_security_group" "my_security_group" {
vpc_id = aws_vpc.my_vpc.id
# other security group configurations...
}
resource "aws_instance" "my_instance" {
ami = var.ami
instance_type = var.instance_type
subnet_id = aws_subnet.my_subnet.id
security_group = [aws_security_group.my_security_group.id]
# other instance configurations...
}
resource "aws_subnet" "my_subnet" {
vpc_id = aws_vpc.my_vpc.id
cidr_block = "10.0.1.0/24"
availability_zone = "us-east-1a"
map_public_ip_on_launch = true
# other subnet configurations...
}
# output block allows you to define values to be displayed after apply
output "instance_ip" {
value = aws_instance.my_instance.public_ip
}

Providers Block:

Variable Block:

Resource Block:

Output Block:

Infrastructure as Code (IaC) is a method that permits you to oversee and arrangement foundation assets utilizing code instead of manual cycles. Terraform, being an IaC device, empowers you to characterize your framework in a definitive language and keep up with it as rendition controlled code. Let’s learn how to set up an AWS EC2 terraform instance and write infrastructure as code using Terraform.

Configuring Security Groups, Security is most important due to it acts as a virtual firewalls, its controlling inbound and outbound traffic for your AWS EC2 terraform instance.

resource "aws_security_group" "my_sg" {
name = "my-security-group"
description = "Allow inbound SSH and HTTP traffic"
inbound {
from_port = 22
to_port = 22
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
inbound {
from_port = 80
to_port = 80
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
outbound {
from_port = 0
to_port = 0
protocol = "-1"
cidr_blocks = ["0.0.0.0/0"]
}
}

Now it’s time to Initializing and applying the terraform configuration after writing the terraform code code by using following code:

terraform init

When using Terraform, the terraform init command is a crucial step. It initializing a working directory, setting up the fundamental parts for Terraform to collaborate with the specified backend (like AWS, Azure , or local), and download any expected supplier modules.

To apply the terraform configuration and create the EC2 terraform instance, to run the following command:

terraform apply

Cleaning up and destroying AWS resources is a fundamental stage to prevent unnecessary costs and keep a clean infrastructure. This is the way you can tidy up the assets made by your AWS EC2 terraform example:

Terminating the EC2 Occurrence

As referenced before, terminating the terraform EC2 instance will remove it for all time, including any related storage and data. Make a point to take backups if necessary prior to terminating the instance.

Removing Terraform Resources: Removing command is necessary in order to ensure that all Terraform resources are properly destroyed. This order will dissect the Terraform state and eliminate every one of the assets oversaw by Terraform, including the VPC, subnet, security groups, and some other resources defined in your Terraform setup.

Run the following command in the directory where terraform project is located

terraform destroy

Conclusion

Terraform makes it easy and scalable to set up virtual servers in the cloud by creating an AWS EC2 instance. All through this aide, we take care of the essentials of AWS EC2 and Terraform, from setting up your AWS account and arranging Terraform to composing foundation as code and dealing with the EC2 occasion lifecycle.

By utilizing Terraform, you can characterize your foundation in code, empowering you to form control, automation, and duplicate your system across various conditions. With the force of Terraform modules, you can undoubtedly reuse and share framework setups, reducing duplication and advancing consistency.

AWS EC2 Using Terraform – FAQ’s

How does Terraform work?

Terraform is an open-source Infrastructure as Code (IaC) apparatus created by HashiCorp. It empowers clients to characterize and arrangement system utilizing a revelatory setup language.

What is Foundation as Code (IaC)?

Infrastructure as Code is an idea where system provisioning and the board are finished through code as opposed to manual cycles. Terraform is a famous IaC device.

What is the reason for the terraform init order?

terraform init is utilized to instate a Terraform working catalog. It sets up the backend and downloads the necessary provider plugins.

How does Terraform keep up with state data?

To keep track of the infrastructure’s current state, Terraform makes use of a state file. The state document is normally put away from a distance or locally and assists Terraform with figuring out the distinctions between the ideal and genuine system.

Could I at any point involve various suppliers in a solitary Terraform setup?

Yes, Terraform upholds utilizing numerous suppliers inside a single design. This is valuable while overseeing assets across various cloud suppliers or administrations.

What is the meaning of the .tf record extension in Terraform?

Terraform arrangement documents utilize the .tf record expansion. These records contain the foundation code written in HashiCorp Setup Language (HCL).


Article Tags :