Search code examples
amazon-web-servicesterraformterraform-provider-awsamazon-vpc

Terraform VPC and default security group issue


I am trying to create VPC suing Terraform. Here is my script

resource "aws_vpc" "my_vpc" {
      cidr_block = "10.10.0.0/24"
      instance_tenancy = "default"
      tags = {
        "Name" = "my-vpc-${var.environment}"
      }
}

VPC was created successfully and also default security group was created for above VPC. I did not add any block for security group so I assume security group was created by default similar to when vpc is created from console.

Default security group has one inbound and one outbound rule. My requirement is too remove default inbound rule and add two custom inbound rule to default VPC.

Question:

  1. Should I create new security group and add custom rules or use default security group? what is best practice?
  2. If I want to use default inbound rule, how do I remove it and add two new rules in Terraform. I have tried use block aws_default_security_group
resource "aws_default_security_group" "default" {
    vpc_id = aws_vpc.shared_services_vpc.id
    
    ingress = [ {
      cidr_blocks = [ "<Cidr>","Cidr"]
      description = "Allowed security rules"
      from_port = 22
      ipv6_cidr_blocks = []
      prefix_list_ids = []
      protocol = "tcp"
      security_groups = [ aws_vpc.my_vpc.default_security_group_id ]
      self = false
      to_port = 22
    } ]
    
    egress = [ {
      cidr_blocks = [ "0.0.0.0/0" ]
      description = "AllowAll"
      from_port = 0
      ipv6_cidr_blocks = []
      prefix_list_ids = []
      protocol = "all"
      security_groups = [ aws_vpc.my_vpc.default_security_group_id ]
      self = false
      to_port = 0
    } ]
}

Solution

  • You can change the default security group. But as Ervin mentioned, it is best to leave it as it is and create a new security group for your use instead. However, if for some reason you want to change the default security group, you can do so using aws_default_security_group resource which you are trying. Answer to your second question is present in the terraform documentation page itself:

    "When Terraform first begins managing the default security group, it immediately removes all ingress and egress rules in the Security Group. It then creates any rules specified in the configuration. This way only the rules specified in the configuration are created." Source: https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/default_security_group

    So you need not remove anything separately, terraform itself removes the old default rules and adds rules that you declare in aws_default_security_group resource.