Secure configuration of EC2 Security Groups
resource "aws_instance" "example" {
ami = "ami-0c94855ba95c574c8"
instance_type = "t2.micro"
# No security group is defined
}
In the above Terraform code, an AWS EC2 instance is being created without any security group associated with it. This is a major security vulnerability as it means that the instance is not protected by any firewall rules, allowing unrestricted access from the internet.
A Security Group acts as a virtual firewall for your instance to control inbound and outbound traffic. When you launch an instance in a VPC, you can assign up to five security groups to the instance. Security groups act at the instance level, not the subnet level. Therefore, each instance in a subnet in your VPC could be assigned to a different set of security groups.
In the provided code, there are no input/output rules defined for the EC2 instance, which means anyone can access the instance, making it vulnerable to various types of attacks such as DDoS attacks, Brute Force attacks, etc. This is a serious security concern and should be addressed immediately.
resource "aws_security_group" "example" {
name = "example"
description = "Example security group"
ingress {
from_port = 22
to_port = 22
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
egress {
from_port = 0
to_port = 0
protocol = "-1"
cidr_blocks = ["0.0.0.0/0"]
}
}
resource "aws_instance" "example" {
ami = "ami-0c94855ba95c574c8"
instance_type = "t2.micro"
vpc_security_group_ids = [aws_security_group.example.id]
}
The above code first defines a new AWS security group named "example". This security group has an inbound rule that allows TCP traffic on port 22 (SSH) from any IP address (0.0.0.0/0). The outbound rule allows all traffic to any IP address.
Then, the code updates the
aws_instance
resource to include the
vpc_security_group_ids
attribute. This attribute is set to the ID of the "example" security group. This means that the EC2 instance will now be associated with this security group, and all traffic to and from the instance will be subject to the rules defined in the security group.
This change ensures that the EC2 instance has a defined security group, and that the security group has explicit inbound and outbound rules. This reduces the risk of unauthorized access to the EC2 instance.