【问题标题】:AWS Lambda "Unable to marshal response" ErrorAWS Lambda“无法编组响应”错误
【发布时间】:2020-08-28 16:30:38
【问题描述】:

我正在尝试设置一个 AWS lambda,它将在我的 EC2 实例中启动一个 SSM 会话并运行一个命令。为简单起见,我现在只是尝试运行 ls。这是我的 lambda 函数:

import json
import boto3

def lambda_handler(commands, context):
    """Runs commands on remote linux instances
    :param client: a boto/boto3 ssm client
    :param commands: string, each one a command to execute on the instance
    :return: the response from the send_command function (check the boto3 docs for ssm client.send_command() )
    """
    client = boto3.client('ssm')
    print ("Hello world")
    resp = client.send_command(
        DocumentName="AWS-RunShellScript",
        # Would normally pass commands param here but hardcoding it instead for testing
        Parameters={"commands":["ls"]},
        InstanceIds=["i-01112223333"],
    )
    return resp

但是,当我在此函数上运行“测试”时,我得到以下日志输出:

START RequestId: d028de04-4004-4a0p-c8d2-975755c84777 Version: $LATEST
Hello world
[ERROR] Runtime.MarshalError: Unable to marshal response: datetime.datetime(2020, 5, 12, 19, 34, 36, 349000, tzinfo=tzlocal()) is not JSON serializable
END RequestId: d028de04-4asdd4-4a0f-b8d2-9asd847813
REPORT RequestId: d42asd04-44d4-4a0f-b9d2-275755c6557   Duration: 1447.76 ms    Billed Duration: 1500 ms    Memory Size: 128 MB Max Memory Used: 76 MB  Init Duration: 301.68 ms

我不确定这个 Runtime.MarshalError: Unable to marshal response 错误是什么意思或如何修复它。

我传递来运行 Test lambda 的有效负载应该无关紧要,因为我没有使用 commands 参数,但它是:

{
  "command": "ls"
}

任何帮助将不胜感激

【问题讨论】:

    标签: python amazon-web-services aws-lambda boto3 aws-ssm


    【解决方案1】:

    这个错误的措辞很清楚,你只是在关注错误的部分。

    我假设您在某处使用resp 对象,并且该部分尝试执行类似json.load() 或相关的操作。

    datetime.datetime(2020, 5, 12, 19, 34, 36, 349000, tzinfo=tzlocal()) is not JSON serializable
    

    这是第一次遇到datetime 的人的常见错误,这里有一个非常全面的问题:How to overcome "datetime.datetime not JSON serializable"?

    【讨论】:

    • 不完全是答案,但这确实让我找到了正确的解决方案。你是对的,我专注于错误的部分。我没有在任何地方调用“resp”,只是将它返回为 lambda 输出,但 AWS lambda 本身显然正在使用它。将最后一行更改为“return str(resp)”解决了该问题。谢谢
    【解决方案2】:

    尝试以下方法:

    return json.loads(json.dumps(resp, default=str))
    

    这会将 resp 转储为 JSON 并使用 str 函数进行日期时间序列化。然后它恢复同一个对象,但你将得到可以序列化的字符串,而不是 datetime 对象。

    【讨论】:

      猜你喜欢
      • 2021-06-09
      • 2018-02-28
      • 1970-01-01
      • 1970-01-01
      • 2017-09-28
      • 2018-03-22
      • 1970-01-01
      相关资源
      最近更新 更多