-
-
Notifications
You must be signed in to change notification settings - Fork 125
Description
I saw that you support serializing a BaseSettings instance to cli arguments, and wondered if something like this could also be supported for environment values.
The are probably lots of details to consider:
- should revealing
SecretStrrequire an explicit flag similar tosqlalchemy.URL.render_as_string? - should primitives like numbers be automatically converted to strings, since env vars values are always strings?
- Is this best done as a method on
EnvSettingsSource, a global function, or a utility class likeCliApp? - probably more I cannot think of right now
I mostly opened this issue to start the discussion and see if there you'd be open for this functionality.
Motivation
Mostly infrastructure as code. E.g. when constructing Lambdas or Fargate tasks the AWS CDK, you can pass a dictionary of environment variables. Would be really cool if one could configure the env vars type safe in CDK at deploy time, then serialize from environment variables. Probably similar use cases exist for other IaC tools like Pulumi.
Example
from pydantic import SecretStr, BaseModel, Field
from pydantic_settings import BaseSettings, EnvSettingsSource
class Nested(BaseModel):
nested_property: str
class MySettings(BaseSettings):
regular_property: int
secret_property: SecretStr
aliased_property: str = Field(alias="aliased")
nested_object: Nested
settings = MySettings(
regular_property=123,
secret_property="s3cr3t",
aliased_property="i am aliased",
nested_object=Nested(nested_property="i am nested")
)
env_var_dict = somehow_serialize_to_env_var_dict(settings)
"""
{
"REGULAR_PROPERTY": "123",
"SECRET_PROPERTY": "s3cr3t",
"ALIASED": "i am aliased",
"NESTED_OBJECT__NESTED_PROPERTY": "i am nested"
}
"""if we'd then set environment variables based on env_var_dict
import os
for key, value in env_var_dict.values():
os.environ[key] = value
assert MySettings() == settingsthe generated settings based on env vars would be the same as the "manually defined" ones.