解密AWS Lambda中的环境变量在Python 3.6中不起作用

时间:2019-05-08 16:32:23

标签: python python-3.x aws-lambda python-3.6

我已使用AWS KMS在AWS Lambda函数中加密了一个环境变量。然后,我尝试使用AWS提供的示例代码对代码中的变量进行解密,以下示例适用于我的变量:

import os
import boto3
from base64 import b64decode

keys = {}
def get_variable(variable):
    encrypted = os.environ[f'{variable}']
    decrypted = boto3.client('kms').decrypt(CiphertextBlob=b64decode(encrypted))['Plaintext']
    keys[variable] = decrypted

get_variable('port')

def lambda_handler(event,context):
    port = keys['port']
    return port

我已经测试了该功能,但它抛出了下一个错误:

An error occurred during JSON serialization of response: b'5934' is not JSON serializable
Traceback (most recent call last):
  File "/var/lang/lib/python3.6/json/__init__.py", line 238, in dumps
    **kw).encode(obj)
  File "/var/lang/lib/python3.6/json/encoder.py", line 199, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "/var/lang/lib/python3.6/json/encoder.py", line 257, in iterencode
    return _iterencode(o, 0)
  File "/var/runtime/awslambda/bootstrap.py", line 110, in decimal_serializer
    raise TypeError(repr(o) + " is not JSON serializable")
TypeError: b'5934' is not JSON serializable

但是,将Lambda从Python 3.6切换到Python 3.7可以使其完美运行。有什么办法可以解决它,而不必更改我的python版本?

1 个答案:

答案 0 :(得分:1)

您可以尝试以下方法。它只是确保该函数返回的字符串是JSON可序列化的字符串,而不是不是字节序列的字节。

def lambda_handler(event,context):
    port = keys['port']
    return str(port)