Usage
Schema Definition
Define a Pydantic model for your environment variables:
| schema.py |
|---|
1
2
3
4
5
6
7
8
9
10
11
12 | from typing import Literal
from pydantic import BaseModel, Field, HttpUrl
from aws_lambda_env_modeler.types import Annotated
class MyEnvVariables(BaseModel):
REST_API: HttpUrl
ROLE_ARN: Annotated[str, Field(min_length=20, max_length=2048)]
POWERTOOLS_SERVICE_NAME: Annotated[str, Field(min_length=1)]
LOG_LEVEL: Literal['DEBUG', 'INFO', 'ERROR', 'CRITICAL', 'WARNING', 'EXCEPTION']
|
Notice how you can use advanced types and value assertions and not just plain strings.
Decorator
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.
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.
| my_handler.py |
|---|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26 | import json
from http import HTTPStatus
from typing import Any, Dict, Literal
from pydantic import BaseModel, Field, HttpUrl
from aws_lambda_env_modeler import get_environment_variables, init_environment_variables
from aws_lambda_env_modeler.types import Annotated
class MyHandlerEnvVars(BaseModel):
REST_API: HttpUrl
ROLE_ARN: Annotated[str, Field(min_length=20, max_length=2048)]
POWERTOOLS_SERVICE_NAME: Annotated[str, Field(min_length=1)]
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.REST_API, env_vars.ROLE_ARN as dataclass
return {
'statusCode': HTTPStatus.OK,
'headers': {'Content-Type': 'application/json'},
'body': json.dumps({'message': 'success'}),
}
|