provider "aws" {
  region = "us-east-1"

  default_tags {
    tags = module.default_tags.tags
  }
}

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

data "aws_iam_policy_document" "customer_managed_kms_policy_example" {
  # checkov:skip=CKV_AWS_109:This is an example for the test
  # checkov:skip=CKV_AWS_111:This is an example for the test
  version = "2012-10-17"
  statement {
    sid    = "Allow access through Amazon DynamoDB for all principals in the account that are authorized to use Amazon DynamoDB"
    effect = "Allow"
    principals {
      identifiers = ["arn:aws:iam::111122223333:user/db-lead"]
      type        = "AWS"
    }
    actions = [
      "kms:Encrypt",
      "kms:Decrypt",
      "kms:ReEncrypt*",
      "kms:GenerateDataKey*",
      "kms:DescribeKey",
      "kms:CreateGrant"
    ]
    resources = ["*"]
    condition {
      test     = "StringLike"
      values   = ["dynamodb.*.amazonaws.com"]
      variable = "kms:ViaService"
    }
  }

  statement {
    sid    = "Allow administrators to view the KMS key and revoke grants"
    effect = "Allow"
    principals {
      identifiers = ["arn:aws:iam::111122223333:role/db-team"]
      type        = "AWS"
    }
    actions = [
      "kms:Describe*",
      "kms:Get*",
      "kms:List*",
      "kms:RevokeGrant"
    ]
    resources = ["*"]
  }
}

resource "aws_kms_key" "dynamodb_table_custom_kms_key" {
  # checkov:skip=CKV_AWS_7:This is an example for the test
  description = "My KMS key for DynamoDB"
}

resource "aws_kms_key_policy" "dynamodb_table_custom_kms_key_policy" {
  key_id = aws_kms_key.dynamodb_table_custom_kms_key.id
  policy = data.aws_iam_policy_document.customer_managed_kms_policy_example.json
}

module "global_table" {
  source = "../../"
  attribute = [
    { name = "primary_key", type = "S" },
    { name = "sort_key", type = "S" },
  ]
  application_family           = "devops"
  env                          = "dev"
  global_table_replica_regions = ["us-west-2"]
  range_key                    = "sort_key"
  range_key_enabled            = true
  table_name                   = "global_table_tf_test"
  kms_key_arn                  = aws_kms_key.dynamodb_table_custom_kms_key.arn
}
