# Do not copy this, it's not how we do it
module "test_instance" {
  source                 = "terraform-aws-modules/ec2-instance/aws"
  version                = "~> 2.0"

  name                   = "test_instance"
  instance_count         = var.create_test_instance ? 1 : 0
  disable_api_termination = false # the test instance can always be destroyed

  ami                    = local.ami_map[var.test_instance_ami]
  instance_type          = "t3a.micro"
  key_name               = var.test_instance_key_name
  vpc_security_group_ids = var.security_group_ids
  subnet_id              = var.subnet_id
  tags = merge(var.standard_tags, var.tags)

  ebs_optimized          = true
  monitoring             = false # Do we use this?

  user_data_base64 = data.template_cloudinit_config.cloud-init.rendered
}

data "template_file" "cloud-init" {
  # Should these be in a common directory? I suspect they'd be reusable
  template = file("${path.module}/cloud-init/cloud-init.tpl")

  vars = {
    hostname = "test_instance"
    fqdn = "test_instance.${var.dns_info["private"]["zone"]}"
    environment = var.environment
    saltmaster  = "salt-master.${var.dns_info["private"]["zone"]}"
    aws_partition = var.aws_partition
    aws_partition_alias = var.aws_partition_alias
    aws_region = var.aws_region
  }
}

# Render a multi-part cloud-init config making use of the part
# above, and other source files
data "template_cloudinit_config" "cloud-init" {
  gzip          = true
  base64_encode = true

  # Main cloud-config configuration file.
  part {
    filename     = "init.cfg"
    content_type = "text/cloud-config"
    content      = data.template_file.cloud-init.rendered
  }

  # Additional parts as needed
  #part {
  #  content_type = "text/x-shellscript"
  #  content      = "ffbaz"
  #}
}
