ec2-instance module
ec2-instance module
We are creating ec2 instance module and its resources via terraform.
First you have to install terraform on your Ec2 instance.
Give the permissions to instance via role.
Connect the instance.
sudo –i
mkdir modules
cd modules
mkdir ec2-instance
cd ec2-instance
vim main.tf
Paste Below Code:
# Terraform Block
# vpc creation
tags = {
Name = "main"
}
}
# subnet creations
tags = {
Name = "Main-subnet"
}
}
# IGW creation
tags = {
Name = "main-igw"
}
}
# Routetable creation
route {
cidr_block = "0.0.0.0/0"
gateway_id = aws_internet_gateway.igw.id
}
tags = {
Name = "main-RT"
}
}
# subnet associate
# instances creations
# security group
resource "aws_security_group" "web_sg" {
name = "HTTP and SSH"
vpc_id = aws_vpc.main.id
ingress {
from_port = 80
to_port = 80
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
ingress {
from_port = 22
to_port = 22
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
}
vim out.tf
Paste below code :
output "instance_ip_addr" {
value = aws_instance.web.private_ip
}
output "instance_public_ip_addr" {
value = aws_instance.web.public_ip
}
output "aws_route_table_id" {
value = aws_route_table.my_rt.id
}
output "instance_id" {
value = aws_instance.web.id
}
vim var.tf
Paste below code:
variable "aws_key_pair" {
type = string
default = "ssh-rsa
AAAAB3NzaC1yc2EAAAADAQABAAABgQCRUKits95UeWBfOOscIwhbhLsimnV/bC/CvJ+Pf2CJnwsnlEmK1
s5mKdJf0uQJe54AgEzv3cdkNoSeDocluFRaDFYHjWJ/g53128BTE9hPaEZSY9kxsyLuoI3u8BJpeviioA
vNBBM1tHfDIzhrzzPXWz959rkt1nOXIHl3vZTAl5Yb7/J67O7fWj+yT1LUT9Yvrazwr3bnR6Udbs+EVT5
xVdxadt8mGjScF6YDgi5dus2vzRyMd7eBwTxr3wLlxfTd5kR4czim47ql0IKGXMsiZP72GiSkir602Ebq
vLcPDSljkwfenativRd/49hQT+t2DU/MbuwEBY7i5ocoqhOE0Lfhve6Nplz4uN/ckMtqj3b/CFV6ii8b4
ykX8e18RkNwOqJTEcYiCBUls6D3DNNaBRsEY+MpwTUqFo3JE/S2tBU2Kc+ntHYbihlh+oNxfa9bvPW2+n
FbvnguE9PeaT8elSbOpwuruzXZwwxj6qdwn1XhpL/tzU0iKJZ1q9a49eU= root@ip-172-31-7-
113.ap-south-1.compute.internal"
}
variable "instance_type" {
type = string
default = "t2.micro"
}
variable "cidr_block" {
type = string
description = "subnet cidr block"
default = "10.0.1.0/24"
}
variable "ami" {
type = string
default = "ami-0d2614eafc1b0e4d2"
}
cd ..
vim main.tf
Paste below code:
provider "aws" {
region = "ap-south-1"
}
terraform {
backend "s3" {
bucket = "my-tf-bucket501"
key = "tf-state"
region = "ap-south-1"
}
}
module "ec2-instance" {
source = "./ec2-instance"
}
tf init
tf plan
tf apply –auto-approve
tf destroy –auto-approve