Skip to content

Commit

Permalink
Add require option to tower.get
Browse files Browse the repository at this point in the history
If set to True it will raise a KeyError instead of returning None if the
pillar key is not found.
  • Loading branch information
jgraichen committed Feb 24, 2021
1 parent 2f33b2b commit 18eec90
Show file tree
Hide file tree
Showing 5 changed files with 16 additions and 3 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/)
and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html).

## [Unreleased]
### Added
- Add require option to tower.get

## [1.5.2] - 2021-02-10
### Fixed
Expand Down
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -376,14 +376,16 @@ The above example demonstrates different usages. The first example will only wor

The `tower` pillar object is available in all rendering engines and can be used for low-level interaction with the ext_pillar engine. Some available functions are:

##### tower.get(key, default=None)
##### tower.get(key, default=None, require=False)

Get a pillar value by given traverse path:

```python
tower.get('my:pillar:key')
```

If `require=True` is set, `default` will be ignored and a KeyError will be raised if the pillar key is not found.

##### tower.update(dict)

Merges given dictionary into the pillar data.
Expand Down
9 changes: 7 additions & 2 deletions salt_tower/pillar/tower.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,8 +80,13 @@ def __init__(self, minion_id, env, pillar):
)
self._default_renderers = "jinja|yaml"

def get(self, key, default=None, **kwargs):
return traverse_dict_and_list(self, key, default, **kwargs)
def get(self, key, default=None, require=False, **kwargs):
if require:
default = KeyError(f"Pillar key missing: {key}")
value = traverse_dict_and_list(self, key, default, **kwargs)
if isinstance(value, KeyError):
raise value
return value

def update(self, obj, merge=True, **kwargs):
if merge:
Expand Down
3 changes: 3 additions & 0 deletions test/pillar/test_tower_tower.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,9 @@ def test_get_default(tower):
def test_get_default_value(tower):
assert tower.get('pillar:none', default=5) == 5

def test_get_default_require(tower):
with pytest.raises(KeyError):
tower.get('pillar:none', require=True)

def test_update(tower):
tower.update({
Expand Down
1 change: 1 addition & 0 deletions tox.ini
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ envlist =
[testenv]
deps =
pytest
salt: salt
salt3002: salt~=3002.0
salt3001: salt~=3001.0
salt3000: salt~=3000.0
Expand Down

0 comments on commit 18eec90

Please sign in to comment.