Skip to content

Project Configuration

Project configuration classes and settings.

config

Project configuration models for CDK applications.

This module provides Pydantic models for defining project, stage, and pipeline configurations for CDK applications.

Classes

EnvVarStr

Bases: str

String type that expands environment variables on validation.

Automatically expands $VAR and ${VAR} patterns when validated.

Functions
__get_validators__ classmethod
__get_validators__()

Yield validators for Pydantic.

Yields:

Type Description

The validate method.

Source code in src/aibs_informatics_cdk_lib/project/config.py
@classmethod
def __get_validators__(cls):
    """Yield validators for Pydantic.

    Yields:
        The validate method.
    """
    yield cls.validate
validate classmethod
validate(v)

Validate and expand environment variables.

Parameters:

Name Type Description Default
v

The value to validate.

required

Returns:

Type Description

The expanded string, or None.

Raises:

Type Description
TypeError

If value is not a string.

Source code in src/aibs_informatics_cdk_lib/project/config.py
@classmethod
def validate(cls, v):
    """Validate and expand environment variables.

    Args:
        v: The value to validate.

    Returns:
        The expanded string, or None.

    Raises:
        TypeError: If value is not a string.
    """
    if v is not None and not isinstance(v, str):
        raise TypeError("string required")
    return expandvars(v, "", False) if v else v

Env

Bases: BaseModel

Environment configuration model.

Attributes:

Name Type Description
env_type EnvType

The environment type (dev, prod, etc.).

label Optional[str]

Optional label for the environment.

account Optional[str]

AWS account ID.

region Optional[str]

AWS region.

Attributes
env_name property
env_name: str

Get the environment name.

Returns:

Type Description
str

The environment type value as a string.

env_base property
env_base: EnvBase

Get the environment base identifier.

Returns:

Type Description
EnvBase

EnvBase in format [-].

is_configured property
is_configured: bool

Check if the environment has an AWS account configured.

Returns:

Type Description
bool

True if account is set, False otherwise.

Functions
to_env_var_map
to_env_var_map() -> MutableMapping[str, str]

Convert to environment variable mapping.

Returns:

Type Description
MutableMapping[str, str]

Dictionary of environment variable names to values.

Source code in src/aibs_informatics_cdk_lib/project/config.py
def to_env_var_map(self) -> MutableMapping[str, str]:
    """Convert to environment variable mapping.

    Returns:
        Dictionary of environment variable names to values.
    """
    return remove_null_values(
        dict(
            [
                (ENV_TYPE_KEY, self.env_type),
                (ENV_LABEL_KEY, self.label),
                (ENV_BASE_KEY, self.env_base),
            ]
        ),  # type: ignore
        in_place=True,
    )

CodePipelineBuildConfig

Bases: BaseModel

Configuration for CodePipeline build settings.

Attributes:

Name Type Description
ssh_key_secret_name str

Name of the secret containing SSH key.

docker_hub_credentials_secret_name str

Name of the secret with Docker Hub credentials.

CodePipelineSourceConfig

Bases: BaseModel

Configuration for CodePipeline source settings.

Attributes:

Name Type Description
repository str

The source repository.

branch str

The branch to build from.

codestar_connection Optional[UniqueIDType]

CodeStar connection ARN.

oauth_secret_name Optional[str]

Name of OAuth secret.

Note

Either codestar_connection or oauth_secret_name must be set.

CodePipelineNotificationsConfig

Bases: BaseModel

Configuration for CodePipeline notifications.

Attributes:

Name Type Description
slack_channel_configuration_arn Optional[str]

ARN of Slack channel.

notify_on_failure bool

Send notification on failure.

notify_on_success bool

Send notification on success.

Attributes
notify_on_any property
notify_on_any: bool

Check if any notifications are enabled.

Returns:

Type Description
bool

True if either failure or success notifications are enabled.

PipelineConfig

Bases: BaseModel

Complete pipeline configuration.

Attributes:

Name Type Description
enable bool

Whether the pipeline is enabled.

build CodePipelineBuildConfig

Build configuration.

source CodePipelineSourceConfig

Source configuration.

notifications CodePipelineNotificationsConfig

Notification settings.

GlobalConfig

Bases: BaseModel

Global project configuration.

Attributes:

Name Type Description
pipeline_name str

Name of the pipeline.

stage_promotions Dict[EnvType, EnvType]

Stage promotion mappings.

StageConfig

Bases: BaseModel

Configuration for a deployment stage.

Attributes:

Name Type Description
env Env

Environment configuration.

pipeline Optional[PipelineConfig]

Optional pipeline configuration.

BaseProjectConfig

Bases: BaseModel, Generic[G, S]

Base class for project configuration.

Generic base class that can be subclassed with custom global and stage config types.

Attributes:

Name Type Description
global_config G

Global configuration settings.

default_config S

Default stage configuration.

default_config_overrides Dict[EnvType, dict]

Per-environment overrides.

Functions
get_global_config_cls classmethod
get_global_config_cls() -> type[G]

Get the global config class type.

Returns:

Type Description
type[G]

The GlobalConfig type used by this project config.

Source code in src/aibs_informatics_cdk_lib/project/config.py
@classmethod
def get_global_config_cls(cls) -> type[G]:
    """Get the global config class type.

    Returns:
        The GlobalConfig type used by this project config.
    """
    return cls.model_fields["global_config"].annotation  # type: ignore
get_stage_config_cls classmethod
get_stage_config_cls() -> type[S]

Get the stage config class type.

Returns:

Type Description
type[S]

The StageConfig type used by this project config.

Source code in src/aibs_informatics_cdk_lib/project/config.py
@classmethod
def get_stage_config_cls(cls) -> type[S]:
    """Get the stage config class type.

    Returns:
        The StageConfig type used by this project config.
    """
    return cls.model_fields["default_config"].annotation  # type: ignore
get_stage_config
get_stage_config(
    env_type: str | EnvType, env_label: str | None = None
) -> S

Get stage config with environment type overrides.

Parameters:

Name Type Description Default
env_type Union[str, EnvType]

The environment type for the stage config.

required
env_label Optional[str]

Optional environment label override. Defaults to None (no override).

None

Returns:

Type Description
S

A stage config object with applied overrides.

Raises:

Type Description
Exception

If stage config model validation fails.

Source code in src/aibs_informatics_cdk_lib/project/config.py
def get_stage_config(self, env_type: str | EnvType, env_label: str | None = None) -> S:
    """Get stage config with environment type overrides.

    Args:
        env_type (Union[str, EnvType]): The environment type for the stage config.
        env_label (Optional[str]): Optional environment label override.
            Defaults to None (no override).

    Returns:
        A stage config object with applied overrides.

    Raises:
        Exception: If stage config model validation fails.
    """
    try:
        stage_config = self.get_stage_config_cls().model_validate(
            {
                **DeepChainMap(
                    self.default_config_overrides[EnvType(env_type)],
                    self.default_config.model_dump(mode="json", exclude_unset=True),
                ),
            }
        )
    except Exception as e:
        raise e

    if env_label is None:
        return stage_config
    else:
        stage_config.env.label = env_label
        return stage_config
parse_file classmethod
parse_file(path: str | Path, **kwargs) -> Self

Parse configuration from a file.

Parameters:

Name Type Description Default
path Union[str, Path]

Path to the configuration file. Supports YAML and JSON formats.

required

Returns:

Type Description
Self

The parsed project configuration.

Source code in src/aibs_informatics_cdk_lib/project/config.py
@classmethod
def parse_file(cls: type[Self], path: str | Path, **kwargs) -> Self:  # type: ignore[override]
    """Parse configuration from a file.

    Args:
        path (Union[str, Path]): Path to the configuration file.
            Supports YAML and JSON formats.

    Returns:
        The parsed project configuration.
    """
    path = Path(path)

    if path.suffix in (".yml", ".yaml"):
        with open(path) as f:
            return cls.model_validate(yaml.safe_load(f))
    return cls.model_validate_json(json_data=path.read_text())
load_config classmethod
load_config(path: str | Path | None = None) -> P

Load configuration from a file.

Parameters:

Name Type Description Default
path Optional[Union[str, Path]]

Path to config file. If None, searches for project.yaml in current directory.

None

Returns:

Type Description
P

The loaded project configuration.

Raises:

Type Description
AssertionError

If multiple or no project.yaml files found.

Source code in src/aibs_informatics_cdk_lib/project/config.py
@classmethod
def load_config(cls: type[P], path: str | Path | None = None) -> P:
    """Load configuration from a file.

    Args:
        path (Optional[Union[str, Path]]): Path to config file.
            If None, searches for project.yaml in current directory.

    Returns:
        The loaded project configuration.

    Raises:
        AssertionError: If multiple or no project.yaml files found.
    """
    if path is None:
        paths = find_paths(
            Path.cwd(), include_dirs=False, include_files=True, includes=[r".*/project.yaml"]
        )
        assert len(paths) == 1, (
            f"Expected to find exactly one project.yaml file, but found {len(paths)}: {paths}"
        )
        path = paths[0]
    return cls.parse_file(path=path)
load_stage_config classmethod
load_stage_config(
    env_type: str | EnvType, path: str | Path | None = None
) -> S

Load stage configuration for an environment type.

Parameters:

Name Type Description Default
env_type Union[str, EnvType]

The environment type.

required
path Optional[Union[str, Path]]

Path to config file.

None

Returns:

Type Description
S

The stage configuration for the specified environment.

Source code in src/aibs_informatics_cdk_lib/project/config.py
@classmethod
def load_stage_config(
    cls: type["BaseProjectConfig[G, S]"],
    env_type: str | EnvType,
    path: str | Path | None = None,
) -> S:
    """Load stage configuration for an environment type.

    Args:
        env_type (Union[str, EnvType]): The environment type.
        path (Optional[Union[str, Path]]): Path to config file.

    Returns:
        The stage configuration for the specified environment.
    """
    proj_config = cls.load_config(path)
    return proj_config.get_stage_config(env_type=env_type)

ProjectConfig

Bases: BaseProjectConfig[GlobalConfig, StageConfig]

Default project configuration using standard global and stage configs.

ConfigProvider

Utility class for loading stage configurations.

Functions
get_stage_config classmethod
get_stage_config(
    env_type: str | EnvType,
    path: str | Path | None = None,
    project_config_cls: type[
        BaseProjectConfig[G, S]
    ] = ProjectConfig,
) -> S

Get stage configuration for an environment type.

Parameters:

Name Type Description Default
env_type Union[str, EnvType]

The environment type.

required
path Optional[Union[str, Path]]

Path to config file.

None
project_config_cls Type[BaseProjectConfig[G, S]]

Project config class to use. Defaults to ProjectConfig.

ProjectConfig

Returns:

Type Description
S

The stage configuration.

Source code in src/aibs_informatics_cdk_lib/project/config.py
@classmethod
def get_stage_config(
    cls,
    env_type: str | EnvType,
    path: str | Path | None = None,
    project_config_cls: type[BaseProjectConfig[G, S]] = ProjectConfig,  # type: ignore[assignment]
) -> S:
    """Get stage configuration for an environment type.

    Args:
        env_type (Union[str, EnvType]): The environment type.
        path (Optional[Union[str, Path]]): Path to config file.
        project_config_cls (Type[BaseProjectConfig[G, S]]): Project config class
            to use. Defaults to ProjectConfig.

    Returns:
        The stage configuration.
    """
    proj_config = project_config_cls.load_config(path)
    return proj_config.get_stage_config(env_type=env_type)