Javier Lopez Tomas
Javier Lopez Tomas

Reputation: 2342

Decrypting environmental variables in AWS Lambda not working in Python 3.6

I have encrypted an environmental variable in an AWS Lambda function with an AWS KMS. Then I have tried to decrypt the variable in code using the example code that AWS provides, which adapted to my variable is the following:

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

I have tested the function but it throw out the next error:

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

However, switching Lambda from Python 3.6 to Python 3.7 make it works perfectly. Is there any way to solve it so that I do not have to change my python version?

Upvotes: 2

Views: 995

Answers (1)

scomes
scomes

Reputation: 1846

You could try the following. It just makes sure the function is returning a string, which is JSON serializable instead of bytes, which are not.

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

Upvotes: 1

Related Questions