What is AWS EC2 Security Group?
An EC2 (Elastic Compute Cloud) Security Group acts as a virtual firewall for controlling inbound and outbound traffic to EC2 instances. It works by allowing you to define rules that dictate which traffic is allowed to reach your instances and which traffic should be blocked.
EC2 Security Group Characteristics
Defining Rules: Security groups are defined by inbound and outbound rules. Each rule allows traffic based on a combination of the following parameters:
Protocol (TCP, UDP, ICMP, etc.)
Port range (e.g., specific port or a range of ports)
Source or destination IP addresses or CIDR blocks (e.g., specific IP, IP range, or "0.0.0.0/0" for all IPs)
Default Security Group: When you launch an EC2 instance without specifying a security group, AWS automatically assigns a default security group to that instance. The default security group is configured to allow all outbound traffic and deny all inbound traffic by default.
Stateful: Security groups are stateful, which means that if you allow inbound traffic for a specific protocol and port, the corresponding outbound traffic for the same protocol and port is automatically allowed. You don't need to create a separate outbound rule for the response traffic.
Regin Specific: Security Groups are locked down to a region/VPC combination.
SGs live outside the EC2 - if traffic is blocked the EC2 instance will not see it.
Grouping Instances: Each EC2 instance must be associated with one or more security groups. A security group can be associated with multiple instances, and multiple security groups can be assigned to a single instance.
Order of Rules: Rules are evaluated in the order they are defined. If there are conflicting rules (e.g., one rule allows traffic, and another denies it), the "allow" rule takes precedence.
Dynamic Updates: You can modify the security group rules at any time. Changes take effect immediately and are automatically applied to all associated instances.
Hands-on Lab Overview
In this hands-on lab, we are going to create a security group for EC2 instances using AWS Management Console, AWS CLI, and AWS SDK;
Hands-on Lab
Create EC2 SG using AWS Console:
Open the Amazon VPC console at https://console.aws.amazon.com/vpc/.
In the navigation pane, choose Security groups.
Choose Create security group.
Enter a name and description for the security group. You cannot change the name and description of a security group after it is created.
From VPC, choose the VPC.
You can add security group rules now, or you can add them later.
You can add tags now, or you can add them later.
Choose Create security group.
Create EC2 SG using AWS CLI
It is assumed that AWS CLI is configured with aws configure
command.
- To create a security group without any rules defined, enter the command:
aws ec2 create-security-group \
--group-name "ftp-sg" \
--description "Rules for FTP traffic"
Note down the security group ID from the output. The output would look like the following:
- Check whether the SG "ftp-sg" was created via AWS Console:
- Next, use the
authorize-security-group-ingress
andauthorize-security-group-egress
commands to add inbound and outbound rules, respectively, to an existing security group in Amazon EC2.
aws ec2 authorize-security-group-ingress \
--group-id "sg-0a2ac365fe2cb4c8a" \
--ip-permissions "IpProtocol=tcp,FromPort=21,ToPort=80,IpRanges=[{CidrIp=0.0.0.0/0},{CidrIp=10.0.0.0/24}]"
We added an inbound rule to the specified security group that allows TCP traffic on port 21 from both the public internet and a specific private IP range (10.0.0.0/24). This is useful if you want to allow FTP connections from both the internet and your private network to instances in the security group. However, be cautious when opening up security groups to the public internet, and only allow the minimum necessary access for your specific use case.
Create EC2 SG using AWS SDK
To create an AWS EC2 security group using the AWS SDK for Node.js (AWS SDK for JavaScript), follow these steps:
Load the AWS SDK for Node.js:
const AWS = require("aws-sdk");
Load credentials and set region:
Configure your AWS credentials by setting the access key ID and secret access key. You can do this using the
AWS.config
object:AWS.config.update({ accessKeyId: "xxx", secretAccessKey: "xxx", region: "us-east-1" })
Create an EC2 service object
const ec2 = new AWS.EC2({apiVersion: '2016-11-15'});
Create a variable to hold an ID of a VPC
let vpc = null;
Retrieve the ID of a VPC and create a Security Group with inbound rules:
ec2.describeVpcs(function(err, data) { if(err) { console.log("Cannot retrieve a VPC", err); } else { vpc = data.Vpcs[0].VpcId; // Define Security Group parameters: const securityGroupParams = { Description: "SG for SSH and HTTP traffic", GroupName: "ssh-http-sg", VpcId: vpc } // Create Security Group ec2.createSecurityGroup(securityGroupParams, (err, data) => { if(err) { console.log("Error creating security group: ", err); } else { const SecurityGroupId = data.GroupId; console.log("Security Group created with ID: ", SecurityGroupId); // Define Security Group Rules: const paramsIngress = { GroupId: SecurityGroupId, IpPermissions: [ { IpProtocol: "tcp", FromPort: 22, ToPort: 22, IpRanges: [{CidrIp: "10.0.0.0/24"}] }, { IpProtocol: "tcp", FromPort: 80, ToPort: 80, IpRanges: [{CidrIp: "10.0.0.0/24"}] }] }; // Add inbound rules ec2.authorizeSecurityGroupIngress(paramsIngress, (err, data) => { if(err) { console.log("Error adding inbound rules: ", err); } else { console.log("Inbound rules added to the security group successfully!", data); } }); } }); } });
The output:
Check via AWS Console whether the SG and its rules were added: