Search code examples
amazon-web-servicesterraforminfrastructure-as-code

AWS with Terraform - security groups argument inside a security group rule


When you look at terraform's docs for security group, you can see that there is an option to define a security_groups argument inside the ingress/egress security rules.

It seems quite strange to me, but maybe I'm missing something here.

I saw this post but there are no real world use cases mentioned.

My question is: In which cases we'll want to use this kind of configuration?


Solution

  • You can use this syntax to apply those ingress/egress rules to any infrastructure that belongs to a particular security group.

    This Terraform code, for example:

    ingress {
        from_port = "80"
        to_port   = "80"
        protocol  = "tcp"
    
        security_groups = [
          "${aws_security_group.elb_sg.id}",
        ]
    }
    

    will allow HTTP access to any infrastructure that belongs to the elb_sg security group. This is helpful if you've got a large amount of infrastructure that needs to have the ingress/egress access and don't want to name all of the parts individually.

    Another example: you could create a security group for an Elastic Search cluster, and then state that all elements of an EC2 app server security group should have ingress/egress access to that cluster by using this syntax.