如何用Terraform部署含本地脚本的AWS SageMaker Notebook实例?
解决方案:无需外部代码仓库,将本地脚本嵌入Terraform部署SageMaker Notebook实例
aws_sagemaker_notebook_instance资源不强制要求关联代码仓库,default_code_repository是可选配置。如果你希望项目自包含,把本地Jupyter脚本部署到SageMaker实例,可通过以下方法实现:
方法一:使用SageMaker生命周期配置(推荐)
通过生命周期配置,在实例启动/创建时自动将本地脚本从S3复制到实例工作目录,全程用Terraform管理,无需外部仓库。
步骤1:上传本地脚本到S3
用Terraform将本地.ipynb文件上传到S3桶:
# 创建唯一命名的S3桶(避免名称冲突) resource "aws_s3_bucket" "notebooks_bucket" { bucket = "my-sagemaker-notebooks-${random_string.suffix.result}" } resource "random_string" "suffix" { length = 6 special = false upper = false } # 上传本地Notebook脚本到S3 resource "aws_s3_object" "notebook_script" { bucket = aws_s3_bucket.notebooks_bucket.id key = "scripts/my_notebook.ipynb" source = "./local_scripts/my_notebook.ipynb" # 替换为你的本地脚本路径 }
步骤2:创建生命周期配置
定义实例启动时执行的脚本,将S3中的文件复制到SageMaker实例的工作目录:
resource "aws_sagemaker_notebook_instance_lifecycle_config" "notebook_lifecycle" { name = "notebook-startup-config" on_start { content = base64encode(<<-EOF #!/bin/bash set -e # 从S3复制脚本到实例工作目录 aws s3 cp s3://${aws_s3_bucket.notebooks_bucket.id}/${aws_s3_object.notebook_script.key} /home/ec2-user/SageMaker/ # 设置正确的文件权限 chown ec2-user:ec2-user /home/ec2-user/SageMaker/my_notebook.ipynb EOF ) } }
步骤3:创建SageMaker Notebook实例
关联生命周期配置,无需指定代码仓库:
# 创建SageMaker服务角色 resource "aws_iam_role" "sagemaker_role" { name = "sagemaker-notebook-role" assume_role_policy = jsonencode({ Version = "2012-10-17" Statement = [ { Action = "sts:AssumeRole" Effect = "Allow" Principal = { Service = "sagemaker.amazonaws.com" } } ] }) } # 赋予角色S3只读权限(用于拉取脚本) resource "aws_iam_role_policy_attachment" "sagemaker_s3_access" { role = aws_iam_role.sagemaker_role.name policy_arn = "arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess" } # 创建Notebook实例 resource "aws_sagemaker_notebook_instance" "my_notebook" { name = "my-sagemaker-notebook" instance_type = "ml.t2.medium" # 替换为你需要的实例类型 role_arn = aws_iam_role.sagemaker_role.arn lifecycle_config_name = aws_sagemaker_notebook_instance_lifecycle_config.notebook_lifecycle.name # 无需配置default_code_repository }
方法二:临时CodeCommit仓库(仅当需要代码版本控制时使用)
如果你的场景必须关联代码仓库(比如需要版本同步),可以用Terraform创建临时CodeCommit仓库,将本地脚本推送到该仓库后关联:
- 用
aws_codecommit_repository创建仓库 - 用
local-exec在Terraform部署时将本地脚本推送到CodeCommit - 在
aws_sagemaker_notebook_instance中指定default_code_repository为该CodeCommit仓库的ARN
但注意:这种方法会额外创建CodeCommit资源,如果你只是需要部署本地脚本,方法一更简洁且满足自包含需求。
内容的提问来源于stack exchange,提问作者Jaco Van Niekerk
相关产品推荐
相关产品推荐

