Sub topic 12
Managing rules with the AWS CLI and Terraform
This chapter assumes you can run AWS CLI commands, know CIDR notation, ports and protocols, and understand that a security group is an allow-only, stateful filter attached to network interfaces in a VPC. It covers how to create, inspect, change and remove rules from the command line, and how to declare the same rules in Terraform so they stay reviewable and repeatable.
Why manage rules as commands or code
The console is fine for learning. It is a poor record of what you did. A command or a Terraform file can be reviewed, repeated in another account, and compared against what is deployed. The CLI suits quick inspection and one-off fixes. Terraform suits anything you expect to keep.
Both tools act on the same objects. A security group has an ID such as sg-0123456789abcdef0. Each rule inside it has its own rule ID such as sgr-0abc.... Direction, protocol, port range and source or destination are the parts of a rule you already know. Every command below sets some of those parts.
Creating a group and a first rule with the CLI
Creating a group takes a name, a description and the VPC it belongs to. The name must be unique within the VPC.
aws ec2 create-security-group \
--group-name web-sg \
--description "Web tier" \
--vpc-id vpc-0123456789abcdef0
aws ec2 authorize-security-group-ingress \
--group-id sg-0123456789abcdef0 \
--protocol tcp \
--port 443 \
--cidr 0.0.0.0/0The first command returns the new group ID. Use that ID in the second command. If you omit --vpc-id, AWS tries to use the default VPC. That can put the group in the wrong place, so pass it explicitly.
The second command adds one inbound rule: TCP 443 from any IPv4 address. Notice that you never state "allow". Every rule is an allow rule, and the command name authorize reflects that. There is no deny option to pass.
A newly created group has no inbound rules and one outbound rule that allows all traffic. Inbound traffic is blocked until you authorize something.
Referencing another group as the source
In a tiered design, the application tier should accept traffic only from the web tier. Instead of listing IP ranges, name the web tier's group as the source.
aws ec2 authorize-security-group-ingress \
--group-id sg-0aaaaaaaaaaaaaaaa \
--protocol tcp \
--port 8080 \
--source-group sg-0123456789abcdef0This allows TCP 8080 into the application group from any instance that has the web group attached. The source is not the web group's rules or its addresses. It is membership. When the web tier scales out and new instances join the group, they are allowed automatically. Nothing needs editing.
Adding a description with `--ip-permissions`
The shorthand flags --protocol, --port and --cidr cannot set a description. For that, use --ip-permissions, which takes the full rule structure.
aws ec2 authorize-security-group-ingress \
--group-id sg-0123456789abcdef0 \
--ip-permissions 'IpProtocol=tcp,FromPort=22,ToPort=22,IpRanges=[{CidrIp=203.0.113.25/32,Description="Admin workstation"}]'This allows SSH from one administrator address. The /32 mask means exactly one IPv4 address. The description is stored on the rule and shows up in listings, so a reviewer a year from now can see why port 22 is open.
A few points about this syntax:
FromPortandToPortdefine a range. For a single port, set both to the same number.- Use single quotes around the whole value so the shell does not interpret the brackets or inner double quotes.
- IPv6 sources use
Ipv6Ranges=[{CidrIpv6=...}]instead ofIpRanges. - Prefix list sources use
PrefixListIds=[{PrefixListId=pl-...}]. - For all protocols, use
IpProtocol=-1. Port values are then ignored, so omit them.
Outbound rules
Outbound rules use the matching authorize-security-group-egress command. The parameters are the same, but the source becomes a destination.
aws ec2 authorize-security-group-egress \
--group-id sg-0aaaaaaaaaaaaaaaa \
--ip-permissions 'IpProtocol=tcp,FromPort=5432,ToPort=5432,UserIdGroupPairs=[{GroupId=sg-0bbbbbbbbbbbbbbbb,Description="To database tier"}]'This is useful when you want to replace the default allow-all outbound rule with something tighter. Remember that revoking the default outbound rule blocks all new outbound connections until you add replacements. Responses to inbound connections still work because the filtering is stateful.
Inspecting rules
To see what a group currently allows, describe it.
aws ec2 describe-security-groups --group-ids sg-0123456789abcdef0The output is JSON. Inbound rules appear under IpPermissions and outbound rules under IpPermissionsEgress. This view groups rules by protocol and port, so several sources may be listed together inside one entry.
To work with individual rules, use describe-security-group-rules. It returns one record per rule, with a SecurityGroupRuleId, which you need for modifying or revoking by ID.
aws ec2 describe-security-group-rules \
--filters Name=group-id,Values=sg-0123456789abcdef0 \
--query 'SecurityGroupRules[].{Id:SecurityGroupRuleId,Egress:IsEgress,Proto:IpProtocol,From:FromPort,To:ToPort,Cidr:CidrIpv4,Desc:Description}' \
--output tableThe --query option uses JMESPath to select only the fields you care about. A table is much easier to read than the full JSON when you are checking a group.
Removing rules
Revoking a rule means describing it again. You pass the same protocol, port and source that created it.
aws ec2 describe-security-groups --group-ids sg-0123456789abcdef0
aws ec2 revoke-security-group-ingress \
--group-id sg-0123456789abcdef0 \
--protocol tcp \
--port 443 \
--cidr 0.0.0.0/0If the details do not match an existing rule exactly, nothing is removed. A common mistake is trying to revoke port 443 from 10.0.0.0/8 when the rule was created from 0.0.0.0/0.
You can also revoke by rule ID, which avoids matching errors.
aws ec2 revoke-security-group-ingress \
--group-id sg-0123456789abcdef0 \
--security-group-rule-ids sgr-0123456789abcdef0Changing an existing rule's description, port range or source in place is possible with modify-security-group-rules, which takes the rule ID and the new rule values. For a rule that changes meaning, such as moving from one source to another, revoking and re-adding is clearer.
Deleting a group
aws ec2 delete-security-group --group-id sg-... removes a group. It fails while the group is attached to any network interface, or while another group's rule references it. Remove those references first. Default groups cannot be deleted.
The same group in Terraform
Terraform declares the desired state, and terraform apply makes AWS match it. The group and each rule are separate resources.
resource "aws_security_group" "web" {
name = "web-sg"
description = "Web tier"
vpc_id = var.vpc_id
}
resource "aws_vpc_security_group_ingress_rule" "https" {
security_group_id = aws_security_group.web.id
cidr_ipv4 = "0.0.0.0/0"
ip_protocol = "tcp"
from_port = 443
to_port = 443
description = "HTTPS from anywhere"
}Using one resource per rule means each rule has its own lifecycle. Changing the HTTPS rule does not touch the SSH rule. Plans are easier to read, because a diff shows exactly which rule is added or removed.
For a reference to another group, use referenced_security_group_id in place of cidr_ipv4. For an outbound rule, use aws_vpc_security_group_egress_rule.
Inline rules versus rule resources
The aws_security_group resource also accepts inline ingress and egress blocks. Do not mix inline blocks with separate rule resources for the same group. Terraform treats inline blocks as the complete list of rules, so it will try to remove rules that the separate resources created, and the two will fight on every apply.
Choose one style per group. The separate rule resources are the better default, for the reasons above.
Terraform removes the default egress rule
When AWS creates a group, it adds an allow-all outbound rule. When Terraform creates a group with no egress declared, it removes that rule. Instances then cannot make outbound connections. If your instances need to reach the internet, package repositories or other tiers, declare the egress rules you need.
resource "aws_vpc_security_group_egress_rule" "all_out" {
security_group_id = aws_security_group.web.id
cidr_ipv4 = "0.0.0.0/0"
ip_protocol = "-1"
description = "Allow all outbound"
}Common errors
| Error or symptom | Likely cause | Fix |
|---|---|---|
| `InvalidPermission.Duplicate` | The same rule already exists | Describe the group and skip or change the rule |
| `InvalidGroup.NotFound` | Wrong group ID, region or profile | Check `--region` and `--profile` |
| `DependencyViolation` on delete | Group is attached or referenced | Detach it and remove references |
| `RulesPerSecurityGroupLimitExceeded` | Quota reached | Consolidate with prefix lists or request a quota increase |
| Revoke succeeds but nothing changes | Details did not match a rule | Use `--security-group-rule-ids` |
| Terraform shows constant drift | Inline blocks mixed with rule resources | Use one style only |
Habits that keep rule sets safe
- Put a description on every rule, especially administrative ones.
- Review
describe-security-group-rulesoutput before and after a change. - Run
terraform planand read it before every apply. Look for rules marked for destruction. - Prefer a
/32address or a group reference over a wide CIDR for management ports.
Exercise
You run aws ec2 revoke-security-group-ingress --group-id sg-0123456789abcdef0 --protocol tcp --port 443 --cidr 10.0.0.0/8, but the HTTPS rule was created with 0.0.0.0/0. What happens, and what is a safer way to remove the right rule?
Show answer
The command does not remove the 0.0.0.0/0 rule, because the protocol, port and source must match an existing rule exactly. Run describe-security-group-rules to find the rule's SecurityGroupRuleId, then call revoke-security-group-ingress with --security-group-rule-ids and that ID.
Exercise
A Terraform configuration defines an aws_security_group with an inline ingress block and also an aws_vpc_security_group_ingress_rule for the same group. What goes wrong, and how do you fix it?
Show answer
Terraform treats the inline block as the full rule list, so it tries to remove the separately managed rule and the two keep conflicting on each apply. Choose one style. The recommended fix is to delete the inline blocks and manage every rule with separate rule resources.