如何在Lambda中向AWS-RunShellScript命令传递变量?
正确实现方式
你当前代码存在两个核心问题:实例ID类型错误、Python变量未正确传入Shell命令,以下是修正后的完整实现:
import sys import logging import datetime import boto3 import botocore import time import json from os import getenv region = 'ap-southeast-2' boto3.setup_default_session(region_name=region) account_id = 123454 def handler(event, context): client = boto3.client('ssm') # 实例ID必须是字符串类型,不能直接使用数字 instance_name_list = ['12345678890', '0000000000'] if instance_name_list: try: response = client.send_command( Targets=[ { 'Key': 'InstanceIds', 'Values': instance_name_list }, ], DocumentName='AWS-RunShellScript', Parameters={ 'commands': [ # 使用f-string将Python变量插入Shell命令,注意变量名大小写匹配 f'echo {account_id}', ] } ) # 可选:添加命令发送后的结果处理逻辑 command_id = response['Command']['CommandId'] print(f"命令已成功发送,ID:{command_id}") except botocore.exceptions.ClientError as e: print(f"发送命令失败:{e.response['Error']['Message']}") raise e
关键修正说明:
- 实例ID类型修正:AWS EC2实例ID是字符串格式,
instance_name_list中的元素必须用引号包裹为字符串,直接写数字会导致SSM无法识别目标实例。 - 变量传入修正:使用Python的f-string语法(
f'echo {account_id}')将变量值插入Shell命令,同时注意原代码中变量名大小写不匹配的问题(原代码写的account_ID和定义的account_id不一致)。 - 异常处理补充:添加了SSM命令发送失败的捕获逻辑,便于排查问题。
内容的提问来源于stack exchange,提问作者Faizan Awan
相关产品推荐
相关产品推荐

