Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
316 views
in Technique[技术] by (71.8m points)

python - AWS Lambda read contents of file in zip uploaded as source code

I have two files:

MyLambdaFunction.py

config.json

I zip those two together to create MyLambdaFunction.zip. I then upload that through the AWS console to my lambda function.

The contents of config.json are various environmental variables. I need a way to read the contents of the file each time the lambda function runs, and then use the data inside to set run time variables.

How do I get my Python Lambda function to read the contents of a file, config.json, that was uploaded in the zip file with the source code?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Figured it out with the push in the right direction from @helloV.

At the top of the python file put import os

Inside your function handler put the following:

configPath = os.environ['LAMBDA_TASK_ROOT'] + "/config.json"
print("Looking for config.json at " + configPath)
configContents = open(configPath).read()
configJson = json.loads(configContents)
environment = configJson['environment']
print("Environment: " + environment)

That bit right there, line by line, does the following:

  • Get the path where the config.json file is stored
  • Print that path for viewing in CloudWatch logs
  • Open the file stored at that path, read the contents
  • Load the contents to a json object for easy navigating
  • Grab the value of one of the variables stored in the json
  • Print that for viewing in the CloudWatch logs

Here is what the config.json looks like:

{
    "environment":"dev"
}

EDIT AWS lambda now supports use of environmental variables directly in the console UI. So if your use case is the same as mine (i.e. for a config file) you no longer need a config file.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...