AWS Lambda Functions - Read and Write Environment Variables

It turns out we can update an AWS Lambda Function’s environment variables quite easily using the AWS SDK, allowing us to use it for storing and updating a value for use within our Lambda code.

In this sample Python function, I set an environment variable for my Lambda Function, called id.

"id" : "100"

In the Lambda Function’s code I can read the id environment variable, convert it to an integer, increase it by 100, and then write it back to the Lambda Function’s Configuration. You must add your Lambda Function’s ARN in the FunctionName value.

import boto3, os

client = boto3.client('lambda')


def lambda_handler(event, context):
    id = int(os.getenv('id'))
    
    id = id + 100
    
    client.update_function_configuration(
        FunctionName='{Lambda ARN}',
        Environment={
            'Variables': {
                'id': str(id)
            }
        }
    )
    
    return id

I have no doubt the sample Python function is frowned upon in many, many ways, but if you were wondering how to read and write environment variables in AWS Lambda Functions, this is one example.

It’s important to note that updating a Lambda Function’s configuration requires additional permissions. Per the documentation, the operation requires permission for the lambda:UpdateFunctionConfiguration action.