CodexBloom - Programming Q&A Platform

Terraform - implementing AWS Security Group Rules Not Applying Based on Subnet Tags

πŸ‘€ Views: 284 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-15
terraform aws security-group subnets HCL

I need some guidance on I'm stuck trying to I'm sure I'm missing something obvious here, but I'm working with a question where my Terraform configuration isn't applying security group rules based on the tags assigned to subnets... I'm using Terraform version 1.4.0 along with the AWS provider version 4.0.0. My goal is to attach security group rules to certain subnets which are tagged with specific keys, but it seems that the rules aren't being created as expected. Here’s a snippet of what I have: ```hcl variable "subnet_tag_key" { default = "environment" } data "aws_subnet_ids" "private_subnets" { tags = {"${var.subnet_tag_key}" = "production"} } resource "aws_security_group" "app_sg" { name = "app_security_group" description = "Security group for the app" vpc_id = aws_vpc.main.id } resource "aws_security_group_rule" "allow_http" { type = "ingress" from_port = 80 to_port = 80 protocol = "tcp" cidr_blocks = data.aws_subnet_ids.private_subnets.ids security_group_id = aws_security_group.app_sg.id } ``` When I run `terraform apply`, I expect the security group rule to be applied to the security group based on the subnet tags, but I'm receiving the following behavior: ``` behavior: Invalid CIDR range on main.tf line 12, in resource "aws_security_group_rule" "allow_http": 12: cidr_blocks = data.aws_subnet_ids.private_subnets.ids Invalid value for "cidr_blocks": must be a valid CIDR range or a list of valid CIDR ranges. ``` I've tried modifying the way I reference the subnet IDs and even looked into using a module to manage my network resources, but the scenario continues. I suspect it might be related to how I'm retrieving the subnet IDs or how the cidr_blocks attribute is being populated. Could anyone provide insights on how to resolve this or suggest a better approach to dynamically add security group rules based on subnet tags? I'd really appreciate any guidance on this. Thanks, I really appreciate it! I'm working with Hcl in a Docker container on macOS. I'd really appreciate any guidance on this. This issue appeared after updating to Hcl 3.9. Am I missing something obvious?