export function buildSagemakerNotebook()

in source/patterns/@aws-solutions-constructs/core/lib/sagemaker-helper.ts [217:300]


export function buildSagemakerNotebook(
  scope: Construct,
  props: BuildSagemakerNotebookProps
): [sagemaker.CfnNotebookInstance, ec2.IVpc?, ec2.SecurityGroup?] {
  // Setup the notebook properties
  let sagemakerNotebookProps;
  let vpcInstance;
  let securityGroup;
  let kmsKeyId: string;
  let subnetId: string;

  // Conditional Sagemaker Notebook creation
  if (!props.existingNotebookObj) {
    if (
      (props.sagemakerNotebookProps?.subnetId && props.sagemakerNotebookProps?.securityGroupIds === undefined) ||
      (props.sagemakerNotebookProps?.subnetId === undefined && props.sagemakerNotebookProps?.securityGroupIds)
    ) {
      throw new Error('Must define both sagemakerNotebookProps.subnetId and sagemakerNotebookProps.securityGroupIds');
    }

    addPermissions(props.role);

    if (props.sagemakerNotebookProps?.kmsKeyId === undefined) {
      kmsKeyId = buildEncryptionKey(scope).keyId;
    } else {
      kmsKeyId = props.sagemakerNotebookProps.kmsKeyId;
    }

    if (props.deployInsideVpc === undefined || props.deployInsideVpc) {
      if (
        props.sagemakerNotebookProps?.subnetId === undefined &&
        props.sagemakerNotebookProps?.securityGroupIds === undefined
      ) {
        vpcInstance = buildVpc(scope, {
          defaultVpcProps: DefaultPublicPrivateVpcProps(),
        });
        securityGroup = buildSecurityGroup(
          scope,
          'SecurityGroup',
          {
            vpc: vpcInstance,
            allowAllOutbound: false,
          },
          [],
          [{ peer: ec2.Peer.anyIpv4(), connection: ec2.Port.tcp(443) }]
        );

        subnetId = vpcInstance.privateSubnets[0].subnetId;

        sagemakerNotebookProps = DefaultSagemakerNotebookProps(props.role.roleArn, kmsKeyId, subnetId, [
          securityGroup.securityGroupId,
        ]);
      } else {
        sagemakerNotebookProps = DefaultSagemakerNotebookProps(
          props.role.roleArn,
          kmsKeyId,
          props.sagemakerNotebookProps?.subnetId,
          props.sagemakerNotebookProps?.securityGroupIds
        );
      }
    } else {
      sagemakerNotebookProps = DefaultSagemakerNotebookProps(props.role.roleArn, kmsKeyId);
    }

    if (props.sagemakerNotebookProps) {
      sagemakerNotebookProps = overrideProps(sagemakerNotebookProps, props.sagemakerNotebookProps);
    }

    // Create the notebook
    const sagemakerInstance: sagemaker.CfnNotebookInstance = new sagemaker.CfnNotebookInstance(
      scope,
      'SagemakerNotebook',
      sagemakerNotebookProps
    );
    if (vpcInstance) {
      return [sagemakerInstance, vpcInstance, securityGroup];
    } else {
      return [sagemakerInstance];
    }
  } else {
    // Return existing notebook object
    return [props.existingNotebookObj];
  }
}