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

如何在Python 3.X的Lambda函数中添加多个EC2实例ID

修改Lambda函数支持多EC2实例执行命令

以下是修改后的完整代码,直接替换你的原有代码即可:

import time
import json
import boto3


def lambda_handler(event, context):
    # 初始化SSM客户端
    ssm = boto3.client("ssm")

    # 定义需要执行命令的多个EC2实例ID列表
    instance_ids = ['i-0e946552448dgsd', 'i-0e946258789itrs']
    
    # 向多个实例发送命令
    response = ssm.send_command(
            InstanceIds=instance_ids,
            DocumentName="AWS-RunShellScript",
            Parameters={
                "commands": ["sh /root/test.sh"]
            },  
        )

    # 获取命令ID
    command_id = response["Command"]["CommandId"]

    # 等待命令执行(可根据实际情况调整等待时长)
    time.sleep(5)

    # 遍历每个实例,获取并打印各自的命令执行输出
    for instance_id in instance_ids:
        try:
            output = ssm.get_command_invocation(CommandId=command_id, InstanceId=instance_id)
            print(f"实例 {instance_id} 的执行输出:")
            print(output)
        except Exception as e:
            print(f"获取实例 {instance_id} 输出失败: {str(e)}")

    return {"statusCode": 200, "body": json.dumps("命令已发送至指定实例!")}

关键修改说明:

  • 多实例ID配置:将原来单个字符串的instance_id改为包含多个实例ID的列表instance_ids,直接传入send_command的InstanceIds参数(SSM API原生支持批量指定实例)。
  • 批量获取执行结果:由于get_command_invocation只能查询单个实例的命令结果,因此新增循环遍历实例列表,逐个获取并打印每个实例的输出,同时添加异常处理避免单个实例失败导致整个函数报错。
  • 移除冗余代码:删除了未使用的EC2客户端client = boto3.client("ec2"),精简代码。
  • 调整等待时间:将原3秒等待时长改为5秒(可根据你的脚本执行时间灵活调整),确保大部分实例有足够时间完成命令执行。

注意事项:

  1. 确保所有指定的EC2实例已安装SSM Agent,并且IAM角色具备AmazonSSMManagedInstanceCore权限。
  2. 如果实例数量较多,建议使用异步方式处理结果,或者结合SSM的命令状态查询API替代固定时长的sleep。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 10:50:36