Skip to content

Instantly share code, notes, and snippets.

@olafurnielsen
Created January 23, 2024 14:59
Show Gist options
  • Select an option

  • Save olafurnielsen/60f3d8534dfea5007b6ccbf290457f43 to your computer and use it in GitHub Desktop.

Select an option

Save olafurnielsen/60f3d8534dfea5007b6ccbf290457f43 to your computer and use it in GitHub Desktop.
Typed Python Pulumi stack config schemas + automatic config loading
# As our Pulumi code base grew we realized we were passing the same
# configuration values to functions over and over again, with little
# or no standardization on parameter names etc.
# We also felt that the code became quite verbose and complex with
# Config.get_x() statements
# So we created a StackConfig base dataclass defining parameters that we require
# for all deployment stacks, and are used as input on functions responsible for
# deploying Pulumi resources
@dataclass(kw_only=True, frozen=True)
class StackConfig():
workload_name: str
env: str
location: Annotated[str, "azure-native"]
tags: Optional[Dict[str, str]] = field(compare=False, default_factory=lambda: {})
resource_group_name: Optional[str] = None
# And as we wanted to standardize the way we loaded stack configurations
# and get rid of the mismatch in how different Pulumi projects loaded their config
# So we created a (kinda crazy) config loader which inspects a dataclass schema
# and uses relevant pulumi.Config getter function based on the input type
# Type inspections are still somewhat hacky in Python and there is probably a better
# way to do this but this is what we came up with:
@dataclass
class Confy:
dataclass_obj: Any
@staticmethod
def field_type(field_type: Any) -> Type:
# Unwrap Optional[]
field_type = (
field_type.__args__[0] if field_type == Optional[field_type] else field_type
)
# Unwrap Annotated[]
field_type = (
get_args(field_type)[0]
if get_origin(field_type) is Annotated
else field_type
)
if field_type in [str, int, bool]:
return field_type
if is_subhint(field_type, dict | list | tuple):
return Collection
raise ValueError(f"Unsupported field data type: {field_type}")
@staticmethod
def is_azure_native(field_type: Any) -> bool:
if field_type == Optional[field_type]:
field_type = field_type.__args__[0]
return get_origin(field_type) is Annotated and "azure-native" in get_args(
field_type
)
@staticmethod
def is_secret(field_type: Any) -> bool:
if field_type == Optional[field_type]:
field_type = field_type.__args__[0]
return get_origin(field_type) is Annotated and "secret" in get_args(field_type)
@staticmethod
def is_optional(field_type: Any) -> bool:
return field_type == Optional[field_type]
@classmethod
def config_getter_func(
cls,
dcfield: Field,
config: pulumi.Config,
) -> Callable:
is_optional = cls.is_optional(dcfield.type)
is_secret: bool = cls.is_secret(dcfield.type)
field_type = cls.field_type(dcfield.type)
getter_func_name: str = "get" if is_optional else "require"
if is_secret:
getter_func_name += "_secret"
if field_type is Collection:
getter_func_name += "_object"
elif field_type is bool:
getter_func_name += "_bool"
elif field_type is int:
getter_func_name += "_int"
elif field_type is str:
pass
else:
raise ValueError(f"Unsupported config getter for field type: {field_type}")
if hasattr(config, getter_func_name):
return getattr(config, getter_func_name)
raise ValueError(
f"Could not find getter function {getter_func_name} in pulumi.Config"
)
@staticmethod
def default_value(dcfield: Field) -> Any:
if dcfield.default_factory is not MISSING:
return dcfield.default_factory()
if dcfield.default is not MISSING:
return dcfield.default
return None
@staticmethod
def field_info(dcfield: Field) -> Dict[str, Any]:
return {
"name": dcfield.name,
"type": dcfield.type,
"default_factory": dcfield.default_factory,
"default": dcfield.default,
}
def __post_init__(self) -> None:
if not is_dataclass(self.dataclass_obj):
raise ValueError("dataclass_type must be a dataclass type")
self.dckwargs: dict[str, Any] = {}
self.pulumi_config = pulumi.Config()
self.pulumi_azure_config = pulumi.Config("azure-native")
# Returns the same type as the dataclass_type
def populate(self) -> Any:
for dcfield in fields(self.dataclass_obj):
config_instance = (
self.pulumi_azure_config
if self.is_azure_native(dcfield.type)
else self.pulumi_config
)
getter_func = self.config_getter_func(
dcfield=dcfield,
config=config_instance,
)
field_value = getter_func(dcfield.name) or self.default_value(dcfield)
self.dckwargs.update({dcfield.name: field_value})
return self.dataclass_obj(**self.dckwargs)
# And for independent Pulumi project modules we'd define a configuration schema
# with required and optional configuration options
@dataclass(kw_only=True, frozen=True)
class LandingZoneConfig(StackConfig):
# Including the StackConfig attributes...
# workload_name: str
# env: str
# location: Annotated[str, "azure-native"]
# tags: Optional[Dict[str, str]] = field(compare=False, default_factory=lambda: {})
# resource_group_name: Optional[str] = None
tags: Optional[Dict[str, str]] = None
cr_ip_allow_list: Optional[List[str]] = field(default_factory=list)
cr_public_network_access: Optional[str] = field(
default=containerregistry.PublicNetworkAccess.DISABLED
)
# And then the stack config can be populated automatically
# (See config_loader.py below)
config: LandingZoneConfig = Confy(LandingZoneConfig).populate()
# Basically.. types will dictate which pulumi.Config getter is used...
# supporting get, require and secret for str, int, bool, dict, list, tuple etc.
# key: str => Config.require()
# key: Optional[str] => Config.get()
# key: Optional[str] = "default value" => Config.get() or key.default_value,
# key: dict|list|tuple => Config.require_object
# etc...
# And getting any config value as a secret is also supported
# secret_key: Annotated[str, "secret"] => Config.require_secret()
# And because the type inspection felt hacky we created tests for all
# the supported parameter types, to have some confidence in this..
import json
from dataclasses import Field, dataclass, field, fields
from typing import Annotated, Any, Collection, Optional
import pulumi
import pytest
from orbitcloud_graviton.az_lib import Confy, StackConfig
from orbitcloud_graviton.pulumi_mocks import set_mocks
@pytest.fixture(scope="module")
def pulumi_project_mock():
set_mocks(
{
"azure-native:location": "northeurope",
"mock-project:workload_name": "test-workload",
"mock-project:env": "dev",
"mock-project:some_other_string": "some_other_value",
"mock-project:some_other_int": 5,
"mock-project:tags": json.dumps({"test-tag": "test-value"}),
}
)
@dataclass(kw_only=True)
class DummyDataclass:
string_field: str
string_field_with_default: str = "default"
string_field_optional: Optional[str] = None
string_field_optional_with_default: Optional[str] = "default"
int_field: int
int_field_with_default: int = 1
int_field_optional: Optional[int] = None
int_field_optional_with_default: Optional[int] = 1
bool_field: bool
bool_field_with_default: bool = True
bool_field_optional: Optional[bool] = None
bool_field_optional_with_default: Optional[bool] = True
dict_field: dict
dict_field_with_default: dict = field(default_factory=lambda: {})
dict_field_optional: Optional[dict] = None
dict_field_optional_with_default: Optional[dict] = field(default_factory=lambda: {})
list_field: list
list_field_with_default: list = field(default_factory=lambda: [])
list_field_optional: Optional[list] = None
list_field_optional_with_default: Optional[list] = field(default_factory=lambda: [])
tuple_field: tuple
tuple_field_with_default: tuple = field(default_factory=lambda: ())
tuple_field_optional: Optional[tuple] = None
tuple_field_optional_with_default: Optional[tuple] = field(
default_factory=lambda: ()
)
secret_str_field: Annotated[str, "secret"]
secret_str_field_with_default: Annotated[str, "secret"] = "default"
secret_str_field_optional: Optional[Annotated[str, "secret"]] = None
secret_str_field_optional_with_default: Optional[
Annotated[str, "secret"]
] = "default"
secret_int_field: Annotated[int, "secret"]
secret_int_field_with_default: Annotated[int, "secret"] = 1
secret_int_field_optional: Optional[Annotated[int, "secret"]] = None
secret_int_field_optional_with_default: Optional[Annotated[int, "secret"]] = 1
secret_bool_field: Annotated[bool, "secret"]
secret_bool_field_with_default: Annotated[bool, "secret"] = True
secret_bool_field_optional: Optional[Annotated[bool, "secret"]] = None
secret_bool_field_optional_with_default: Optional[Annotated[bool, "secret"]] = True
secret_dict_field: Annotated[dict, "secret"]
secret_dict_field_with_default: Annotated[dict, "secret"] = field(
default_factory=lambda: {}
)
secret_dict_field_optional: Optional[Annotated[dict, "secret"]] = None
secret_dict_field_optional_with_default: Optional[
Annotated[dict, "secret"]
] = field(default_factory=lambda: {})
azure_native_str_field: Annotated[str, "azure-native"]
azure_native_str_field_with_default: Annotated[str, "azure-native"] = "default"
azure_native_str_field_optional: Optional[Annotated[str, "azure-native"]] = None
azure_native_str_field_optional_with_default: Optional[
Annotated[str, "azure-native"]
] = "default"
@pytest.fixture(scope="module")
def config_fields() -> dict[str, Field[Any]]:
dcfields_dict: dict[str, Field[Any]] = {
dcfield.name: dcfield for dcfield in fields(DummyDataclass)
}
return dcfields_dict
@pulumi.runtime.test
@pytest.mark.usefixtures("pulumi_project_mock")
def test_confy_stack() -> None:
@dataclass(kw_only=True, frozen=True)
class TestBaseConfig(StackConfig):
resource_group_name: Optional[str] = "test-resource-group"
some_other_string: str
some_other_int: int = 1
some_other_optional_int: Optional[int] = 1
stack_config: TestBaseConfig = Confy(dataclass_obj=TestBaseConfig).populate()
assert stack_config.workload_name == "test-workload"
assert stack_config.env == "dev"
# assert stack_config.tags == {"test-tag": "test-value"}
assert stack_config.resource_group_name == "test-resource-group"
assert stack_config.some_other_string == "some_other_value"
assert stack_config.some_other_optional_int == 1
@pytest.mark.usefixtures("config_fields")
def test_config_getter_func_strings(request) -> None:
dcfields = request.getfixturevalue("config_fields")
config = pulumi.Config()
for field_name, config_func in [
("string_field", config.require),
("string_field_with_default", config.require),
("string_field_optional", config.get),
("string_field_optional_with_default", config.get),
]:
assert (
Confy.config_getter_func(dcfield=dcfields[field_name], config=config)
== config_func
)
@pytest.mark.usefixtures("config_fields")
def test_config_getter_func_ints(request) -> None:
dcfields = request.getfixturevalue("config_fields")
config = pulumi.Config()
for field_name, config_func in [
("int_field", config.require_int),
("int_field_with_default", config.require_int),
("int_field_optional", config.get_int),
("int_field_optional_with_default", config.get_int),
]:
assert (
Confy.config_getter_func(dcfield=dcfields[field_name], config=config)
== config_func
)
@pytest.mark.usefixtures("config_fields")
def test_config_getter_func_bools(request) -> None:
dcfields = request.getfixturevalue("config_fields")
config = pulumi.Config()
for field_name, config_func in [
("bool_field", config.require_bool),
("bool_field_with_default", config.require_bool),
("bool_field_optional", config.get_bool),
("bool_field_optional_with_default", config.get_bool),
]:
assert (
Confy.config_getter_func(dcfield=dcfields[field_name], config=config)
== config_func
)
@pytest.mark.usefixtures("config_fields")
def test_field_is_bool(request) -> None:
dcfields = request.getfixturevalue("config_fields")
for field_name in [
"bool_field",
"bool_field_with_default",
"bool_field_optional",
"bool_field_optional_with_default",
]:
assert Confy.field_type(field_type=dcfields[field_name].type) is bool
@pytest.mark.usefixtures("config_fields")
def test_field_is_int(request) -> None:
dcfields = request.getfixturevalue("config_fields")
for field_name in [
"int_field",
"int_field_with_default",
"int_field_optional",
"int_field_optional_with_default",
]:
assert Confy.field_type(field_type=dcfields[field_name].type) is int
@pytest.mark.usefixtures("config_fields")
def test_field_is_collection(request) -> None:
dcfields = request.getfixturevalue("config_fields")
for field_name in dcfields.keys():
if dcfields[field_name].name.startswith(("dict", "list", "tuple")):
assert Confy.field_type(field_type=dcfields[field_name].type) is Collection
@pytest.mark.usefixtures("config_fields")
def test_field_is_secret(request) -> None:
dcfields = request.getfixturevalue("config_fields")
for field_name in dcfields.keys():
if field_name.startswith("secret"):
assert Confy.is_secret(field_type=dcfields[field_name].type)
@pytest.mark.usefixtures("config_fields")
def test_config_getter_func_dicts(request) -> None:
dcfields = request.getfixturevalue("config_fields")
config = pulumi.Config()
for field_name, config_func in [
("dict_field", config.require_object),
("dict_field_with_default", config.require_object),
("dict_field_optional", config.get_object),
("dict_field_optional_with_default", config.get_object),
]:
assert (
Confy.config_getter_func(dcfield=dcfields[field_name], config=config)
== config_func
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment