Introduction
This guide provides a step-by-step explanation of how to use Terraform to deploy an AWS EC2 instance with a security group that allows HTTP traffic. The configuration automates the setup of an Apache web server on the instance.
Prerequisites
Before running the Terraform script, ensure you have the following:
An AWS account.
Terraform installed on your system.
AWS CLI configured with appropriate credentials.
Terraform Script Breakdown
Below is the Terraform script used to create an EC2 instance and security group:
- Provider Configuration
The provider block specifies AWS as the cloud provider and sets the region where the resources will be deployed.
- EC2 Instance Configuration
This resource creates an EC2 instance with the following configurations:
Uses an Amazon Linux 2 AMI (ami-08b5b3a93ed654d19).
Assigns a t2.micro instance type (free-tier eligible).
Attaches a security group.
Runs a startup script that installs Apache, starts the web server, and creates a simple web page.
- Security Group Configuration
This security group:
Allows inbound HTTP traffic on port 80 from any IP (0.0.0.0/0).
Allows all outbound traffic.
Deploying the Terraform Script
Follow these steps to deploy the resources:
- Initialize Terraform (downloads required provider plugins):
- Preview the execution plan:
- Apply the configuration (creates resources in AWS):
4. Verify the Instance:
- Copy the public IP from the output or AWS Console.
Destroying the Infrastructure
To delete the created resources and avoid charges, run:
Conclusion
This Terraform script automates the deployment of an EC2 instance running an Apache web server. By using infrastructure as code, you can quickly set up and manage AWS resources efficiently.
Top comments (0)