Search code examples
amazon-web-servicesterraformterraform-provider-awsaws-security-group

How to append or delete the ingress/egress rule for a security group using Terraform?


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.


Solution

  • Yes, you can add and remove individual rules to existing security groups (SGs). This can be done in two steps:

    1. Get data source for an existing SG using aws_security_group:
    data "aws_security_group" "selected" {
      id = <group-id-of-existing-sg>
    }
    
    1. Create aws_security_group_rule resource to add a new rule to the SG from step 1:
    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.