如何通过Lambda触发AWS SageMaker指定Notebook实例及IPynb文件
实现S3上传触发SageMaker Notebook运行指定脚本的方案
1. 配置S3事件触发Lambda
- 打开S3控制台,找到目标存储桶,进入「属性」→「事件通知」
- 创建新通知:
- 名称:比如
s3-upload-trigger-dev-process - 事件类型:勾选「所有对象创建事件」(或按需选择「PUT」等特定操作)
- 目标:选择「Lambda函数」,指定要创建的Lambda函数(也可先创建Lambda再返回选择)
- 名称:比如
2. 创建Lambda函数(Python运行时)
Lambda需完成三个核心操作:检查实例状态、启动实例(按需)、运行指定Notebook脚本。核心代码示例如下:
import boto3 import time sagemaker = boto3.client('sagemaker') ssm = boto3.client('ssm') INSTANCE_NAME = 'dev-process' NOTEBOOK_PATH = '/home/ec2-user/SageMaker/data-pipeline/entire_process.ipynb' def lambda_handler(event, context): # 获取Notebook实例当前状态 instance_status = sagemaker.describe_notebook_instance( NotebookInstanceName=INSTANCE_NAME )['NotebookInstanceStatus'] # 若实例处于停止/失败状态,启动实例并等待就绪 if instance_status in ['Stopped', 'Failed']: sagemaker.start_notebook_instance( NotebookInstanceName=INSTANCE_NAME ) # 轮询等待实例进入活跃状态 while True: current_status = sagemaker.describe_notebook_instance( NotebookInstanceName=INSTANCE_NAME )['NotebookInstanceStatus'] if current_status == 'InService': break time.sleep(30) # 每30秒检查一次状态 # 通过SSM发送命令执行Notebook脚本 response = ssm.send_command( InstanceIds=[INSTANCE_NAME], # SageMaker Notebook实例ID即实例名称 DocumentName='AWS-RunShellScript', Parameters={ 'commands': [ f'cd /home/ec2-user/SageMaker && jupyter nbconvert --to notebook --execute {NOTEBOOK_PATH} --inplace' ] } ) return { 'statusCode': 200, 'message': f'已触发实例{INSTANCE_NAME}运行脚本,命令ID: {response["Command"]["CommandId"]}' }
3. 配置Lambda的IAM角色权限
给Lambda执行角色添加以下权限策略:
- SageMaker权限:允许
DescribeNotebookInstance、StartNotebookInstance操作 - SSM权限:允许
SendCommand、DescribeCommands操作 - S3权限:允许读取触发事件的S3对象(按需配置,如
s3:GetObject)
示例权限策略片段:
{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "sagemaker:DescribeNotebookInstance", "sagemaker:StartNotebookInstance" ], "Resource": "arn:aws:sagemaker:*:*:notebook-instance/dev-process" }, { "Effect": "Allow", "Action": [ "ssm:SendCommand", "ssm:DescribeCommands" ], "Resource": [ "arn:aws:ssm:*:*:document/AWS-RunShellScript", "arn:aws:ec2:*:*:instance/*" ] }, { "Effect": "Allow", "Action": "s3:GetObject", "Resource": "arn:aws:s3:::your-bucket-name/*" } ] }
4. 验证流程
- 上传文件到目标S3存储桶
- 查看Lambda函数的CloudWatch执行日志,确认实例启动和命令发送情况
- 检查SageMaker Notebook实例的状态变化,以及脚本运行结果(可在实例对应路径下查看执行后的ipynb文件)
注意事项
- 若实例处于
Stopping或Starting状态,建议在Lambda中添加状态判断,避免重复操作 - 脚本运行时间可能较长,需将Lambda超时时间设置足够(比如15分钟,根据实际脚本运行时长调整)
- 确保Notebook实例的IAM角色拥有运行脚本所需的权限(如访问其他S3桶、调用AWS服务等)
内容的提问来源于stack exchange,提问作者Logan27
相关产品推荐
相关产品推荐

