Add format_dict filter

This commit is contained in:
Wojciech Kozlowski 2022-12-11 22:10:11 +01:00
parent 534e3435e3
commit ac795065f0
7 changed files with 98 additions and 0 deletions

2
.flake8 Normal file
View File

@ -0,0 +1,2 @@
[flake8]
max-line-length = 100

2
.gitignore vendored
View File

@ -1,3 +1,5 @@
**/__pycache__/**
.coverage
fact_cache/**
group_vars/**
host_vars/**

View File

@ -1,7 +1,10 @@
[defaults]
gathering = smart
fact_caching = ansible.builtin.jsonfile
fact_caching_connection = fact_cache
filter_plugins = plugins/filter
[privilege_escalation]
become = True

6
ci-requirements.txt Normal file
View File

@ -0,0 +1,6 @@
ansible
ansible-lint
pytest
pytest-cov
flake8
yamllint

10
makefile Normal file
View File

@ -0,0 +1,10 @@
ci-requirements:
@python -m pip install --upgrade -r ci-requirements.txt
plugins-test:
@python -m pytest -vv --cov plugins/filter --cov-report=term-missing plugins/tests
plugins-lint:
@python -m flake8 plugins
.PHONY: ci-requirements plugins-test plugins-lint

32
plugins/filter/format.py Normal file
View File

@ -0,0 +1,32 @@
import jinja2.exceptions
import ansible.errors
import ansible.module_utils
def __format_dict(dict_, pattern, *args):
values = []
for arg in args:
keys = arg.split(".")
value = dict_
for i, key in enumerate(keys):
try:
value = value[key]
except KeyError:
raise KeyError(f"{key} not in {'.'.join(['item'] + keys[:i])}")
values.append(value)
return pattern.format(*values)
def format_dict(dict_, pattern, *args): # pragma: no cover
try:
return __format_dict(dict_, pattern, *args)
except jinja2.exceptions.UndefinedError as e:
raise ansible.errors.AnsibleUndefinedVariable(
ansible.module_utils._text.to_native(e)) from e
except Exception as e:
raise ansible.errors.AnsibleFilterError(ansible.module_utils._text.to_native(e)) from e
class FilterModule: # pragma: no cover
def filters(self):
return {"format_dict": format_dict}

View File

@ -0,0 +1,43 @@
import ansible.errors
import pytest
from plugins.filter.format import format_dict
@pytest.fixture()
def item():
return {
"key": "key_value",
"value": {
"key_2_1": "value_2_1",
"key_2_2": {
"key_2_2_1": "value_2_2_1",
"key_2_2_2": "value_2_2_2",
},
"key_2_3": {
"key_2_3_1": "value_2_3_1",
},
},
}
def test_format_dict(item):
string = format_dict(
item,
"start-{}-{}-{}-end",
"key",
"value.key_2_1",
"value.key_2_2.key_2_2_2",
)
assert string == "start-key_value-value_2_1-value_2_2_2-end"
def test_format_dict_key_error(item):
with pytest.raises(ansible.errors.AnsibleFilterError):
format_dict(
item,
"start-{}-{}-{}-end",
"key",
"value.key_2_1",
"value.key_2_2.key_2_3_1",
)