Security Groups in Code
Security Groups vs NACLs explained that security groups are stateful firewalls attached to network interfaces, and that the best rules reference other security groups instead of IP ranges: "the database accepts 5432 from the app tier", whatever the app's IPs are today. In code, that becomes a chain of three groups for a classic three-tier service:
internet ──443──▶ [alb] ──8080──▶ [app] ──5432──▶ [db]Groups and rules as separate resources
The AWS provider offers two styles. Inline ingress {}/egress {} blocks inside aws_security_group (shown in Dynamic Blocks) are compact, but all rules of a group are one attribute: any change rewrites the list, and a group can't reference another that references it back. The current recommendation is one resource per rule: aws_vpc_security_group_ingress_rule and aws_vpc_security_group_egress_rule. Each rule has its own address, can be added or removed alone, and can carry tags and a description.
mkdir sg && cd sg
cat > offline.tf <<'HCL'
provider "aws" {
region = "eu-west-1"
access_key = "offline"
secret_key = "offline"
skip_credentials_validation = true
skip_requesting_account_id = true
skip_metadata_api_check = true
}
HCL
cat > main.tf <<'HCL'
terraform {
required_providers {
aws = { source = "hashicorp/aws", version = "~> 6.0" }
}
}
variable "vpc_id" {
type = string
default = "vpc-0123456789abcdef0"
}
locals {
tiers = {
alb = "Load balancer: HTTPS from the internet"
app = "Application: traffic from the load balancer only"
db = "PostgreSQL: traffic from the application only"
}
}
resource "aws_security_group" "this" {
for_each = local.tiers
name = "linkly-${each.key}"
description = each.value
vpc_id = var.vpc_id
}
resource "aws_vpc_security_group_ingress_rule" "alb_https" {
security_group_id = aws_security_group.this["alb"].id
description = "HTTPS from anywhere"
cidr_ipv4 = "0.0.0.0/0"
ip_protocol = "tcp"
from_port = 443
to_port = 443
}
resource "aws_vpc_security_group_ingress_rule" "app_from_alb" {
security_group_id = aws_security_group.this["app"].id
description = "App port from the ALB"
referenced_security_group_id = aws_security_group.this["alb"].id
ip_protocol = "tcp"
from_port = 8080
to_port = 8080
}
resource "aws_vpc_security_group_ingress_rule" "db_from_app" {
security_group_id = aws_security_group.this["db"].id
description = "PostgreSQL from the app"
referenced_security_group_id = aws_security_group.this["app"].id
ip_protocol = "tcp"
from_port = 5432
to_port = 5432
}
# outbound: the ALB may only talk to the app, the app anywhere (APIs, the database)
resource "aws_vpc_security_group_egress_rule" "alb_to_app" {
security_group_id = aws_security_group.this["alb"].id
referenced_security_group_id = aws_security_group.this["app"].id
ip_protocol = "tcp"
from_port = 8080
to_port = 8080
}
resource "aws_vpc_security_group_egress_rule" "app_all" {
security_group_id = aws_security_group.this["app"].id
cidr_ipv4 = "0.0.0.0/0"
ip_protocol = "-1"
}
HCL
tofu init >/dev/null
tofu validate
tofu plan -out=tfplan | grep '^Plan:'
echo "--- the rules, as planned"
tofu show -json tfplan | jq -r '
.resource_changes[] | select(.type | test("rulequot;)) | .change.after
| [(.description // "-"), (.cidr_ipv4 // "sg:"), .ip_protocol, ((.from_port // "all") | tostring)] | @tsv'Success! The configuration is valid.
Plan: 8 to add, 0 to change, 0 to destroy.
--- the rules, as planned
- sg: tcp 8080
- 0.0.0.0/0 -1 all
HTTPS from anywhere 0.0.0.0/0 tcp 443
App port from the ALB sg: tcp 8080
PostgreSQL from the app sg: tcp 5432
The sg: rows are rules whose source is another security group: its id is only known after apply. The database group has no egress rule at all; security groups are stateful, so replies to allowed inbound connections go out anyway.
Note: When Terraform/OpenTofu creates an
aws_security_group, it removes AWS's default "allow all outbound" rule. Every egress you need must be declared. That is the safe default, and the reason the app tier above has an explicitapp_allrule.
Guard rails in tests
A security mistake in a security group is easy to write and easy to miss in review. Assert the rules you care about. This test file belongs next to the code above (it is run here with a mock provider, in a session of its own):
mkdir -p sg/tests && cd sg
cat > main.tf <<'HCL'
terraform {
required_providers {
aws = { source = "hashicorp/aws", version = "~> 6.0" }
}
}
variable "admin_cidrs" {
type = list(string)
default = []
}
resource "aws_security_group" "bastion" {
name = "bastion"
vpc_id = "vpc-0123456789abcdef0"
}
resource "aws_vpc_security_group_ingress_rule" "ssh" {
for_each = toset(var.admin_cidrs)
security_group_id = aws_security_group.bastion.id
cidr_ipv4 = each.value
ip_protocol = "tcp"
from_port = 22
to_port = 22
}
HCL
cat > tests/no_open_ssh.tftest.hcl <<'HCL'
mock_provider "aws" {}
run "office_only" {
command = plan
variables {
admin_cidrs = ["203.0.113.0/24"]
}
assert {
condition = alltrue([for r in aws_vpc_security_group_ingress_rule.ssh : r.cidr_ipv4 != "0.0.0.0/0"])
error_message = "SSH must never be open to the internet"
}
}
run "someone_opens_ssh_to_the_world" {
command = plan
variables {
admin_cidrs = ["203.0.113.0/24", "0.0.0.0/0"]
}
assert {
condition = alltrue([for r in aws_vpc_security_group_ingress_rule.ssh : r.cidr_ipv4 != "0.0.0.0/0"])
error_message = "SSH must never be open to the internet"
}
}
HCL
tofu init >/dev/null
tofu test 2>&1 | grep -E 'run "|must never|passed' run "office_only"... pass
run "someone_opens_ssh_to_the_world"... fail
on tests/no_open_ssh.tftest.hcl line 20, in run "someone_opens_ssh_to_the_world":
SSH must never be open to the internet
Failure! 1 passed, 1 failed.
The second run shows what CI would print on a pull request that opens SSH to the world. Better still, put such a rule into the module as a validation on admin_cidrs, so it fails for every caller, and use policy-as-code tools (Checkov, tfsec's successor Trivy, OPA/Conftest on show -json) across all repositories (Toolkit). And prefer no SSH at all: AWS Systems Manager Session Manager gives shell access without an open port.
Test yourself
Why prefer aws_vpc_security_group_ingress_rule resources over inline ingress blocks?
- Inline blocks are not supported in provider 6
- Each rule has its own address, so rules can be added, removed and referenced individually without rewriting the group
- They are cheaper
- They work without a VPC
How does the db security group allow only the app tier?
cidr_ipv4with the app's IPsreferenced_security_group_idpointing at the app's security group- A NACL
- Tags
What happens to AWS's default allow-all egress rule when Terraform/OpenTofu creates a security group?
- It is kept
- It is removed; declare every egress rule you need
- It becomes deny-all ingress
- It moves to the NACL