Open In App

How To Create AWS EC2 Using Terraform ?

Last Updated : 21 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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:

  • Scalability: You can easily increase or decrease the number of instances based on demand.
  • Instance Types: Choose from compute-optimized, memory-optimized, or storage-optimized instance types that are optimized for various use cases.
  • AMI (Amazon Machine Image): Launch instances with particular software and operating system configurations by utilizing pre-configured images.
  • Elastic Load Balancing: Circulate approaching traffic across different examples to ensure high accessibility and adaptation to non-critical failure.

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:

  • Declarative Configuration: Depict the ideal infrastructure state in a configuration file (written in HashiCorp Design Language – HCL).
  • Support for Multi-Clouds: Arrangement and oversee assets across different cloud suppliers with a solitary arrangement of design documents.
  • Version Control: Infrastructure code can be formed, permitting joint effort and change following.
  • Dependency management: The order of resource creation and their interdependencies are automatically managed by Terraform.
  • Plan and Apply: Terraform gives an planning phase (terraform plan) to review changes prior to applying them (terraform apply).

Step by Step Process

Setting up AWS account

  • Go to AWS Management Console
  • Login with by using your credentials
  • Now you need to generate access key to authenticate Terraform with your AWS account
  • In AWS management console in home screen search for IAM ( Identity and Access Management ) service. Choose Users and click on Add user .
  • Give a username and select administration access as the access type. Attach necessary permissions to the user.
  • Review the user details and create the user. Now you will see the access key ID and secret access key. Save this information securely as it will be required when configure Terraform.

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

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:

  • Providers block is utilized to design the Providers, which is liable for overseeing assets in a particular cloud environment (e.g., AWS, Azure, and so on.).
  • It remembers subtleties, for example, the district for which assets ought to be made.

Variable Block:

  • Input variables that can be used throughout your Terraform configuration can be defined using the variable block.
  • Helps in defining your design and making it more adaptable.
  • You can set default values, depictions, and different qualities for factors.

Resource Block:

  • Resource block is the most key structure block in Terraform.
  • It proclaims an asset type (e.g., aws_instance, aws_vpc) and its particular setups.
  • Every asset block makes an occurrence of the asset it depicts.

Output Block:

  • Output block characterizes values that will be displayed subsequent to applying the Terraform arrangement.
  • Valuable for showing data like IP addresses, DNS names, and so on.
  • Gives a method for uncovering explicit data for outside use

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

destroy command

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).



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads