locals {
  # For the default EBS key, we allow the entire account access
  root_arn = "arn:${var.aws_partition}:iam::${var.aws_account_id}:root"
}

module "ebs_root_encrypt_decrypt" {
  source = "../../submodules/kms/ebs-key"

  name = "ebs_root_encrypt_decrypt"
  alias = "alias/ebs_root_encrypt_decrypt"
  description = "encrypt and decrypt root volume" # updated to match legacy
  tags = merge(var.standard_tags, var.tags)
  key_admin_arns = var.extra_ebs_key_admins
  key_user_arns = concat([ local.root_arn ], var.extra_ebs_key_users)
  key_attacher_arns = concat([ local.root_arn ], var.extra_ebs_key_attachers)
  standard_tags = var.standard_tags
  aws_account_id = var.aws_account_id
  aws_partition = var.aws_partition
  is_legacy = var.is_legacy

  depends_on = [ aws_iam_service_linked_role.AWSServiceRoleForAutoScaling ]
}

# Note: The following wasn't configured in tf11
resource "aws_ebs_default_kms_key" "ebs_root_encrypt_decrypt" {
  key_arn = module.ebs_root_encrypt_decrypt.key_arn
}

resource "aws_ebs_encryption_by_default" "encryptbydefault" {
  enabled = true
}

resource "aws_kms_grant" "ASG_access_to_EBS_Default_CMK" {
  name              = "ASG_access_to_EBS_Default_CMK"
  key_id            = module.ebs_root_encrypt_decrypt.key_arn
  grantee_principal = aws_iam_service_linked_role.AWSServiceRoleForAutoScaling.arn
  operations        = [
    "Decrypt",
    "Encrypt",
    "GenerateDataKey",
    "GenerateDataKeyWithoutPlaintext",
    "ReEncryptFrom",
    "ReEncryptTo",
    "CreateGrant",
    "RetireGrant",
    "DescribeKey",
  ]

  depends_on = [ aws_iam_service_linked_role.AWSServiceRoleForAutoScaling ]
}
