【问题标题】:Execute Lambda from AWS SSM Automation with Parameters使用参数从 AWS SSM Automation 执行 Lambda
【发布时间】:2024-05-20 16:00:02
【问题描述】:

我目前有一个 lambda 函数,它使用作为参数传递的值更新 DynamoDB 表。我可以在 Lambda 控制台中运行以下命令,并将测试参数设置为 "TEST"

import boto3
import json

def lambda_handler(event, context):
    # TODO implement
    update_ami(event)


def update_ami(ami_id):
    #DO STUFF

我正在尝试从基于以下 JSON 文档构建的 SSM 自动化中调用它:

{  
   "description":"Test Execute Lambda Function.",
   "schemaVersion":"0.3",
   "assumeRole":"MYARN",
   "parameters":{},
   "mainSteps":[  
        {
            "name": "invokeMyLambdaFunction",
            "action": "aws:invokeLambdaFunction",
            "maxAttempts": 3,
            "timeoutSeconds": 120,
            "onFailure": "Abort",
            "inputs": {
                "FunctionName": "MyLambdaFunction",
                "Payload": "TESTER"

            }
        }
   ]
}

执行此自动化会导致以下错误:

Automation Step Execution fails when it is invoking the lambda function. Get Exception from Invoke API of lambda Service. Exception Message from Invoke API: [Could not parse request body into json: Unrecognized token 'TESTER': was expecting ('true', 'false' or 'null')

我还尝试将Payload 输入作为 JSON 对象而不是字符串传递,并相应地调整了我的 lambda 方法:

JSON 自动化:

...
    "inputs": {
         "FunctionName": "MyLambdaFunction",
         "Payload": {
             "ami_id": "AMI-TESTER"
         }  
    }
...

Lambda Python:

def lambda_handler(event, context):
    # TODO implement
    update_ami(event['ami-id'])

这会导致来自 SSM 控制台中的自动化文档编辑器的以下错误:

Input {ami_id=TESTER} is of type class java.util.LinkedHashMap, but expected type is String.

简而言之...如何将单个字符串从自动化文档传递到 Lambda 函数?

【问题讨论】:

    标签: python json amazon-web-services automation aws-lambda


    【解决方案1】:

    下面显示的错误似乎是负载未作为字符串传递的问题:

    Input {ami_id=TESTER} is of type class java.util.LinkedHashMap, but expected type is String
    

    请尝试在双引号前使用转义字符。

        "inputs": {
                 "FunctionName": "MyLambdaFunction",
                 "Payload": "{
                     \"ami_id\": \"AMI-TESTER\"
                 }"  
            }
    

    AWS 提供了正确的语法,如果您看到 this Url

      {
         "name":"updateSsmParam",
         "action":"aws:invokeLambdaFunction",
         "timeoutSeconds":1200,
         "maxAttempts":1,
         "onFailure":"Abort",
         "inputs":{
            "FunctionName":"Automation-UpdateSsmParam",
            "Payload":"{\"parameterName\":\"latestAmi\", \"parameterValue\":\"{{createImage.ImageId}}\"}"
         }
      }
    

    【讨论】: