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.
Generating an RSA Key Pair
This generates a 4096-bit RSA private key, which will be used to access the EC2 instance securely.
Creating an AWS Key Pair
Terraform creates an AWS key pair using the public key from the RSA key.
Saving the Private Key Locally
This saves the private key to a local file named Demo.pem, which you will use to SSH into the instance.
Security Group Configuration
This security group allows HTTP (port 80) and SSH (port 22) inbound traffic from anywhere and allows all outbound traffic.
EC2 Instance Provisioning
AMI: The Amazon Machine Image (AMI) used for the instance.
Instance Type: Uses t2.micro, which is free-tier eligible.
Key Name: Uses the previously created key pair.
Security Group: Attaches the Demo security group.
Public IP: Enables a public IP for external access.
User Data: Installs and starts Apache web server on boot.
Tags: Tags the instance as Demo.
Dependencies: Ensures key pair is created before the instance.
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.