Is there a way to manage AWS security Groups in Terraform to edit rules for an existing SG?
e.g: If I provision a new instance the ingress rules of an existing SG is updated to allow the newly provisioned instance. The SG also needs to update when an instance terminates.
Feel free to suggest other common practices if not directly supported via Terraform.
Yes, you can add and remove individual rules to existing security groups (SGs). This can be done in two steps:
data "aws_security_group" "selected" {
id = <group-id-of-existing-sg>
}
resource "aws_security_group_rule" "example" {
type = "ingress"
from_port = 0
to_port = 65535
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
security_group_id = data.aws_security_group.selected.id
}
If your instance is created in same TF file as the SG rule, upon terraform destroy
both the instance and the rule will get destroyed.