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:

  1. An AWS account.

  2. Terraform installed on your system.

  3. AWS CLI configured with appropriate credentials.

Terraform Script Breakdown

Below is the Terraform script used to create an EC2 instance and security group:

  1. Provider Configuration

Image description

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.

Image description

Creating an AWS Key Pair
Terraform creates an AWS key pair using the public key from the RSA key.

Image description

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.

Image description

Security Group Configuration

Image description

This security group allows HTTP (port 80) and SSH (port 22) inbound traffic from anywhere and allows all outbound traffic.

EC2 Instance Provisioning

Image description

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:

  1. Initialize Terraform (downloads required provider plugins):

Image description

  1. Preview the execution plan:

Image description

  1. Apply the configuration (creates resources in AWS):

Image description

4. Verify the Instance:

Image description

  • Copy the public IP from the output or AWS Console.

Image description

Destroying the Infrastructure

To delete the created resources and avoid charges, run:

Image description

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.