How can I access environment variables in python global scope, outside the lambda function itself? In the cdk stack code I can define a function like this for example:
get_games_lambda = PythonFunction(
self,
'GetGamesHandler',
function_name='GetGames',
entry='../server',
runtime=_lambda.Runtime.PYTHON_3_8,
handler='get_games',
index='app.py',
environment={
"rds": 'arn:aws:secretsmanager:...',
}
)
but I want the env var to be accessible in the code that's run in the top of the file where the lambda function is.
app.py file:
from sqlalchemy import create_engine, func, select, and_, text
engine = create_engine(<here I want to access the env variable>)
# the lambda function:
def get_games(event, context):
...
engine = create_engine(<here I want to access the env variable>)
This code will execute once, when Lambda loads your module into a container which will eventually execute your function. You can tell containers from each other, for instance, by looking into their CloudWatch log names.
Per Lambda philosophy, it's not any of your business when and how this global code gets executed, and you should design your functions without any assumptions about it. It should be read-only shared state.
Realistically, it does matter (expensive things like initializing connection pools and similar should go here, so they are executed once per container rather than once per invocation). Lambda invocation involving executing this global code is called "cold start" and there are many clever tricks to make it faster.
That said, this global code has access to the container's environment, the same way the function code does, which is populated with the values from your Lambda function's definition.
If you do something like this:
rds = os.environ['rds']
url = boto3.client('secretsmanager').get_secret_value(SecretId = rds)
engine = create_engine(url)
, it should have access to the variable you previously defined in your construct.
You can check in the AWS console if this value made it to the Lambda's settings after deployment.