'Update an environment variable of an AWS Lambda function in python
I am wanting to update an Environment Variable from an AWS Lambda function. I have tried this code:
import os
def lambda_handler(event, context):
call = os.environ["last_call"]
print (call)
os.environ["last_call"] = "last update now "
print (os.environ["last_call"])
When I reassign the os.environ["last_call"] = "last update now"
, I don't see the environment variable updating.
I know I am missing something. Could you please guide me how can I update the value every time I call the Lambda function?
Solution 1:[1]
It would appear that your objective is to store some information that will be accessible to the Lambda function when the function is next executed.
This can (mostly) be accomplished simply by using a global variable rather than an environment variable. Simply define a variable outside of the handler function and it will be accessible during future executions of the function.
However:
- If the function is executed frequently, AWS Lambda might create multiple containers. The global variable will only operate within one of the containers, so the value will not be accessible for all functions.
- If a function is not used for some time period, the container might be destroyed. This would lose the global variable.
Using an environment variable will have the same issues.
The correct way to make information accessible to future executions of a Lambda function would be to use some form of storage service, such as DynamoDB, Amazon S3 or a database.
Solution 2:[2]
With os.putenv(key, value)
, but with caution:
If the platform supports the
putenv()
function, this mapping may be used to modify the environment as well as query the environment.
Solution 3:[3]
You can use it like this... It worked for me.
import boto3
def lambda_handler(event, context):
client = boto3.client('lambda')
response = client.update_function_configuration(
FunctionName='my-test-lam-1',
Environment={
'Variables': {
'NAME': 'updated_value',
'key2': 'val2'
}
}
)
Solution 4:[4]
environment variables will be used by importing library
import os
variable = os.environ["env-variable"]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | John Rotenstein |
Solution 2 | RomanPerekhrest |
Solution 3 | Tushar De |
Solution 4 | Suraj Rao |