Deploying Multiple AWS EC2 instances with Terraform
Introduction
Terraform is an open-source Infrastructure as Code (IaC) tool that uses a declarative configuration language to let users define and provision cloud infrastructure. This post explains how to set up security groups, deploy EC2 instances in AWS, and specify output values for obtaining instance information.
Objectives:
Deploy EC2 instances in AWS.
Set up security groups to control both outgoing and incoming traffic.
Define output values to retrieve instance information effectively.
Automate the deployment of infrastructure to improve management and scalability.
Prerequisites:
Before proceeding, ensure you have:
An AWS account
Terraform installed on your system
AWS CLI configured with appropriate credentials
Note:-
Change the ami_id variable to match your required AMI. Modify the security group rules as per your requirements.
We define variables to parameterize our infrastructure, making it reusable and scalable.
variable"ami_id" {type = stringdefault = "ami-09c813fb71547fc4f"description = "This is ami id RHEL9"}variable"instance_name_loop" {type = list(any)default = ["mysql", "frontend", "backend"]description = "description"}variable"environment" {type = stringdefault = "dev"description = "this is env variable"}variable"instance_type" {type = stringdefault = "t2.micro"description = "This is instance type"}variable"ec2_tgsa" {type = map(any)default = {project = "expenses"component = "backend"environment = "dev"Name = "expenses dev backend" }description = "description"}variable"from_port" {type = numberdefault = 0description = "Starting port for inbound rules (0 allows all)"}variable"to_port" {type = numberdefault = 0description = "Ending port for inbound rules (0 allows all)"}variable"protocol" {type = stringdefault = "-1"description = "this is protocal allow all"}variable"cidr_blocks" {type = list(string)default = ["0.0.0.0/0"]description = "Allow all ip"}variable"sg_tags" {type = map(any)default = {Name = "allow_tl" }description = "security tags"}
Creating an EC2 Instance
The aws_instance resource defines three EC2 instances using the count parameter. Each instance is assigned a unique name from the instance_name_loop variable.
1 thought on “Effortless Multiple AWS EC2 Deployment with Terraform: Automate Your Infrastructure Today!”