如何从 Python 访问 AWS Lambda 环境变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40937512/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 00:13:13  来源:igfitidea点击:

How to access an AWS Lambda environment variable from Python

pythonaws-lambda

提问by keybits

Using the new environment variable support in AWS Lambda, I've added an env var via the webui for my function.

使用AWS Lambda 中的新环境变量支持,我通过 webui 为我的函数添加了一个环境变量

How do I access this from Python? I tried:

我如何从 Python 访问它?我试过:

import os

MY_ENV_VAR = os.environ['MY_ENV_VAR']

but my function stopped working (if I hard code the relevant value for MY_ENV_VARit works fine).

但我的函数停止工作(如果我硬编码相关值,MY_ENV_VAR它工作正常)。

回答by SkyWalker

AWS Lambda environment variables can be defined using the AWS Console, CLI, or SDKs. This is how you would define an AWS Lambda that uses an LD_LIBRARY_PATH environment variable using AWS CLI:

可以使用 AWS 控制台、CLI 或开发工具包定义 AWS Lambda 环境变量。这是您使用 AWS CLI 定义使用 LD_LIBRARY_PATH 环境变量的 AWS Lambda 的方式:

aws lambda create-function \
  --region us-east-1
  --function-name myTestFunction
  --zip-file fileb://path/package.zip
  --role role-arn
  --environment Variables={LD_LIBRARY_PATH=/usr/bin/test/lib64}
  --handler index.handler
  --runtime nodejs4.3
  --profile default

Once created, environment variables can be read using the support your language provides for accessing the environment, e.g. using process.env for Node.js. When using Python, you would need to import the os library, like in the following example:

创建后,可以使用您的语言为访问环境提供的支持来读取环境变量,例如使用 node.js 的 process.env。使用 Python 时,您需要导入 os 库,如下例所示:

...
import os
...
print("environment variable: " + os.environ['variable'])

Resource Link:

资源链接:

AWS Lambda Now Supports Environment Variables

AWS Lambda 现在支持环境变量





Assuming you have created the .env file along-side your settings module.

假设您已经在设置模块旁边创建了 .env 文件。

.
├── .env
└── settings.py

Add the following code to your settings.py

将以下代码添加到您的 settings.py

# settings.py
from os.path import join, dirname
from dotenv import load_dotenv

dotenv_path = join(dirname(__file__), '.env')
load_dotenv(dotenv_path)

Alternatively, you can use find_dotenv() method that will try to find a .env file by (a) guessing where to start using fileor the working directory -- allowing this to work in non-file contexts such as IPython notebooks and the REPL, and then (b) walking up the directory tree looking for the specified file -- called .env by default.

或者,您可以使用 find_dotenv() 方法,该方法将尝试通过 (a) 猜测从哪里开始使用文件或工作目录来查找 .env 文件——允许它在非文件上下文中工作,例如 IPython 笔记本和 REPL ,然后 (b) 沿着目录树向上查找指定的文件 - 默认情况下称为 .env 。

from dotenv import load_dotenv, find_dotenv
load_dotenv(find_dotenv())

Now, you can access the variables either from system environment variable or loaded from .env file.

现在,您可以从系统环境变量或从 .env 文件中访问变量。

Resource Link:

资源链接:

https://github.com/theskumar/python-dotenv

https://github.com/theskumar/python-dotenv





gepoggio answered in this post: https://github.com/serverless/serverless/issues/577#issuecomment-192781002

gepoggio 在这篇文章中回答:https: //github.com/serverless/serverless/issues/577#issuecomment-192781002

A workaround is to use python-dotenv: https://github.com/theskumar/python-dotenv

import os
import dotenv

dotenv.load_dotenv(os.path.join(here, "../.env"))
dotenv.load_dotenv(os.path.join(here, "../../.env"))

It tries to load it twice because when ran locally it's in project/.env and when running un Lambda the .env is located in project/component/.env

一种解决方法是使用 python-dotenv:https: //github.com/theskumar/python-dotenv

import os
import dotenv

dotenv.load_dotenv(os.path.join(here, "../.env"))
dotenv.load_dotenv(os.path.join(here, "../../.env"))

它尝试加载两次,因为在本地运行时它位于 project/.env 中,而在运行 un Lambda 时,.env 位于 project/component/.env

回答by Daniel Cortés

I used this code; it includes both cases, setting the variable from the handler and setting it from outside the handler.

我使用了这段代码;它包括两种情况,从处理程序设置变量和从处理程序外部设置它。

#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Trying new lambda stuff"""
import os
import configparser

class BqEnv(object):
    """Env and self variables settings"""
    def __init__(self, service_account, configfile=None):
        config = self.parseconfig(configfile)
        self.env = config
        self.service_account = service_account

    @staticmethod
    def parseconfig(configfile):
        """Connection and conf parser"""
        config = configparser.ConfigParser()
        config.read(configfile)
        env = config.get('BigQuery', 'env')
        return env

    def variable_tests(self):
        """Trying conf as a lambda variable"""
        my_env_var = os.environ['MY_ENV_VAR']
        print my_env_var
        print self.env
        return True

def lambda_handler(event, context):
    """Trying env variables."""
    print event
    configfile = os.environ['CONFIG_FILE']
    print configfile
    print type(str(configfile))
    bqm = BqEnv('some-json.json', configfile)
    bqm.variable_tests()
    return True

I tried this with a demo config file that has this:

我使用具有以下内容的演示配置文件进行了尝试:

[BigQuery]
env = prod

And the setting on lambda was the following: env variables

lambda 上的设置如下: 环境变量

Hope this can help!

希望这可以帮助!

回答by Nicolò Gasparini

Both

两个都

import os
os.getenv('MY_ENV_VAR')

And

os.environ['MY_ENV_VAR']

are feasible solutions, just make sure in the lambda GUI that the ENV variables are actually there.

是可行的解决方案,只需确保在 lambda GUI 中 ENV 变量实际上存在。