CodexBloom - Programming Q&A Platform

Terraform with AWS: Issues Updating Security Groups Based on Dynamic Subnet Changes

πŸ‘€ Views: 47 πŸ’¬ Answers: 1 πŸ“… Created: 2025-07-23
terraform aws security-groups hcl

I'm attempting to set up I'm migrating some code and I'm collaborating on a project where Quick question that's been bugging me - I'm working with a question while trying to dynamically update security groups in Terraform based on changes to my subnets... My goal is to allow specific inbound traffic only from the subnets defined in a variable. However, when I apply my changes, Terraform always seems to create new security group rules instead of updating the existing ones. Here's the relevant snippet of my Terraform configuration: ```hcl variable "subnet_ids" { type = list(string) } resource "aws_security_group" "example" { name = "example-sg" description = "Example security group" ingress { from_port = 80 to_port = 80 protocol = "tcp" cidr_blocks = [for subnet_id in var.subnet_ids : aws_subnet.example[subnet_id].cidr_block] } } ``` In my main configuration file, I'm passing the subnet IDs like this: ```hcl module "network" { source = "./network" subnet_ids = ["subnet-12345678", "subnet-87654321"] } ``` However, whenever I change the subnet IDs in my `subnet_ids` variable and run `terraform apply`, I see the following plan output: ``` + aws_security_group_rule.example_egress ... + aws_security_group_rule.example_ingress ... ``` I expected Terraform to recognize that the existing rules needed to be updated instead of creating new ones. After checking the Terraform state, it seems that it’s treating the ingress rules as completely new resources. I’ve tried using the `lifecycle` block with `prevent_destroy` but that didn't resolve the scenario. Does anyone have insights on how to properly manage dynamic security group rules so that Terraform updates existing rules instead of creating duplicates? Any help would be greatly appreciated! This is part of a larger CLI tool I'm building. I appreciate any insights! I'm working on a desktop app that needs to handle this. Any ideas how to fix this? The project is a application built with Hcl. Any pointers in the right direction?