Ansible has a lot of options, where combining and chaining filters is of great usage.
In certain cases the final result might become a bit hard to maintain if it is re-used in multiple places. E.g. take the following examples:
I couldn’t find anything about Ansible having this functionality, but is it an idea for adding functions/aliases to Ansible where often re-used expressions can be stored as a ‘function’ or ‘alias’ so the user can call it with the appropriate input arguments?
In case of the above e.g. defining the expressions somewhere and calling it as e.g. {{ merge_dict(‘__merge_dict’, testdict_initial_value) }}
The user then only has to define the complex expression once, after which it can re-use the function in multiple places throughout the project.
Happy to hear any thoughts on this idea (or whether this is already possible).
Knowing that this is called a macro, I found the following feature request: https://github.com/ansible/ansible/issues/36130
It is mentioned in the issue that the decision was made not to add such a feature.
I tried using the described workaround but wasn’t successful so far:
Honestly using a separate file for defining this macro and then importing it for every usage also feels a bit like a workaround (since this would not something I’d do once, more like in the 100+ occurrences area).
Do you know if there is an alternative to define and use macros within a playbook?
Is it maybe worth reevaluating the feature request for adding support for this?
Mostly i was thinking for the use of in templates, the only other
thing i can think of is using 'intermediate vars' to keep reusable
expressions and then creating their input when needed:
- name: also works with 'vars' in other scopes, using set_fact to
get 'static value'
set_fact:
mylist: '{{merged_list}}'
vars:
testlist_initial_value: [10,11]
merge_pattern: '^.+_merge_list'
a_merge_list: [1,2,3]
b_merge_list: [4,5,6]