通过 Terraform 创建 sagemaker notebook 实例

create sagemaker notebook instance via Terraform

我正在迈出进入 Terraform 世界的第一步,所以请对我温柔点。我有一个使用 AmazonSageMakerFullAccess 的用户,我通过 AWS CLI 将其存储在一个名为 terraform 的配置文件中。我可以创建一个 S3 存储桶,如下所示,在 VSC 的 Windows 中引用此用户没有问题:

provider "aws" {
    region = "eu-west-2"
    shared_credentials_files = ["C:\Users\amazinguser\.aws\credentials"]
    profile = "terraform"
}

resource "aws_s3_bucket" "b" {
  bucket = "blabla-test-bucket"

  tags = {
    Name        = "amazing_tag"
    Environment = "dev"
  }
}

我尝试实施 this documented here 并尝试这样做:

resource "aws_sagemaker_notebook_instance" "notebook_instance" {
  name = "titanic-sagemaker-byoc-notebook"
  role_arn = aws_iam_role.notebook_iam_role.arn
  instance_type = "ml.t2.medium"
  #lifecycle_config_name = aws_sagemaker_notebook_instance_lifecycle_configuration.notebook_config.name
  #default_code_repository = aws_sagemaker_code_repository.git_repo.code_repository_name
}

我对这里定义的 role_arn 有点困惑:

https://github.com/dkhundley/terraform-sagemaker-tutorial/blob/main/Part%202a%20-%20Creating%20a%20SageMaker%20Notebook/terraform/iam.tf

我可以不使用上面的用户吗?谢谢!

默认情况下不允许尝试调用其他 AWS 服务和执行操作的 AWS 服务。例如,SageMaker 笔记本基本上是 EC2 实例。为了让 SageMaker 创建 EC2 实例,它必须有一个允许例如将 ENI 注入 VPC 的策略。由于您可能不想自己完成所有这些工作(毕竟这是一项托管笔记本服务),因此您必须授予 SageMaker 代表您执行操作的权限。输入 执行角色 。对于 SageMaker,您可以在 [1] 中阅读更多内容。您通常会发现使用执行角色的其他服务包括 Lambda、ECS 和许多其他服务。一个 IAM 角色通常由两部分组成:

  1. 信任关系(我喜欢称之为信任政策)
  2. 权限策略

第一个决定哪个委托人(AWS 标识符、服务等 [2])将能够承担该角色。在您的示例中,即:

data "aws_iam_policy_document" "sm_assume_role_policy" {
  statement {
    actions = ["sts:AssumeRole"]
    
    principals {
      type = "Service"
      identifiers = ["sagemaker.amazonaws.com"]
    }
  }
}

该政策的内容是“我将允许 SageMaker(Service 类型)承担该政策所附加的任何角色,并执行权限政策中定义的操作”。权限策略是:

# Attaching the AWS default policy, "AmazonSageMakerFullAccess"
resource "aws_iam_policy_attachment" "sm_full_access_attach" {
  name = "sm-full-access-attachment"
  roles = [aws_iam_role.notebook_iam_role.name]
  policy_arn = "arn:aws:iam::aws:policy/AmazonSageMakerFullAccess"
}

无需详细了解 SageMaker 的 AWS 托管策略的功能,只需查看 FullAccess 部分就可以清楚地了解它。如果您想格外小心,可以做的是为 SageMaker 笔记本定义客户托管策略 [3]。此权限策略将附加到 roles 参数中定义的 IAM 角色。请注意,它是一个列表,因此多个角色可以附加相同的权限策略。

最后但同样重要的是,信任和权限策略之间的粘合剂是角色本身:

resource "aws_iam_role" "notebook_iam_role" {
  name = "sm_notebook_role"
  assume_role_policy = data.aws_iam_policy_document.sm_assume_role_policy.json
}

如您所见,assume_role_policy 是允许 SageMaker 根据权限策略中定义的权限在 AWS 账户中执行操作的策略。

这个主题比这个答案复杂得多,但它应该能为您提供相当多的信息。

注意:理论上,在 AWS 中访问信息的相同角色和使用 Terraform 时 运行 AWS API 操作可用于 SageMaker,但我强烈建议不要这样做。始终牢记关注点分离和最小特权原则。


[1] https://docs.aws.amazon.com/sagemaker/latest/dg/sagemaker-roles.html#sagemaker-roles-create-execution-role

[2]https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_principal.html

[3]https://docs.aws.amazon.com/acm/latest/userguide/authen-custmanagedpolicies.html