AWS Lambda:“参数验证失败”

时间:2019-07-24 10:20:37

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

我有一个lambda功能,我在其中发送电子邮件,并且邮件模板作为对象从S3存储桶中提取。我已经在计算机上本地运行了代码,并且工作正常。当我将其粘贴到lambda函数中时,它显示以下错误。

Response:
{
  "errorMessage": "Parameter validation failed:\nInvalid type for parameter Message.Body.Html.Data, value: b\"<html>\\n<head></head>\\n<body>\\n  <h1>Amazon SES Test (SDK for Python)</h1>\\n  <p>This email was sent with\\n    <a href='https://aws.amazon.com/ses/'>Amazon SES</a> using the\\n    <a href='https://aws.amazon.com/sdk-for-python/'>\\n      AWS SDK for Python (Boto)</a>.</p>\\n</body>\\n</html>\", type: <class 'bytes'>, valid types: <class 'str'>",
  "errorType": "ParamValidationError",
  "stackTrace": [
    [
      "/var/task/lambda_function.py",
      65,
      "lambda_handler",
      "Source=SENDER,"
    ],
    [
      "/var/runtime/botocore/client.py",
      314,
      "_api_call",
      "return self._make_api_call(operation_name, kwargs)"
    ],
    [
      "/var/runtime/botocore/client.py",
      586,
      "_make_api_call",
      "api_params, operation_model, context=request_context)"
    ],
    [
      "/var/runtime/botocore/client.py",
      621,
      "_convert_to_request_dict",
      "api_params, operation_model)"
    ],
    [
      "/var/runtime/botocore/validate.py",
      291,
      "serialize_to_request",
      "raise ParamValidationError(report=report.generate_report())"
    ]
  ]
}

Request ID:
"7b13a612-97f6-4278-9825-724abeaa3b51"

Function Logs:
START RequestId: 7b13a612-97f6-4278-9825-724abeaa3b51 Version: $LATEST
Parameter validation failed:
Invalid type for parameter Message.Body.Html.Data, value: b"<html>\n<head></head>\n<body>\n  <h1>Amazon SES Test (SDK for Python)</h1>\n  <p>This email was sent with\n    <a href='https://aws.amazon.com/ses/'>Amazon SES</a> using the\n    <a href='https://aws.amazon.com/sdk-for-python/'>\n      AWS SDK for Python (Boto)</a>.</p>\n</body>\n</html>", type: <class 'bytes'>, valid types: <class 'str'>: ParamValidationError
Traceback (most recent call last):
  File "/var/task/lambda_function.py", line 65, in lambda_handler
    Source=SENDER,
  File "/var/runtime/botocore/client.py", line 314, in _api_call
    return self._make_api_call(operation_name, kwargs)
  File "/var/runtime/botocore/client.py", line 586, in _make_api_call
    api_params, operation_model, context=request_context)
  File "/var/runtime/botocore/client.py", line 621, in _convert_to_request_dict
    api_params, operation_model)
  File "/var/runtime/botocore/validate.py", line 291, in serialize_to_request
    raise ParamValidationError(report=report.generate_report())
botocore.exceptions.ParamValidationError: Parameter validation failed:
Invalid type for parameter Message.Body.Html.Data, value: b"<html>\n<head></head>\n<body>\n  <h1>Amazon SES Test (SDK for Python)</h1>\n  <p>This email was sent with\n    <a href='https://aws.amazon.com/ses/'>Amazon SES</a> using the\n    <a href='https://aws.amazon.com/sdk-for-python/'>\n      AWS SDK for Python (Boto)</a>.</p>\n</body>\n</html>", type: <class 'bytes'>, valid types: <class 'str'>

END RequestId: 7b13a612-97f6-4278-9825-724abeaa3b51
REPORT RequestId: 7b13a612-97f6-4278-9825-724abeaa3b51  Duration: 1608.47 ms    Billed Duration: 1700 ms    Memory Size: 128 MB Max Memory Used: 71 MB

从S3存储桶加载模板时,我检查了它在lambda中显示以下错误。当我在代码中声明BODY_HTML而不从Lambda的S3中获取它时,它可以正常工作。现在这是我的代码:

import json
import os
import boto3
from botocore.exceptions import ClientError

SENDER = "***********"
RECIPIENT = "************"
AWS_REGION = "us-east-1"
def lambda_handler(event, context):            
    CHARSET = "UTF-8"
    client = boto3.client('ses',aws_access_key_id=******,
                              aws_secret_access_key=*****,region_name='us-east-1')
    s3_client = boto3.client('s3',aws_access_key_id=*********,
                                  aws_secret_access_key=***********,region_name='us-east-1')
    s3_response_object = s3_client.get_object(Bucket='my s3 bucket', Key='template.html')
    object_content = s3_response_object['Body'].read()
    BODY_HTML = object_content
    SUBJECT = "sqs-poc-lambda test email"
    BODY_TEXT = ("This is a test email for sqs-poc-lambda"
                )

    try:
        #Provide the contents of the email.
        response = client.send_email(
            Destination={
                'ToAddresses': [
                    RECIPIENT,
                ],
            },
            Message={
                'Body': {
                    'Html': {
                        'Charset': CHARSET,
                        'Data': BODY_HTML,
                    },
                    'Text': {
                        'Charset': CHARSET,
                        'Data': BODY_TEXT,
                    },
                },
                'Subject': {
                    'Charset': CHARSET,
                    'Data': SUBJECT,
                },
            },
            Source=SENDER,
        )

    except ClientError as e:
        print(e.response['Error']['Message'])
    else:
        print("Email sent! Message ID:"),
        print(response['MessageId'])

它应该在Function Logs中成功返回消息ID。有什么帮助吗?我看不出任何背后的逻辑。

1 个答案:

答案 0 :(得分:1)

很难相信第二个代码可以工作,因为它包含与第一个错误日志中报告的错误相同的错误。我已经复制了代码,但失败的方式相同。

可以通过从错误日志中读取此消息来发现问题。

参数Message.Body.Html.Data的无效类型,值:b“ ...”,类型:类字节,有效类型:类'str':ParamValidationError。

正文应为字符串类型,但object_content

object_content = s3_response['Body'].read()

是字节类型。您需要将其转换为字符串。例如。 BODY_HTML = str(object_content)

重要

不要在您的lambda代码中存储永久凭证。

client = boto3.client('ses',aws_access_key_id=******,
                          aws_secret_access_key=*****,region_name='us-east-1')
s3_client = boto3.client('s3',aws_access_key_id=*********,
                          aws_secret_access_key=***********,region_name='us-east-1')

通过Lambda执行角色授予对lambda函数的权限。

如果您需要为lambda函数提供跨帐户访问权限,则在该角色中包含sts:AssumeRole权限,然后使用通过调用sts:AssumeRole获得的临时凭据

client = boto3.client(
    'ses',
    aws_access_key_id=...,
    aws_secret_access_key=...,
    aws_session_token=... // !!!
)

但是,再次,从不将永久凭证存储在功能代码中。您确定下次将代码放置在某个公共存储库中时,会不会忘记将这些值替换为******?每次?