AWS Security Group Terraform module
Terraform module which creates EC2 security group within VPC on AWS.
Usage
Root module
module "security_group" {
source = "terraform-aws-modules/security-group/aws"
name = "example"
description = "Example security group"
vpc_id = "vpc-12345678"
ingress_rules = {
https = {
from_port = 443
ip_protocol = "tcp"
cidr_ipv4 = "10.0.0.0/16"
description = "HTTPS from internal"
}
self-all = {
ip_protocol = "-1"
referenced_security_group_id = "self"
description = "All traffic from members of this SG"
}
}
egress_rules = {
all = {
ip_protocol = "-1"
cidr_ipv4 = "0.0.0.0/0"
}
}
tags = {
Environment = "dev"
}
}
Preset submodule
Each preset submodule under modules/ ships a curated set of ingress rules for a specific service (PostgreSQL, Consul, Cassandra, etc.). Use one when a security group serves a single service.
module "postgresql_security_group" {
source = "terraform-aws-modules/security-group/aws//modules/postgresql"
name = "postgresql"
description = "PostgreSQL access"
vpc_id = "vpc-12345678"
ingress_cidr_ipv4 = {
vpc = "10.0.0.0/16"
peer = "172.16.0.0/12"
}
}
Examples
- Complete - Comprehensive example demonstrating the full module surface
Notes
Referencing the security group itself
To allow traffic between members of the security group created by this module, set referenced_security_group_id = "self" on the rule. The sentinel is rewritten to the security group's own id at apply time:
ingress_rules = {
self-all = {
ip_protocol = "-1"
referenced_security_group_id = "self"
description = "All traffic from members of this SG"
}
}
use_name_prefix and the create-before-destroy lifecycle
The security group resource sets lifecycle { create_before_destroy = true } so replacements happen without dropping traffic. When use_name_prefix = false (i.e. you pin a static name), any change that forces replacement will fail because AWS cannot create a second security group with the same name in the same VPC. Either:
- keep
use_name_prefix = true(default), or - change
namealong with the replacement.
Authors
Module is maintained by Anton Babenko with help from these awesome contributors.
License
Apache 2 Licensed. See LICENSE for full details.
Additional information for users from Russia and Belarus
- Russia has illegally annexed Crimea in 2014 and brought the war in Donbas followed by full-scale invasion of Ukraine in 2022.
- Russia has brought sorrow and devastations to millions of Ukrainians, killed hundreds of innocent people, damaged thousands of buildings, and forced several million people to flee.
- Putin khuylo!