AWS Lambda "Unable to marshal response" 错误

AWS Lambda "Unable to marshal response" Error

我正在尝试设置一个 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

然而,当我 运行 "Test" 使用此函数时,我得到以下日志输出:

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: 无法编组响应 错误是什么意思或如何修复它。

我传递给 运行 测试 lambda 的有效载荷应该无关紧要,因为我没有使用命令参数,但它是:

{
  "command": "ls"
}

如有任何帮助,我们将不胜感激

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

我假设你在某处使用了 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"?

尝试以下操作:

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

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