Querying aws_default_security_group ID without creating?

I would like to query and print the ID of the default security group but when I apply the following code, it indicates that it wishes to make a change to the default security group

I was hoping to be able to query default security group like I query default VPC

=======================================
variable “availability_zone_names” {
type = list(string)
default = [“ca-central-1a”,“ca-central-1b”]
}

provider “aws” {
region = “ca-central-1”
}

data “aws_vpc” “default” {
default = true
}

resource “aws_default_security_group” “default” {
vpc_id = data.aws_vpc.default.id
}

data “aws_subnet” “default” {
vpc_id = data.aws_vpc.default.id
default_for_az = true
availability_zone = var.availability_zone_names[0]
}

output “aws_vpc_id” {
value = data.aws_vpc.default.id
}

output “aws_subnet_vpc_id” {
value = data.aws_subnet.default.id
}

output “aws_security_group_id” {
value = aws_default_security_group.default.id
}

Hi @nyue,

The general rule here is that resource blocks tell Terraform to manage something, while data blocks tell Terraform to retrieve information about an existing object managed by some other system.

With that said, to get the result you wanted here means we need to find a way to describe the query “what is the default security group for this given VPC?” as a data block.

There doesn’t seem to be an aws_default_security_group data source defined in the provider, but there is aws_security_group, which can retrieve information about a particular existing security group based on a given set of constraints.

I don’t see a first-class attribute for selecting a default security group there, but the data source accepts filter blocks that apparently expose the filtering capabilities of the underlying EC2 action DescribeSecurityGroups.

I don’t see any filter there specifically for default security groups, but the EC2 documentation on default security groups says that a default security group is always called “default”, so perhaps filtering by the security group name would be sufficient, unless you plan to have other security groups in the same VPC also called “default”:

data "aws_security_group" "selected" {
  vpc_id = data.aws_vpc.default.id

  filter {
    name   = "group-name"
    values = ["default"]
  }
}

As far as I can tell, there’s no explicit API action in the underlying EC2 API for finding the default security group for a VPC. Out of curiousity I took a look in the AWS provider code to see how the aws_default_security_group resource type finds it, and indeed it’s doing the same filtering by name. I think this is safe because user-defined VPC security groups never have names in this sense; they might have a Name tag set, but that’s a separate idea that this filter would not match.