# AWS Security Groups

> A security group is a stateful virtual firewall that controls the inbound and outbound traffic of AWS resources such as EC2 instances and databases.

- Source: https://www.itwonderlab.com/aws-security-groups/
- Published: 2026-10-05
- Updated: 2026-10-05
- Author: Javier Ruiz Jiménez (https://www.javierruizjimenez.com/)
- Site: IT Wonder Lab (https://www.itwonderlab.com/)

---

A **security group** acts as a virtual firewall for the resources of a [VPC](https://www.itwonderlab.com/aws-vpc/): [EC2](https://www.itwonderlab.com/aws-ec2/) instances, [RDS](https://www.itwonderlab.com/aws-rds/) databases, [load balancers](https://www.itwonderlab.com/aws-elastic-load-balancing/), [EKS](https://www.itwonderlab.com/aws-eks/) nodes and more. It is a set of rules that allow traffic by protocol, port and origin or destination.

### Key concepts

- **Allow rules only**: there are no deny rules. Whatever is not allowed is denied.
- **Stateful**: when a request is allowed in, the response is allowed out automatically, and the other way around.
- **Inbound rules** are empty by default (all denied). A security group created in the console allows all **outbound** traffic by default, but one created with Terraform has no outbound rules until they are defined.
- **Sources and destinations** can be an IP range (CIDR), a prefix list or **another security group**. Referencing a security group, for example "the back-end can reach the database on port 3306", keeps working when the IP addresses change.
- A resource can have several security groups: the rules of all of them are combined.
- Security groups are bound to a VPC, not to a subnet. To filter at subnet level, see [Network ACLs](https://www.itwonderlab.com/aws-network-acl/).

### Pricing

Security groups are free.

### With Terraform

The resources are `aws_security_group` and the rule resources `aws_vpc_security_group_ingress_rule`, `aws_vpc_security_group_egress_rule` or `aws_security_group_rule`. Avoid mixing in-line rules with separate rule resources for the same group.

```hcl
resource "aws_security_group" "web" {
  name        = "web"
  vpc_id      = aws_vpc.main.id
  description = "Web server"
}

resource "aws_vpc_security_group_ingress_rule" "https" {
  security_group_id = aws_security_group.web.id
  ip_protocol       = "tcp"
  from_port         = 443
  to_port           = 443
  cidr_ipv4         = "0.0.0.0/0"
}
```

See tutorials:

-   [AWS with Terraform: The Essential Guide (9/21) – AWS Security Groups](https://www.itwonderlab.com/aws-terraform-tutorial-aws-security-groups/)
-   [AWS Security Groups’ Best Practices](https://www.itwonderlab.com/aws-security-groups-best-practices/)
-   [Creating AWS EC2 Instances and Security Rules with Terraform (5/5)](https://www.itwonderlab.com/terraform-aws-ec2-security-rules/)
