AWS Lambda Environment Variables Modeler (Python)
AWS-Lambda-Env-Modeler is a Python library designed to simplify the process of managing and validating environment variables in your AWS Lambda functions.
It leverages the power of Pydantic models to define the expected structure and types of the environment variables.
This library is especially handy for serverless applications where managing configuration via environment variables is a common practice.
Contact details | ran.isenberg@ranthebuilder.cloud
The Problem
Environment variables are often viewed as an essential utility. They serve as static AWS Lambda function configuration.
Their values are set during the Lambda deployment, and the only way to change them is to redeploy the Lambda function with updated values.
However, many engineers use them unsafely despite being such an integral and fundamental part of any AWS Lambda function deployment.
This usage may cause nasty bugs or even crashes in production.
This library allows you to correctly parse, validate, and use your environment variables in your Python AWS Lambda code.
Read more about it in the AWS Lambda environment variables article on the Ran The Builder website.
Features
- Validates the environment variables against a Pydantic model: define both semantic and syntactic validation.
- Parses the string environment variables into complex classes and types.
- Provides means to access the environment variables safely with a global getter function in every part of the function.
- Provides a decorator to initialize the environment variables before executing a function.
- Caches the parsed model for performance improvement for multiple 'get' calls.
Installation
Supported Python versions: 3.11, 3.12, 3.13, 3.14 and 3.15. Python 3.10 is no longer supported, as it is deprecated. See the AWS Lambda runtimes page for further information.
You can install it using pip:
pip install aws-lambda-env-modeler
or uv:
uv add aws-lambda-env-modeler
Getting started
Head over to the complete documentation at https://ran-isenberg.github.io/aws-lambda-env-modeler
Usage
First, define a Pydantic model for your environment variables:
from pydantic import BaseModel, HttpUrl
class MyEnvVariables(BaseModel):
DB_HOST: str
DB_PORT: int
DB_USER: str
DB_PASS: str
FLAG_X: bool
API_URL: HttpUrl
Before executing a function, you must use the @init_environment_variables decorator to validate and initialize the environment variables automatically.
The decorator guarantees that the function will run with the correct variable configuration.
from aws_lambda_env_modeler import init_environment_variables
@init_environment_variables(model=MyEnvVariables)
def my_handler_entry_function(event, context):
# At this point, environment variables are already validated and initialized
pass
Then, you can fetch the environment variables using the global getter function, 'get_environment_variables,' and use them just like a data class. At this point, they are parsed and validated.
from aws_lambda_env_modeler import get_environment_variables
env_vars = get_environment_variables(model=MyEnvVariables)
print(env_vars.DB_HOST)
Disabling Cache for Testing
By default, the modeler uses cache - the parsed model is cached for performance improvement for multiple 'get' calls.
In some cases, such as during testing, you may want to turn off the cache. You can do this by setting the LAMBDA_ENV_MODELER_DISABLE_CACHE environment variable to true.
This is especially useful in tests where each test sets a different set of environment variables for the same model.
Here's an example of how you can use this in a pytest test:
import json
from http import HTTPStatus
from typing import Any, Dict, Literal
from unittest.mock import patch
from pydantic import BaseModel
from aws_lambda_env_modeler import LAMBDA_ENV_MODELER_DISABLE_CACHE, get_environment_variables, init_environment_variables
class MyHandlerEnvVars(BaseModel):
LOG_LEVEL: Literal['DEBUG', 'INFO', 'ERROR', 'CRITICAL', 'WARNING', 'EXCEPTION']
@init_environment_variables(model=MyHandlerEnvVars)
def my_handler(event: Dict[str, Any], context) -> Dict[str, Any]:
env_vars = get_environment_variables(model=MyHandlerEnvVars) # noqa: F841
# can access directly env_vars.LOG_LEVEL as dataclass
return {
'statusCode': HTTPStatus.OK,
'headers': {'Content-Type': 'application/json'},
'body': json.dumps({'message': 'success'}),
}
@patch.dict('os.environ', {LAMBDA_ENV_MODELER_DISABLE_CACHE: 'true', 'LOG_LEVEL': 'DEBUG'})
def test_my_handler():
response = my_handler({}, None)
assert response['statusCode'] == HTTPStatus.OK
assert response['headers'] == {'Content-Type': 'application/json'}
assert json.loads(response['body']) == {'message': 'success'}
Code Contributions
Code contributions are welcomed. Read this guide.
Code of Conduct
Read our code of conduct here.
Connect
- Email: ran.isenberg@ranthebuilder.cloud
- Website RanTheBuilder
- LinkedIn: ranisenberg
- Twitter: RanBuilder
- Bluesky: @ranthebuilder.cloud
License
This library is licensed under the MIT License. See the LICENSE file.
Metadata
Release files for aws-lambda-env-modeler 4.0.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| aws_lambda_env_modeler-4.0.0.tar.gz | 8.0 kB | Without provenance | Details for aws_lambda_env_modeler-4.0.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| aws_lambda_env_modeler-4.0.0-py3-none-any.whl | Python 3 | none | any | Details for aws_lambda_env_modeler-4.0.0-py3-none-any.whl |
Total release size: 15.3 kB
Release files / aws_lambda_env_modeler-4.0.0.tar.gz
| Download URL | aws_lambda_env_modeler-4.0.0.tar.gz |
|---|---|
| Size | 8.0 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
91bf20dde1aaf39cb38a957eb63db986a4d843af8eec5487fde4b0925ef0e497
|
|
BLAKE2b-256 checksum How to use checksums |
500de7d339d0ba6d40374b53a61f9097b280efb5869076d4ee3d1abf27690403
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Release files / aws_lambda_env_modeler-4.0.0-py3-none-any.whl
| Download URL | aws_lambda_env_modeler-4.0.0-py3-none-any.whl |
|---|---|
| Size | 7.3 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
a63d5e25623d65cd127fa062ad32701797a45781f6892e4c5b73d5825421508b
|
|
BLAKE2b-256 checksum How to use checksums |
4057471716543b61ee6714017dcecdfaf55e3a024ecee140aecdeafce8e33e6a
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Security for aws-lambda-env-modeler 4.0.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.