Terraform Project to Create 5 EC2 Instances
Terraform Project to Create 5 EC2 Instances
This document outlines the steps to create a Terraform project that provisions five EC2
instances on AWS. The project will include the necessary configuration files and instructions
to deploy the instances efficiently. By following this guide, you will be able to set up a
scalable infrastructure using Infrastructure as Code (IaC) principles.
Prerequisites
• An AWS account
• Terraform installed on your local machine
• AWS CLI configured with your credentials
Project Structure
Create a directory for your Terraform project and navigate into it:
mkdir terraform-ec2-instances
cd terraform-ec2-instances
• main.tf
• variables.tf
• outputs.tf
`main.tf`
This file contains the main configuration for your EC2 instances. Create the main.tf file and
add the following content:
provider "aws" {
region = "us-east-1" # Change to your preferred region
}
tags = {
Name = "WebServer-${count.index + 1}"
}
}
`variables.tf`
In this file, you can define any variables you want to use in your configuration. For this
example, we will keep it simple:
variable "region" {
description = "The AWS region to deploy the instances"
default = "us-east-1"
}
variable "instance_type" {
description = "The type of EC2 instance"
default = "t2.micro"
}
`outputs.tf`
This file will define the outputs of your Terraform project, such as the public IP addresses of
the created instances:
output "instance_ips" {
value = aws_instance.web[*].public_ip
}
Initialize Terraform
Before you can apply your configuration, you need to initialize your Terraform project. Run
the following command in your project directory:
terraform init
Next, you can create an execution plan to see what resources Terraform will create:
terraform plan
If everything looks good, you can apply the configuration to create the EC2 instances:
terraform apply
You will be prompted to confirm the action. Type yes and press Enter.
Once the deployment is complete, you can verify that the instances have been created by
checking the AWS Management Console or by using the output command:
Clean Up
To remove the EC2 instances and clean up your resources, run the following command:
terraform destroy
You will again be prompted to confirm the action. Type yes to proceed.
Conclusion
You have successfully created a Terraform project to provision five EC2 instances on AWS.
This project serves as a foundation for further enhancements and scaling your infrastructure
as needed. By leveraging Terraform, you can manage your cloud resources efficiently and
consistently.