Setting up EC2 environment in AWS using Terraform
📄Task
✏To create and setup key pair, security groups, ec2 instance and attaching it with EBS with storage of 1 GB.
First we will create a Profile.tf file to mention provider on which we are going to work i.e., AWS .
then write following terraform code :
provider "aws" {
region = "ap-south-1"
access_key = "[access_key]"
secret_key = "[your_secret_key]"}
Note: Replace [access_key] and [your_secret_key] with yours.
Now we will be writing the ec2.tf for this task.
✔Step 1:
To create a Key pair.
resource "aws_key_pair" "terrakey" {
key_name = "terraform-key"
public_key = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQD3F6tyPEFEzV0LX3X8BsXdMsQz1x2cEikKDEY0aIj41qgxMCP/iteneqXSIFZBp5vizPvaoIR3Um9xK7PGoW8giupGn+EPuxIA4cDM4vzOqOkiMPhz5XK0whEjkVzTo4+S0puvDZuwIsdiW9mxhJc7tgBNL0cYlWSYVkz4G/fslNfRPW5mYAM49f4fhtxPb5ok4Q2Lg9dPKVHO/Bgeu5woMc7RY0p1ej6D4CKFE6lymSDJpW0YHX/wqE9+cfEauh7xZcG0q9t2ta6F6fmX0agvpFyZo8aFbXeUBr7osSCJNgvavWbM/06niWrOvYX2xwWdhXmXSrbX8ZbabVohBK41 email@example.com"
✔Step 2:
Create a security group
first create vpc for it
resource “aws_vpc” “main” {
cidr_block = “10.0.0.0/16”
}
then write this
resource "aws_security_group" "SecGroup" {
name = "TLS"
description = "Allow TLS inbound traffic"
vpc_id = aws_vpc.main.id
ingress {
description = "TLS from VPC"
from_port = 443
to_port = 443
protocol = "tcp"
}
egress {
from_port = 0
to_port = 0
protocol = "-1"
}
tags = {
Name = "allow_tls"
}}
✔Step 3:
Launch an instance using the above created key pair and security group.
✔Step 4:
Create an EBS volume of 1 GB.
✔Step 5:
The final step is to attach the above created EBS volume to the instance you created in the previous steps.
Now first write this command in your terminal
terraform init
This command will initialise the terraform with the provider which you have mentioned.
Now write the following command to apply the setup for your instance:
terraform apply -auto-approve
then
Yippie, the whole task is executed.✨
Now, to destroy the environment:
terraform destroy
Type “yes” when prompted.
Destroyed successfully!
Thanks for reading.
Have a great day ahead.😊