/**
 TERRAFORM SAGEMAKER NOTEBOOK MODULE

 This terraform module allows for spinning up a terraform notebook where you can explore and model data with out of the box support for the following:

* Feature Store (Offline) - Which allows the user to explore catalogued datasets
* Secret Manager - Only to a select few secrets that get created by secrets.tf
* S3 Access (default: dev-cucumbers) - this allows for loading data from snowflake (assuming you are using COPY INTO) to explore on the notebooks in python

**/


# Fetch service bucket
data "aws_s3_bucket" "selected" {
  bucket = var.service_bucket
}

# Create KMS key related resources
resource "aws_kms_key" "sagemaker_kms_key" {
  description             = "${var.environment}-${var.service_name}"
  enable_key_rotation     = true
  deletion_window_in_days = 30
}

resource "aws_kms_alias" "sagemaker_kms_alias" {
  name          = "alias/${var.environment}-sagemaker-${var.service_name}"
  target_key_id = aws_kms_key.sagemaker_kms_key.key_id
}


# Create AWS Sagemaker notebook instance
resource "aws_sagemaker_notebook_instance" "sagemaker_notebook" {
  # checkov:skip=CKV_AWS_371:Ensure Amazon SageMaker Notebook Instance only allows for IMDSv2
  name                   = "${var.environment}-sagemaker-${var.service_name}-notebook"
  role_arn               = aws_iam_role.notebook_iam_role.arn
  kms_key_id             = aws_kms_key.sagemaker_kms_key.key_id
  direct_internet_access = "Disabled"
  root_access            = "Disabled"

  # See network.tf for security-group module
  security_groups         = [aws_security_group.notebook_sg.id]
  subnet_id               = element(tolist(data.aws_subnets.private.ids), 0)
  instance_type           = var.instance_type
  volume_size             = var.volume_size
  platform_identifier     = var.platform_identifier
  default_code_repository = var.default_code_repository_name
  lifecycle_config_name   = var.lifecycle_config_enabled == false ? null : aws_sagemaker_notebook_instance_lifecycle_configuration.notebook_config[0].name

  tags = local.combined_resource_tags

}
