You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现S3触发的EC2自动化运行GitHub上Python分析代码的工作流

解决方案:S3触发EC2自动执行GitHub图片分析代码的自动化工作流

以下是几种可行的落地方案,针对你当前的问题场景优化:

方案一:EC2用户数据(User Data)自动初始化执行

利用EC2启动时的用户数据,让实例启动后自动拉取代码、执行任务并自我终止,无需额外命令触发。

步骤:

  1. 编写启动执行脚本
    准备一个Shell脚本,嵌入到EC2的用户数据中,示例如下:

    #!/bin/bash
    # 安装依赖(根据你的Python环境调整)
    yum update -y
    yum install python3 git -y
    pip3 install boto3 pillow pandas  # 替换为你的代码依赖
    
    # 克隆GitHub仓库(如果是私仓,用带令牌的HTTPS链接或配置SSH密钥)
    git clone https://github.com/your-username/your-repo.git /opt/image-analyzer
    cd /opt/image-analyzer
    
    # 执行Python分析脚本(传入S3源桶、目标桶参数)
    python3 image_analyze.py --source-bucket your-source-bucket --target-bucket your-target-bucket
    
    # 任务完成后停止当前实例(需给EC2角色加停止权限)
    INSTANCE_ID=$(curl -s http://169.254.169.254/latest/meta-data/instance-id)
    aws ec2 stop-instances --instance-ids $INSTANCE_ID --region your-region
    
  2. 配置EC2实例角色
    创建IAM角色并附加到EC2实例,需包含以下权限:

    • S3读写权限(访问源桶和目标桶)
    • EC2实例停止权限(允许自身终止)
    • CloudWatch日志权限(可选,用于记录执行日志)
  3. 修改Lambda触发逻辑
    在Lambda启动EC2的代码中,指定包含上述脚本的用户数据(注意用户数据需Base64编码):

    import boto3
    import base64
    
    ec2 = boto3.client('ec2')
    
    def lambda_handler(event, context):
        user_data = """
        # 这里粘贴上面的Shell脚本内容
        """
        encoded_user_data = base64.b64encode(user_data.encode()).decode()
        ec2.run_instances(
            ImageId='your-ami-id',
            InstanceType='t3.medium',
            IamInstanceProfile={'Name': 'your-ec2-role-name'},
            UserData=encoded_user_data,
            # 其他参数:密钥对、安全组等
        )
    

方案二:AWS Systems Manager (SSM) Run Command 远程触发

适合已有固定EC2实例(处于停止状态)的场景,启动后通过SSM发送执行命令。

步骤:

  1. 配置EC2实例SSM访问

    • 确保EC2实例安装了SSM Agent(Amazon Linux 2默认预装,其他系统需手动安装)
    • 给EC2实例附加AmazonEC2RoleforSSM角色,允许SSM管理实例
  2. Lambda逻辑调整
    Lambda触发流程:启动EC2 → 等待实例就绪并可被SSM连接 → 发送执行命令 → 任务完成后停止实例
    核心代码片段:

    import boto3
    import time
    
    ec2 = boto3.client('ec2')
    ssm = boto3.client('ssm')
    
    def lambda_handler(event, context):
        # 启动EC2实例
        instance_id = 'your-instance-id'
        ec2.start_instances(InstanceIds=[instance_id])
    
        # 等待实例就绪且SSM可连接
        waiter = ec2.get_waiter('instance_running')
        waiter.wait(InstanceIds=[instance_id])
        time.sleep(30)  # 额外等待SSM Agent注册
    
        # 发送执行命令
        response = ssm.send_command(
            InstanceIds=[instance_id],
            DocumentName='AWS-RunShellScript',
            Parameters={
                'commands': [
                    'cd /opt/image-analyzer && git pull',
                    'python3 image_analyze.py --source-bucket your-source-bucket --target-bucket your-target-bucket',
                    'aws ec2 stop-instances --instance-ids {}'.format(instance_id)
                ]
            }
        )
    

方案三:AWS Batch 托管式任务执行

无需手动管理EC2实例,由Batch自动按需启动计算资源、执行任务并回收。

步骤:

  1. 创建Batch资源

    • 计算环境:选择"按需实例",指定实例类型和VPC配置
    • 作业队列:关联上述计算环境
    • 作业定义:指定执行脚本,示例命令:
      git clone https://github.com/your-username/your-repo.git && cd your-repo && pip3 install -r requirements.txt && python3 image_analyze.py --source-bucket your-source-bucket --target-bucket your-target-bucket
      
  2. Lambda触发Batch作业
    S3事件触发Lambda后,直接提交Batch作业:

    import boto3
    
    batch = boto3.client('batch')
    
    def lambda_handler(event, context):
        batch.submit_job(
            jobName='image-analysis-job',
            jobQueue='your-job-queue',
            jobDefinition='your-job-definition'
        )
    

关键注意事项

  • 权限配置:确保所有IAM角色(Lambda、EC2、Batch)拥有对应服务的操作权限,避免因权限不足导致流程中断
  • 私仓访问:若GitHub仓库为私有,可将访问令牌存储在AWS Secrets Manager,让实例/任务启动时拉取令牌用于克隆代码
  • 错误处理:添加CloudWatch日志监控任务执行状态,配置SNS告警接收失败通知
  • 资源清理:所有方案需确保任务失败时也能终止EC2实例,避免资源浪费

内容的提问来源于stack exchange,提问作者MRo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 17:07:33