module "default_tags" {
  source             = "git@github.com:theorchard/terraform-default-tags.git//?ref=2.0.0"
  environment        = var.environment
  application_family = "devops"
  team_name          = "devops"
}

provider "aws" {
  region = var.aws_region

  default_tags {
    tags = module.default_tags.tags
  }
}

# Terraform backends cannot contain interpolations
terraform {
  backend "s3" {
    bucket  = "prod-dc-terraform-state"
    key     = "prod/datacollector-server/terraform.tfstate"
    region  = "us-east-1"
    encrypt = true
  }
}

resource "aws_instance" "datacollector_instance" {
  # checkov:skip=CKV_AWS_8: The storage is encrypted but not defined in Terraform.
  # checkov:skip=CKV_AWS_126: The existing value is false, monitoring is disabled.
  ami                         = "ami-02deed6b2adf2775d"
  instance_type               = "m5.8xlarge"
  subnet_id                   = "subnet-0057d7881dd979b52"
  associate_public_ip_address = false
  availability_zone           = "us-east-1a"
  vpc_security_group_ids      = ["sg-01d360805e16b58de"]
  ebs_optimized               = true
  iam_instance_profile        = aws_iam_instance_profile.datacollector_profile.name
  monitoring                  = false

  metadata_options {
    http_endpoint               = "enabled"
    http_protocol_ipv6          = "disabled"
    http_put_response_hop_limit = 2
    http_tokens                 = "required"
    instance_metadata_tags      = "disabled"
  }

  tags = {
    Name        = "dcp-datacollector-server"
    SERVER_TYPE = "EC2"
  }
}

resource "aws_iam_instance_profile" "datacollector_profile" {
  name = "dcp-datacollector-server-profile"
  role = aws_iam_role.datacollector_s3_access_role.name
}

data "aws_iam_policy_document" "assume_role" {
  statement {
    effect = "Allow"

    principals {
      type        = "Service"
      identifiers = ["ec2.amazonaws.com"]
    }

    actions = ["sts:AssumeRole"]
  }
}

resource "aws_iam_role" "datacollector_s3_access_role" {
  name               = "EC2-dcp-datacollector-server-role"
  path               = "/"
  assume_role_policy = data.aws_iam_policy_document.assume_role.json
}

module "datacollector_s3_access_iam_policy_document" {
  source = "git@github.com:theorchard/terraform-iam-policy-templates.git//documents/s3/buckets_with_prefixes?ref=0.4.0"

  buckets = [{
    bucket = "orcd-podcast-analytics"
  }]
  action_types = ["read"]
}

resource "aws_iam_role_policy" "datacollector_s3_access_role_policy" {
  policy = module.datacollector_s3_access_iam_policy_document.policy.json
  role   = aws_iam_role.datacollector_s3_access_role.id
}
