Terraform: scenarios When Trying to Use `count` with `for_each` on AWS Security Groups
I've been struggling with this for a few days now and could really use some help... I'm attempting to create multiple AWS Security Groups using Terraform and I'm running into issues when trying to combine the `count` and `for_each` meta-arguments. I want to dynamically create security groups based on a list of environment names, but I'm getting the following behavior: ``` behavior: Invalid count argument on main.tf line 15, in resource "aws_security_group" "example": 15: count = length(var.env_names) The "count" argument must be used with a single resource or module. ``` My `main.tf` looks something like this: ```hcl variable "env_names" { description = "List of environment names" type = list(string) default = ["dev", "staging", "prod"] } resource "aws_security_group" "example" { count = length(var.env_names) name = "${var.env_names[count.index]}-sg" vpc_id = var.vpc_id ingress { from_port = 80 to_port = 80 protocol = "tcp" cidr_blocks = ["0.0.0.0/0"] } } ``` However, I have read that `for_each` is more appropriate for this use case because it allows me to index directly into a map or set. So I attempted switching to `for_each` as follows: ```hcl resource "aws_security_group" "example" { for_each = toset(var.env_names) name = "${each.key}-sg" vpc_id = var.vpc_id ingress { from_port = 80 to_port = 80 protocol = "tcp" cidr_blocks = ["0.0.0.0/0"] } } ``` But now, I'm receiving this behavior instead: ``` behavior: Invalid for_each argument on main.tf line 15, in resource "aws_security_group" "example": 15: for_each = toset(var.env_names) The "for_each" argument must be set to a map or set of strings. ``` I thought that converting the list to a set using `toset()` would work. I've confirmed that `var.env_names` is indeed a list of strings. Can someone clarify what I'm doing wrong here, or suggest the best way to create multiple security groups from a list of names? I'm using Terraform version 1.0.0. Any help would be greatly appreciated! This is part of a larger API I'm building.