Search code examples
terraform

receiving terraform security group syntax error for two ec2 instance


I am receiving the below error.

ec2.tf

## create EC2 instance for webserver 
module "ec2-module" {

  source  = "XXX"
  version = "4.0.1"

  for_each = toset(["1", "2"])

  #ec2 instance settings
  
  backup_plan        = XXX
  env                = XXX
  instance_type      = XXX
  key_name           = XXX
  maintenance_window = XXX
  name               = "${var.xxx["name"]}-${each.key}"
  os                 = XXX
  product_code       = data.terraform_remote_state.app-baseline.outputs.account_short_name
  subnet_id          = data.terraform_remote_state.app-baseline.outputs.private_subnets_primary[0]
  vpc_group          = data.terraform_remote_state.app-baseline.outputs.account_vpc_policy

  tags = local.common_tags
  }

sg.tf

### Allow traffic from EC2 to RDS mysql instance
`resource "aws_security_group_rule" "ec2_rds_webserver_1" {
  type              = "ingress"
  from_port                = var.webserver_rds["db_port"]
  to_port                  = var.webserver_rds["db_port"]
  protocol                 = "tcp"
  source_security_group_id = module.ec2-module.security_groups[0]
  security_group_id        = module.rds-webserver.sg_rds_servers
}

error source_security_group_id = module.ec2-module.security_groups[0] module.ec2-module is object with 2 attributes This object does not have an attribute named "security_groups".

I'd create two EC2 instance and I can't find syntax to handle two ec2-module objects.

I need code to handle two ec2-module objects.


Solution

  • You are using a for_each to deploy the module, which means that you need to add an identifier in the correct place when referencing an attribute.

    Change: module.ec2-module.security_groups[0]

    Into: module.ec2-module[1].security_groups[0] or module.ec2-module[2].security_groups[0]