Terraform duplicates the security groups, how do I stop it?

I’m using terraform to create two instances and a security group. Here is how I did it:

# bastion host
resource "aws_instance" "bastion_1a" {
  ami                         = data.aws_ami.amazon_linux_2.id
  availability_zone           = var.az_1a
  instance_type               = var.instance_type
  key_name                    = var.bastion_key_name
  subnet_id                   = data.aws_subnet.public_subnet_us_east_1a.id
  vpc_security_group_ids      = [aws_security_group.bastion_sg.id]
}

resource "aws_instance" "bastion_1b" {
  ami                         = data.aws_ami.amazon_linux_2.id
  availability_zone           = var.az_1b
  instance_type               = var.instance_type
  key_name                    = var.bastion_key_name
  subnet_id                   = data.aws_subnet.public_subnet_us_east_1b.id
  vpc_security_group_ids      = [aws_security_group.bastion_sg.id]    
}

resource "aws_security_group" "bastion_sg" {
  name        = var.name_bastion_sg
  description = var.bastion_sg_description  
  vpc_id      = module.vpc.vpc_id

  ingress {
    description = var.ssh_ingress_description
    from_port   = var.port_ssh
    to_port     = var.port_ssh
    protocol    = var.protocol_tcp
    cidr_blocks = local.ips_allowed_ssh
  }
}

the problem: after the resources have been created, I checked the console and found that two security groups were created one for bastion_1a and another one for bastion_1b. However, as you can see in my terraform I only specified one security group.

I would like to use terraform to create one security group for both instances.Please can someone explain to me why terraform is creating two security groups.

What do I need to do so that terraform only creates one security group.

Go to Source
Author: davidonstack