data aws_ami "preauthorized" {

  most_recent      = true
  owners           = ["aws-marketplace"]

  filter {
    name   = "product-code"
    values = [ "1mp9h4zd2ze4biqif5schqeyu" ]
  }
  filter {
      name = "name"
      values = [ "qVSA*" ]
  }
}

data aws_ami "standard" {

  most_recent      = true
  owners           = ["aws-marketplace"]

  filter {
    name   = "product-code"
    values = [ "9hnn1m0a6jb7k2r1n9itk3jxu" ]
  }
  filter {
      name = "name"
      values = [ "qVSA*" ]
  }
}


resource aws_instance "qualys_scanner_preauthorized" {

  count                       = var.create_preauthorized_scanner == true ? 1 : 0
  ami                         = data.aws_ami.preauthorized.id
  instance_type               = "t3.medium"
  subnet_id                   = element(module.vpc.private_subnets,0)

  user_data                   = base64encode("PERSCODE=${var.personalization_codes["preauthorized"]}")

  ebs_optimized               = true
  vpc_security_group_ids      = [
    module.qualys_scanner_sg.this_security_group_id
  ]

  credit_specification {
    cpu_credits            = "unlimited"
  }

  tags                        = merge(var.tags,{"Name": "qualys-scanner-preauthorized"})
  volume_tags                 = merge(var.tags,{"Name": "qualys-scanner-preauthorized"})
  root_block_device {
    volume_size = 100
    volume_type = "gp2"
    encrypted   = true
  }
  lifecycle {
    ignore_changes = [ ami ]
  }
}

resource aws_instance "qualys_scanner_standard" {

  count                       = var.create_standard_scanner == true ? 1 : 0
  ami                         = data.aws_ami.standard.id
  instance_type               = "t3.medium"
  subnet_id                   = element(module.vpc.private_subnets,0)

  user_data                   = base64encode("PERSCODE=${var.personalization_codes["standard"]}")

  ebs_optimized               = true
  vpc_security_group_ids      = [
    module.qualys_scanner_sg.this_security_group_id
  ]

  credit_specification {
    cpu_credits            = "unlimited"
  }

  tags                        = merge(var.tags,{"Name": "qualys-scanner-standard"})
  volume_tags                 = merge(var.tags,{"Name": "qualys-scanner-standard"})
  root_block_device {
    volume_size = 100
    volume_type = "gp2"
    encrypted   = true
  }

  lifecycle {
    ignore_changes = [ ami ]
  }
}
