Skip to content

config

napt.config

Configuration loading and management for NAPT.

Loads and merges YAML configuration in five layers: code defaults, defaults/org.yaml, defaults/vendors/{Vendor}.yaml, the parent recipe, and the recipe.

The loader performs deep merging where dicts are merged recursively and lists/scalars are replaced (last wins). See the Path resolution section of loader for how relative paths resolve.

Modules:

Name Description
loader

The layered configuration loader (load_effective_config).

defaults

Built-in default configuration and the org.yaml template.

napt.config.loader

Configuration loading and merging for NAPT.

This module implements a layered configuration system that allows NAPT to work out of the box while supporting full customization. Each layer wins over the previous one.

Configuration Layers
  1. Code defaults (napt/config/defaults.py)
  2. Built-in defaults that ship with NAPT
  3. Always present; ensures NAPT works without any config files
  4. Provides sensible defaults for all settings

  5. Organization defaults (defaults/org.yaml)

  6. Organization-wide settings
  7. Optional; only loaded if file exists
  8. Customizes settings for your organization

  9. Vendor defaults (defaults/vendors/{Vendor}.yaml)

  10. Vendor-specific settings (e.g., Google-specific settings)
  11. Optional; loaded when the vendor is detected and defaults/org.yaml exists
  12. Wins over organization defaults

  13. Parent recipe (the file named by the recipe's parent field)

  14. Another recipe merged beneath this one
  15. Optional; a parent may not itself declare a parent
  16. Wins over vendor defaults
  17. A parent under upstream/ is a pinned copy: it must match the hash upstream.yaml records, and only app-owned keys are merged (see napt.upstream.pinned)

  18. Recipe configuration (recipes/{Vendor}/{app}.yaml)

  19. App-specific configuration
  20. Always required; defines the app itself
  21. Wins over all other layers
Merge Behavior

The loader performs deep merging with "last wins" semantics:

  • Dicts: Recursively merged (keys from overlay win over base)
  • Lists: Completely replaced (NOT appended/extended)
  • Scalars: Overwritten (strings, numbers, booleans)
  • secrets: Taken from defaults/org.yaml alone; a vendor file, parent, or recipe that declares one fails validation
Path Resolution

Relative paths in two fields are resolved after merging:

  • psadt.brand_pack.path resolves against defaults/ (the recipe directory when no defaults/org.yaml is found).
  • intune.logo_path resolves against the recipe directory, then defaults/ if no file is there.
Dynamic Injection

Some fields are injected at load time, with the provenance layer computed:

  • psadt.app_vars.AppScriptDate: Today's date (YYYY-MM-DD)
  • psadt.app_vars.RequireAdmin: true unless intune.run_as_account is user; a value set in any config layer wins
Error Handling
  • ConfigError: A missing recipe or parent file, a YAML parse error, a file whose top level is not a mapping (in any layer), a parent chain, a pinned parent that is untracked or edited, or a pinned copy run directly
  • All errors are chained with "from err" for better debugging
Note
  • Code defaults are always applied first (NAPT works without config files)
  • The loader walks upward from the recipe to find defaults/org.yaml
  • Organization and vendor defaults are optional; vendor defaults need defaults/org.yaml to be found
  • The vendor is the name of the recipe's directory (recipes/Google/)

LoadedParent dataclass

A parent recipe as the loader hands it to the merge.

Attributes:

Name Type Description
path Path

The resolved parent file.

data dict[str, Any]

Its parsed contents, filtered to the allowed keys when the parent is a pinned copy.

dropped tuple[str, ...]

The dotted names of the keys the filter removed; empty for a local parent.

Source code in napt/config/loader.py
@dataclass(frozen=True)
class LoadedParent:
    """A parent recipe as the loader hands it to the merge.

    Attributes:
        path: The resolved parent file.
        data: Its parsed contents, filtered to the allowed keys when the
            parent is a pinned copy.
        dropped: The dotted names of the keys the filter removed; empty
            for a local parent.
    """

    path: Path
    data: dict[str, Any]
    dropped: tuple[str, ...] = ()

load_parent

load_parent(
    recipe_path: Path, recipe_obj: dict[str, Any]
) -> LoadedParent | None

Loads the parent recipe a recipe declares, if any.

The parent field names another recipe file relative to the declaring recipe's directory. The parent is merged beneath the declaring recipe by merge_config_layers.

A parent under upstream/ is a pinned copy: its bytes must match the hash recorded in upstream.yaml, and only the keys in ALLOWED_PARENT_KEYS are kept. See napt.upstream.pinned for what makes a parent a pinned copy.

Parameters:

Name Type Description Default
recipe_path Path

Path to the recipe that may declare parent.

required
recipe_obj dict[str, Any]

The parsed recipe dictionary.

required

Returns:

Type Description
LoadedParent | None

The parent, or None when the recipe declares no parent.

Raises:

Type Description
ConfigError

When parent is not a non-empty string, the parent file is missing or not a mapping, the parent itself declares a parent (chains are not supported), or a pinned parent is not tracked in upstream.yaml or does not match its recorded hash.

Source code in napt/config/loader.py
def load_parent(recipe_path: Path, recipe_obj: dict[str, Any]) -> LoadedParent | None:
    """Loads the parent recipe a recipe declares, if any.

    The ``parent`` field names another recipe file relative to the
    declaring recipe's directory. The parent is merged beneath the
    declaring recipe by
    [merge_config_layers][napt.config.loader.merge_config_layers].

    A parent under ``upstream/`` is a pinned copy: its bytes must match the hash
    recorded in ``upstream.yaml``, and only the keys in
    [ALLOWED_PARENT_KEYS][napt.upstream.pinned.ALLOWED_PARENT_KEYS] are
    kept. See [napt.upstream.pinned][] for what makes a parent a pinned
    copy.

    Args:
        recipe_path: Path to the recipe that may declare ``parent``.
        recipe_obj: The parsed recipe dictionary.

    Returns:
        The parent, or None when the recipe declares no parent.

    Raises:
        ConfigError: When ``parent`` is not a non-empty string, the parent
            file is missing or not a mapping, the parent itself declares a
            parent (chains are not supported), or a pinned parent is not
            tracked in ``upstream.yaml`` or does not match its recorded
            hash.
    """
    parent_ref = recipe_obj.get("parent")
    if parent_ref is None:
        return None
    if not isinstance(parent_ref, str) or not parent_ref.strip():
        raise ConfigError(f"parent must be a non-empty string: {recipe_path}")

    recipe_dir = recipe_path.resolve().parent
    parent_path = (recipe_dir / parent_ref).resolve()
    # Pinned by the reference as written, or by where the file really is.
    location = pinned_location(recipe_dir, parent_ref) or tracked_location(parent_path)

    data = _read_yaml_bytes(parent_path, "Parent recipe")
    if location is not None:
        verify_pinned_copy(parent_path, location, data)
    parent_obj = _parse_yaml_mapping(data, parent_path)
    if "parent" in parent_obj:
        raise ConfigError(
            f"Parent chains are not supported: {parent_path} declares its own "
            f"parent (used as parent by {recipe_path})"
        )
    if location is None:
        return LoadedParent(path=parent_path, data=parent_obj)
    kept, dropped = filter_pinned_parent(parent_obj)
    return LoadedParent(path=parent_path, data=kept, dropped=dropped)

collect_recipe_paths

collect_recipe_paths(recipes: Path) -> list[Path]

Collects recipe file paths from a file or directory.

Parameters:

Name Type Description Default
recipes Path

A recipe YAML file, or a directory scanned recursively for *.yaml / *.yml files.

required

Returns:

Type Description
list[Path]

Sorted recipe file paths.

Raises:

Type Description
ConfigError

If the path does not exist or contains no recipes.

Source code in napt/config/loader.py
def collect_recipe_paths(recipes: Path) -> list[Path]:
    """Collects recipe file paths from a file or directory.

    Args:
        recipes: A recipe YAML file, or a directory scanned recursively
            for ``*.yaml`` / ``*.yml`` files.

    Returns:
        Sorted recipe file paths.

    Raises:
        ConfigError: If the path does not exist or contains no recipes.
    """
    if recipes.is_file():
        return [recipes]
    if recipes.is_dir():
        found = sorted(
            path for pattern in ("*.yaml", "*.yml") for path in recipes.rglob(pattern)
        )
        if not found:
            raise ConfigError(f"No recipe files found under {recipes}")
        return found
    raise ConfigError(f"Recipe path not found: {recipes}")

resolve_state_dir

resolve_state_dir(recipes: Path) -> Path

Resolves the configured state directory for a run over recipes.

directories.state is org policy (consistent across a project), so the first recipe's effective configuration determines it for a fleet-wide run. The load is quiet: this reads one setting and reports nothing about the recipe, so the command's own output (for example napt status --format json) is not preceded by recipe diagnostics.

Parameters:

Name Type Description Default
recipes Path

A recipe YAML file, or a directory scanned recursively.

required

Returns:

Type Description
Path

The configured state directory.

Raises:

Type Description
ConfigError

If the recipes path is invalid or the first recipe cannot be loaded.

Source code in napt/config/loader.py
def resolve_state_dir(recipes: Path) -> Path:
    """Resolves the configured state directory for a run over recipes.

    ``directories.state`` is org policy (consistent across a project),
    so the first recipe's effective configuration determines it for a
    fleet-wide run. The load is quiet: this reads one setting and reports
    nothing about the recipe, so the command's own output (for example
    ``napt status --format json``) is not preceded by recipe diagnostics.

    Args:
        recipes: A recipe YAML file, or a directory scanned recursively.

    Returns:
        The configured state directory.

    Raises:
        ConfigError: If the recipes path is invalid or the first recipe
            cannot be loaded.

    """
    first = collect_recipe_paths(recipes)[0]
    config = load_effective_config(first, quiet=True)
    return Path(config["directories"]["state"])

register_recipe_id

register_recipe_id(
    sources: dict[str, Path], app_id: str, path: Path
) -> str | None

Records which file declares a recipe id, reporting a second claimant.

napt validate and napt promote both scan a directory and must agree on what a duplicate id is; this is the one place that decides.

Parameters:

Name Type Description Default
sources dict[str, Path]

The ids seen so far, mapped to the file that declared each. A new id is recorded here.

required
app_id str

The id the file declares.

required
path Path

The file declaring it.

required

Returns:

Type Description
str | None

None when the id is new; otherwise the error message, naming both files and the usual cause, with the first declaration kept.

Source code in napt/config/loader.py
def register_recipe_id(sources: dict[str, Path], app_id: str, path: Path) -> str | None:
    """Records which file declares a recipe id, reporting a second claimant.

    ``napt validate`` and ``napt promote`` both scan a directory and must
    agree on what a duplicate id is; this is the one place that decides.

    Args:
        sources: The ids seen so far, mapped to the file that declared each.
            A new id is recorded here.
        app_id: The id the file declares.
        path: The file declaring it.

    Returns:
        None when the id is new; otherwise the error message, naming both
            files and the usual cause, with the first declaration kept.
    """
    first = sources.get(app_id)
    if first is None:
        sources[app_id] = path
        return None
    return (
        f"Recipe id '{app_id}' is declared by both {first} and {path}. Give "
        f"each recipe its own id, or move a parent recipe that shares its "
        f"child's id out of the directory being scanned."
    )

merge_effective_config

merge_effective_config(
    recipe_path: Path, *, quiet: bool = False
) -> tuple[dict[str, Any], Path | None]

Merges the configuration layers for a recipe without validating them.

Reads the recipe and the parent it declares, then merges them with merge_config_layers. When a pinned parent set keys the allow list dropped, one always-visible line names them, because the effective configuration differs from what the pinned copy says.

Parameters:

Name Type Description Default
recipe_path Path

Path to the recipe YAML file.

required
quiet bool

Skip the dropped-keys line, for a caller that reads one setting and reports nothing about the recipe.

False

Returns:

Type Description
tuple[dict[str, Any], Path | None]

The merged configuration and the parent recipe's path (None when the recipe declares no parent).

Raises:

Type Description
ConfigError

On a missing recipe or parent file, a YAML parse error, a layer whose top level is not a mapping, a parent chain, a recipe that is itself a pinned copy under upstream/, or a pinned parent that fails its hash check.

Source code in napt/config/loader.py
def merge_effective_config(
    recipe_path: Path, *, quiet: bool = False
) -> tuple[dict[str, Any], Path | None]:
    """Merges the configuration layers for a recipe without validating them.

    Reads the recipe and the parent it declares, then merges them with
    [merge_config_layers][napt.config.loader.merge_config_layers]. When
    a pinned parent set keys the allow list dropped, one always-visible
    line names them, because the effective configuration differs from
    what the pinned copy says.

    Args:
        recipe_path: Path to the recipe YAML file.
        quiet: Skip the dropped-keys line, for a caller that reads one
            setting and reports nothing about the recipe.

    Returns:
        The merged configuration and the parent recipe's path (None when
            the recipe declares no parent).

    Raises:
        ConfigError: On a missing recipe or parent file, a YAML parse error,
            a layer whose top level is not a mapping, a parent chain, a
            recipe that is itself a pinned copy under ``upstream/``, or a
            pinned parent that fails its hash check.
    """
    logger = get_global_logger()
    if is_pinned_copy(recipe_path):
        raise ConfigError(
            f"{recipe_path} is a pinned copy under upstream/. Run the "
            f"override in recipes/ that names it as parent instead."
        )
    recipe_path = recipe_path.resolve()
    logger.verbose("CONFIG", f"Loading recipe: {recipe_path}")

    recipe_obj = _load_yaml_mapping(recipe_path, "Recipe")
    parent = load_parent(recipe_path, recipe_obj)
    if parent is not None and parent.dropped and not quiet:
        logger.info(
            "CONFIG",
            "Ignoring from parent (not allowed from upstream recipes): "
            + ", ".join(parent.dropped),
        )
    merged = merge_config_layers(recipe_path, recipe_obj, parent)
    return merged, parent.path if parent is not None else None

merge_config_layers

merge_config_layers(
    recipe_path: Path,
    recipe_obj: dict[str, Any],
    parent: LoadedParent | None = None,
) -> dict[str, Any]

Merges the configuration layers for an already-parsed recipe.

The recipe and its parent arrive as objects, so a recipe that is not on disk yet can be merged exactly as it will be once written. Performs the following operations:

  1. Find defaults root by scanning upwards from the recipe's directory for defaults/org.yaml
  2. Load org defaults from defaults/org.yaml
  3. Load the vendor defaults named after the recipe's directory, if present
  4. Merge: org -> vendor -> parent -> recipe (dicts deep-merge, lists replace); the secrets section is taken from org.yaml alone
  5. Resolve known relative paths (see Path resolution in the module docstring)
  6. Inject dynamic fields (AppScriptDate = today if absent)

The merged dict carries the recipe's parent field and a _provenance entry naming the layer that set each value, so validation can check both.

Parameters:

Name Type Description Default
recipe_path Path

Where the recipe lives or will live; its directory names the vendor and anchors relative paths and the search for defaults/org.yaml.

required
recipe_obj dict[str, Any]

The parsed recipe.

required
parent LoadedParent | None

The parent as load_parent returns it, already filtered when pinned, or None when the recipe declares no parent.

None

Returns:

Type Description
dict[str, Any]

The merged configuration.

Raises:

Type Description
ConfigError

On a missing or unreadable org.yaml or vendor file, or one whose top level is not a mapping.

Source code in napt/config/loader.py
def merge_config_layers(
    recipe_path: Path,
    recipe_obj: dict[str, Any],
    parent: LoadedParent | None = None,
) -> dict[str, Any]:
    """Merges the configuration layers for an already-parsed recipe.

    The recipe and its parent arrive as objects, so a recipe that is not on
    disk yet can be merged exactly as it will be once written. Performs the
    following operations:

    1. Find defaults root by scanning upwards from the recipe's directory
       for defaults/org.yaml
    2. Load org defaults from defaults/org.yaml
    3. Load the vendor defaults named after the recipe's directory, if present
    4. Merge: org -> vendor -> parent -> recipe (dicts deep-merge, lists
       replace); the ``secrets`` section is taken from org.yaml alone
    5. Resolve known relative paths (see Path resolution in the module
       docstring)
    6. Inject dynamic fields (AppScriptDate = today if absent)

    The merged dict carries the recipe's ``parent`` field and a
    ``_provenance`` entry naming the layer that set each value, so
    validation can check both.

    Args:
        recipe_path: Where the recipe lives or will live; its directory
            names the vendor and anchors relative paths and the search for
            defaults/org.yaml.
        recipe_obj: The parsed recipe.
        parent: The parent as [load_parent][napt.config.loader.load_parent]
            returns it, already filtered when pinned, or None when the
            recipe declares no parent.

    Returns:
        The merged configuration.

    Raises:
        ConfigError: On a missing or unreadable org.yaml or vendor file, or
            one whose top level is not a mapping.
    """
    logger = get_global_logger()
    recipe_path = recipe_path.resolve()
    recipe_dir = recipe_path.parent

    parent_path: Path | None = None
    parent_obj: dict[str, Any] | None = None
    if parent is not None:
        parent_path, parent_obj = parent.path, parent.data

    # 1) Find defaults root
    defaults_root = _find_defaults_root(recipe_dir)
    if defaults_root:
        logger.verbose("CONFIG", f"Found defaults root: {defaults_root}")

    # Start with code defaults (always present baseline)
    merged = copy.deepcopy(DEFAULT_CONFIG)
    provenance: dict[str, Any] = {}
    layers_merged = 1  # Code defaults count as first layer

    # Initialize provenance: all DEFAULT_CONFIG keys start as "code_default"
    def _init_provenance(cfg: dict[str, Any], prov: dict[str, Any]) -> None:
        for k, v in cfg.items():
            if isinstance(v, dict):
                sub = prov.setdefault(k, {})
                _init_provenance(v, sub)
            else:
                prov[k] = "code_default"

    _init_provenance(DEFAULT_CONFIG, provenance)

    # The secrets section as org.yaml wrote it. Restored over the merge
    # below so no other layer can declare a secret or widen its hosts.
    org_secrets: Any = {}

    if defaults_root:
        # 2) Load org defaults; _find_defaults_root found this file.
        org_defaults_path = defaults_root / "org.yaml"
        logger.verbose(
            "CONFIG",
            f"Loading: {org_defaults_path.relative_to(defaults_root.parent)}",
        )
        org_defaults = _load_yaml_mapping(org_defaults_path, "org.yaml")
        logger.debug("CONFIG", "--- Content from org.yaml ---")
        _print_yaml_content(org_defaults)
        org_secrets = org_defaults.get("secrets", {})
        merged = _deep_merge_dicts(
            merged,
            org_defaults,
            provenance=provenance,
            layer_name="org_yaml",
        )
        layers_merged += 1

        # 3) Load vendor defaults if present
        vendor_name = _detect_vendor(recipe_path)
        if vendor_name:
            logger.verbose("CONFIG", f"Detected vendor: {vendor_name}")
            candidate = defaults_root / "vendors" / f"{vendor_name}.yaml"
            if candidate.exists():
                logger.verbose(
                    "CONFIG", f"Loading: {candidate.relative_to(defaults_root.parent)}"
                )
                vendor_defaults = _load_yaml_mapping(candidate, "Vendor defaults")
                logger.debug("CONFIG", f"--- Content from {vendor_name}.yaml ---")
                _print_yaml_content(vendor_defaults)
                merged = _deep_merge_dicts(
                    merged,
                    vendor_defaults,
                    provenance=provenance,
                    layer_name="vendor_yaml",
                )
                layers_merged += 1

    # 4) Merge the parent beneath the recipe, then the recipe on top
    if parent_path is not None and parent_obj is not None:
        logger.verbose("CONFIG", f"Loading parent: {parent_path}")
        logger.debug("CONFIG", f"--- Content from {parent_path.name} ---")
        _print_yaml_content(parent_obj)
        merged = _deep_merge_dicts(
            merged, parent_obj, provenance=provenance, layer_name="parent"
        )
        layers_merged += 1

    # Show recipe content
    logger.verbose("CONFIG", f"Loading: {recipe_path.name}")
    logger.debug("CONFIG", f"--- Content from {recipe_path.name} ---")
    _print_yaml_content(recipe_obj)

    merged = _deep_merge_dicts(
        merged, recipe_obj, provenance=provenance, layer_name="recipe"
    )
    layers_merged += 1

    # Secrets are org policy and nothing else may touch them. Provenance
    # still records what the other layers tried, and validation reports it.
    merged["secrets"] = copy.deepcopy(org_secrets)

    logger.verbose("CONFIG", f"Deep merging {layers_merged} layer(s)")
    # Show final config structure
    # A key that is not a string is reported by validation, not here.
    top_level_keys = [str(key) for key in merged]
    logger.verbose(
        "CONFIG",
        (
            f"Final config has {len(top_level_keys)} top-level keys: "
            f"{', '.join(top_level_keys)}"
        ),
    )
    # 5) Resolve relative paths (branding paths relative to defaults_root)
    _resolve_known_paths(merged, recipe_dir, defaults_root)

    # 6) Inject dynamic values (e.g., AppScriptDate, RequireAdmin)
    _inject_dynamic_values(merged, provenance)

    # The configuration the command runs with, in debug mode
    logger.debug("CONFIG", "--- Final Merged Configuration ---")
    _print_yaml_content(merged)

    # Store provenance for downstream consumers
    merged["_provenance"] = provenance
    return merged

load_effective_config

load_effective_config(
    recipe_path: Path, *, quiet: bool = False
) -> dict[str, Any]

Loads, merges, and validates the effective configuration for a recipe.

Merges the layers with merge_effective_config, then validates the result: errors raise, warnings are logged. The returned dict does not carry the parent field; the parent's contents are already merged in.

Parameters:

Name Type Description Default
recipe_path Path

Path to the recipe YAML file.

required
quiet bool

Skip the validation warnings and the dropped-keys line, for a caller that reads one setting and reports nothing about the recipe.

False

Returns:

Type Description
dict[str, Any]

The merged configuration; code defaults are always included.

Raises:

Type Description
ConfigError

On a missing recipe or parent file, a YAML parse error, a layer whose top level is not a mapping, a parent chain, a pinned parent that fails its hash check, or a configuration that fails validation.

Source code in napt/config/loader.py
def load_effective_config(recipe_path: Path, *, quiet: bool = False) -> dict[str, Any]:
    """Loads, merges, and validates the effective configuration for a recipe.

    Merges the layers with
    [merge_effective_config][napt.config.loader.merge_effective_config],
    then validates the result: errors raise, warnings are logged. The
    returned dict does not carry the ``parent`` field; the parent's contents
    are already merged in.

    Args:
        recipe_path: Path to the recipe YAML file.
        quiet: Skip the validation warnings and the dropped-keys line, for
            a caller that reads one setting and reports nothing about the
            recipe.

    Returns:
        The merged configuration; code defaults are always included.

    Raises:
        ConfigError: On a missing recipe or parent file, a YAML parse error,
            a layer whose top level is not a mapping, a parent chain, a
            pinned parent that fails its hash check, or a configuration
            that fails validation.
    """
    from napt.validation import validate_config

    logger = get_global_logger()
    merged, parent_path = merge_effective_config(recipe_path, quiet=quiet)

    result = validate_config(merged, recipe_path=str(recipe_path.resolve()))
    if result.errors:
        where = f" (parent: {parent_path})" if parent_path is not None else ""
        raise ConfigError(f"Invalid configuration{where}: {'; '.join(result.errors)}")
    if not quiet:
        for warning in result.warnings:
            logger.warning("CONFIG", warning)

    # The parent's contents are merged in; the pointer itself is not config.
    merged.pop("parent", None)
    merged["_provenance"].pop("parent", None)

    return merged

napt.config.defaults

Default configuration values for NAPT.

This module provides the baseline configuration that ships with NAPT. These defaults are always applied first, then overridden by organization defaults (org.yaml), vendor defaults, and finally recipe-specific settings.

The configuration hierarchy is
  1. Code defaults (this module) - always present
  2. Organization defaults (defaults/org.yaml) - optional
  3. Vendor defaults (defaults/vendors/{Vendor}.yaml) - optional
  4. Parent recipe (the file named by parent) - optional
  5. Recipe configuration - required, app-specific settings

This design ensures that NAPT works out of the box without requiring any configuration files, while still allowing full customization when needed.

Note

Authentication for 'napt upload' requires no config file. Developers run 'napt auth login' once; CI/CD pipelines set AZURE_CLIENT_ID, AZURE_TENANT_ID and AZURE_CLIENT_SECRET, or use OIDC federation.