Yes, you can apply multiple security groups to an EC2 instance. Rules from all applied security groups are aggregated to determine the allowed traffic.
Example Code
Here’s an example of creating an AWS Security Group using AWS CLI:
# Create a new security group
aws ec2 create-security-group --group-name MySecurityGroup --description "My Security Group"
# Add an inbound rule to allow SSH access from a specific IP range
aws ec2 authorize-security-group-ingress --group-name MySecurityGroup --protocol tcp --port 22 --cidr 203.0.113.0/24
This script first creates a new security group named "MySecurityGroup" with a description. Then, it adds an inbound rule to allow SSH (port 22) traffic from the IP range 203.0.113.0/24.