简体   繁体   English

将其他文件部署到 AWS Lambda (Python)

[英]Deploying additional files into AWS Lambda (Python)

I am attempting to upload an additional file containing an encryption secret to AWS Lambda, and am having trouble.我正在尝试将包含加密密钥的附加文件上传到 AWS Lambda,但遇到了问题。 The file is to be read from my Python script and be processed.该文件将从我的 Python 脚本中读取并进行处理。 I have tested this functionality locally, and it works just fine.我在本地测试了这个功能,它工作得很好。

I package and upload the .zip correctly, as AWS has no problems running the script once it uploads.我正确打包并上传了 .zip,因为一旦上传,AWS 运行脚本就没有问题。 However, my code fails at the line that it reads my file, even though it should be in the working directory.但是,我的代码在读取我的文件时失败,即使它应该在工作目录中。

Is it possible to upload a file into the AWS zip deployment, and have it be read by the script?是否可以将文件上传到 AWS zip 部署中,并让脚本读取它?

I was surprised that this did not work, so I did some digging for anyone interest.我很惊讶这不起作用,所以我为任何感兴趣的人做了一些挖掘。

I created a simple function:我创建了一个简单的函数:

import json
import os
import random

def lambda_handler(event, context):
    selection = str(random.randint(1,5))

    with open('mydata.csv') as dogs:
        for l in dogs:
            if selection == l.split(',')[0]:
                random_dog = l.split(',')[2]

    return {
        'statusCode': 200,
        'body': json.dumps('Hello from Lambda!'),
        'cwd': os.getcwd(),
        'ls': os.listdir(),
        'random_dog': random_dog
    }

A data file:一个数据文件:

akc_popularity,year,breed
1,2019,labrador Retriever
2,2019,German Shepherd Dog
3,2019,Golden Retriever
4,2019,French Bulldog
5,2019,Bulldog

Added them to a zip archive:将它们添加到 zip 存档中:

$ zip fileImport.zip importer.py
$ zip fileImport.zip mydata.csv

Created the function:创建函数:

$ aws lambda create-function --function-name fileImport --zip-file fileb://fileImport.zip --handler importer.lambda_handler --runtime python3.8 --role arn:aws:iam::***************:role/Lambda_StackExchange

Triggered the function:触发函数:

$ aws lambda invoke --function-name fileImport output.json
{
    "StatusCode": 200,
    "ExecutedVersion": "$LATEST"
}
$ jq . output.json
{
  "statusCode": 200,
  "body": "\"Hello from Lambda!\"",
  "cwd": "/var/task",
  "ls": [
    "importer.py",
    "mydata.csv"
  ],
  "random_dog": "Bulldog\n"
}

So, please share some code so we can dive in!所以,请分享一些代码,以便我们深入研究! FYI...I would highly recommend storing secrets using AWS Secrets Manager .仅供参考...我强烈建议使用AWS Secrets Manager存储机密。 It is very easy to use and keeps your hardcoded secrets out of things like version control systems.它非常易于使用,并且可以将您的硬编码秘密置于版本控制系统之类的东西之外。 Additionally, changing your secret will not require a redeployment of your function.此外,更改您的密钥不需要重新部署您的函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM