Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 51 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -285,6 +285,57 @@ tagging: "{{projects.{{project.name}}.tagging}}"
It's possible to have the same key (eg. a dict/list) in multiple files and combine them using a deep merge.
See an example [here](https://github.com/adobe/himl#deep-merge-example).

#### Removing inherited keys

Use the custom YAML tag `!delete` to remove a dictionary key inherited from an
earlier file. Unlike `null`, this removes the key rather than assigning a value.

`data/globals.yaml`:

```yaml
modules_to_deploy:
module1: config-mod1
module2: config-mod2
module3: config-mod3
```

`data/special_dr_site/site.yaml`:

```yaml
modules_to_deploy:
module2: !delete
```

Running `himl --cwd data special_dr_site` produces:

```yaml
modules_to_deploy:
module1: config-mod1
module3: config-mod3
```

Deletion works at any dictionary depth through the Python API, `himl`, and
`himl-config-merger`, including precomputed and parallel processing. It is applied
as each file is merged, before interpolation, environment variables, or secrets
are resolved. Files follow the existing hierarchy order and alphabetical order
within each directory. A later file can recreate a deleted key without restoring
its old contents.

Deleting a missing key does nothing. Deleting a dictionary removes its entire
subtree; deleting its final child leaves an empty dictionary. Deleting all
top-level keys produces `{}`. References to deleted keys elsewhere still follow
the normal interpolation-validation rules.

Only the empty tag form shown above is accepted: do not supply a payload such as
`!delete null`. The tag is supported only as a dictionary value, not as a key,
a whole document, or anywhere inside a list or set. Quoted `"!delete"` remains
an ordinary string, and existing `null` behavior is unchanged. The tag also works
in files loaded with the merger's [existing `!include` support](#extra-merger-features).

`!delete` is a Himl-specific extension using standard YAML tag syntax. Other
tools reading these source files need a registered constructor for the tag;
generated YAML/JSON contains no deletion markers and needs no custom loader.

### Secrets retrieval

#### [AWS SSM](https://docs.aws.amazon.com/systems-manager/latest/userguide/integration-ps-secretsmanager.html)
Expand Down
39 changes: 37 additions & 2 deletions himl/config_generator.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,17 +22,51 @@
from .interpolation import InterpolationResolver, EscapingResolver, InterpolationValidator, SecretResolver, \
DictIterator, replace_parent_working_directory, EnvVarResolver, collect_pending_keys
from .python_compat import iteritems, primitive_types, PY3
from .yaml_tags import DELETE, loader_with_delete_tag

logger = logging.getLogger(__name__)


@functools.lru_cache(maxsize=None)
def _yaml_get_content_cached(yaml_file):
with open(yaml_file, 'r') as f:
content = yaml.load(f, Loader=yaml.SafeLoader)
loader = loader_with_delete_tag(yaml.SafeLoader)
content = yaml.load(f, Loader=loader) # nosec B506 # Scoped subclass of SafeLoader
return content if content else {}


def _reject_delete_markers(value, path):
if value is DELETE:
location = ".".join(path) or "<root>"
raise ValueError("!delete is only supported as a dictionary value at {}".format(location))
if isinstance(value, dict):
for key, child in iteritems(value):
_reject_delete_markers(key, path + ("<key>",))
_reject_delete_markers(child, path + (str(key),))
elif isinstance(value, (list, tuple, set)):
for index, child in enumerate(value):
_reject_delete_markers(child, path + (str(index),))


def _prepare_deletions(reference, incoming, path=()):
if incoming is DELETE:
_reject_delete_markers(incoming, path)
cleaned = {}
for key, value in iteritems(incoming):
key_path = path + (str(key),)
_reject_delete_markers(key, key_path)
if value is DELETE:
if isinstance(reference, dict):
reference.pop(key, None)
elif isinstance(value, dict):
inherited = reference.get(key) if isinstance(reference, dict) else None
cleaned[key] = _prepare_deletions(inherited, value, key_path)
else:
_reject_delete_markers(value, key_path)
cleaned[key] = value
return cleaned


class ConfigProcessor(object):

def process(self, cwd=None,
Expand Down Expand Up @@ -261,6 +295,7 @@ def merge_value(reference, new_value, type_strategies, fallback_strategies, type

@staticmethod
def merge_yamls(values, yaml_content, type_strategies, fallback_strategies, type_conflict_strategies):
yaml_content = _prepare_deletions(values, yaml_content)
for key, value in iteritems(yaml_content):
if key in values and not isinstance(values[key], type(value)) and not isinstance(value, type(values[key])):
raise Exception("Failed to merge key '{}', because of mismatch in type: {} vs {}"
Expand Down Expand Up @@ -353,7 +388,7 @@ def process_hierarchy_with_precomputed(self, precomputed_state):
self.fallback_strategies, self.type_conflict_strategies)
self.resolve_simple_interpolations(merged_values, yaml_file)

if not merged_values:
if not precomputed_state and not any(self.hierarchy):
raise Exception("No YAML files found to process in the hierarchy")

self.generated_data = merged_values
Expand Down
4 changes: 3 additions & 1 deletion himl/config_merger.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
from .config_generator import ConfigProcessor
from multiprocessing import Pool, cpu_count
from .filter_rules import FilterRules
from .yaml_tags import construct_delete

logging.basicConfig()
logging.root.setLevel(logging.INFO)
Expand Down Expand Up @@ -87,6 +88,7 @@ def __traverse_path(self, path: str, yaml_dict: dict):

# Register the include constructor
Loader.add_constructor('!include', Loader.include)
Loader.add_constructor('!delete', construct_delete)


def _group_by_parent(directories):
Expand All @@ -108,7 +110,7 @@ def build_parent_cache(directories, cwd=None):
# Patch SafeLoader so !include tags work in yaml_get_content (same patch
# that merge_logic applies, but build_parent_cache runs before merge_logic).
Loader.add_constructor('!include', Loader.include)
yaml.SafeLoader.add_constructor('!include', Loader.include)
yaml.SafeLoader = Loader # type: ignore
cwd = cwd or os.getcwd()
cache = {}
for leaf_path in directories:
Expand Down
33 changes: 33 additions & 0 deletions himl/yaml_tags.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
# Copyright 2026 Adobe. All rights reserved.
# This file is licensed to you under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License. You may obtain a copy
# of the License at http://www.apache.org/licenses/LICENSE-2.0

# Unless required by applicable law or agreed to in writing, software distributed under
# the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
# OF ANY KIND, either express or implied. See the License for the specific language
# governing permissions and limitations under the License.

from enum import Enum
from typing import cast

import yaml


class _DeleteMarker(Enum):
DELETE = "delete"


DELETE = _DeleteMarker.DELETE


def construct_delete(loader, node):
if not isinstance(node, yaml.ScalarNode) or node.value != "":
raise yaml.constructor.ConstructorError(None, None, "!delete requires an empty scalar", node.start_mark)
return DELETE


def loader_with_delete_tag(base_loader):
loader = cast(type[yaml.SafeLoader], type("HimlDeleteLoader", (base_loader,), {}))
loader.add_constructor("!delete", construct_delete)
return loader
Loading
Loading