|
| 1 | +from typing import Dict |
| 2 | + |
| 3 | +import pydantic |
| 4 | +import yaml |
| 5 | +from pydantic_core.core_schema import FieldValidationInfo |
| 6 | +from pydantic_settings import BaseSettings, SettingsConfigDict |
| 7 | + |
| 8 | + |
| 9 | +class AppConfig(BaseSettings): |
| 10 | + model_config = SettingsConfigDict( |
| 11 | + env_file=".env" |
| 12 | + ) |
| 13 | + aws_default_account: str = pydantic.Field( |
| 14 | + description="AWS account ID" |
| 15 | + ) |
| 16 | + project_id: str = pydantic.Field( |
| 17 | + description="Project ID", default="eoapi-cdk" |
| 18 | + ) |
| 19 | + stage: str = pydantic.Field(description="Stage of deployment", default="test") |
| 20 | + # because of its validator, `tags` should always come after `project_id` and `stage` |
| 21 | + tags: Dict[str, str] | None = pydantic.Field( |
| 22 | + description="""Tags to apply to resources. If none provided, |
| 23 | + will default to the defaults defined in `default_tags`. |
| 24 | + Note that if tags are passed to the CDK CLI via `--tags`, |
| 25 | + they will override any tags defined here.""", |
| 26 | + default=None, |
| 27 | + ) |
| 28 | + db_instance_type: str = pydantic.Field( |
| 29 | + description="Database instance type", default="t3.micro" |
| 30 | + ) |
| 31 | + db_allocated_storage: int = pydantic.Field( |
| 32 | + description="Allocated storage for the database", default=5 |
| 33 | + ) |
| 34 | + |
| 35 | + @pydantic.field_validator("tags") |
| 36 | + def default_tags(cls, v, info: FieldValidationInfo): |
| 37 | + return v or {"project_id": info.data["project_id"], "stage": info.data["stage"]} |
| 38 | + |
| 39 | + def build_service_name(self, service_id: str) -> str: |
| 40 | + return f"{self.project_id}-{self.stage}-{service_id}" |
| 41 | + |
| 42 | + |
| 43 | +def build_app_config() -> AppConfig: |
| 44 | + """Builds the AppConfig object from config.yaml file if exists, |
| 45 | + otherwise use defaults""" |
| 46 | + try: |
| 47 | + with open("config.yaml") as f: |
| 48 | + print("Loading config from config.yaml") |
| 49 | + app_config = yaml.safe_load(f) |
| 50 | + app_config = ( |
| 51 | + {} if app_config is None else app_config |
| 52 | + ) # if config is empty, set it to an empty dict |
| 53 | + app_config = AppConfig(**app_config) |
| 54 | + except FileNotFoundError: |
| 55 | + # if no config at the expected path, using defaults |
| 56 | + app_config = AppConfig() |
| 57 | + |
| 58 | + return app_config |
0 commit comments