Strengthening Infrastructure Security with Terraform, AWS EC2, and SSH Access ๐ก๏ธ
Advancing DevOps Practices
Introduction:
In the ever-evolving landscape of DevOps, the path to infrastructure automation is a constant journey of improvement. In this blog post, we'll build upon our earlier guide for provisioning an AWS EC2 instance using Terraform. This time, our focus shifts to fortifying security by setting up a custom security group that allows SSH inbound traffic. We'll explore how to achieve both efficiency and robust networking controls.
Prerequisites:
AWS CLI installed on your local machine.
Terraform installed on your local machine.
An AWS account with the necessary permissions.
Step 1: Configure AWS CLI Securely ๐ก๏ธ:
Begin by securing your AWS CLI on your local machine. Open your terminal and run:
aws configure
Enter your AWS Access Key ID, Secret Access Key, default region, and output format as prompted.
Step 2: Terraform Configuration ๐:
Update your Terraform configuration (main.tf
) to include the new security group feature:
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "3.63.0"
}
}
}
resource "aws_security_group" "allow_ssh" {
name = "allow_ssh"
description = "Allow SSH inbound traffic"
ingress {
from_port = 22
to_port = 22
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"] # Open to all sources. Adjust as needed.
}
}
resource "aws_instance" "example_server" {
#count = 4
ami = "ami-0c7217cdde317cfec"
instance_type = "t2.micro"
key_name = "jenkins"
vpc_security_group_ids = [aws_security_group.allow_ssh.id]
tags = {
Name = "terraform-ec2"
}
}
output "instance_public_ip" {
description = "Public IP address of the created EC2 instance"
value = aws_instance.example_server.public_ip
#value = aws_instance.example_server[*].public_ip
}
Step 3: Initialize, Apply, and Destroy Terraform ๐:
Run the following commands to initialize and apply the Terraform configuration:
terraform init
terraform apply
To safely destroy the infrastructure when it's no longer needed, run:
terraform destroy
Enter 'yes' when prompted. Terraform will then gracefully tear down the resources.
Step 4: Connect to Your EC2 Instance ๐:
After the deployment is complete, connect to your EC2 instance using the private key:
ssh -i ~/.ssh/jenkins ec2-user@<public_ip_of_your_instance>
Conclusion:
By extending our Terraform configuration to include a custom security group allowing SSH traffic, we've fortified our infrastructure with an extra layer of protection. This step not only streamlines the deployment of EC2 instances but also exemplifies a commitment to security best practices.
As you continue your DevOps journey, consider further enhancements, such as fine-tuning security group rules, exploring additional AWS features, and optimizing your Terraform modules. The combination of Terraform and AWS empowers you to build a resilient and secure infrastructure seamlessly.
Happy automating! ๐โจ