Leveraging Jinja2 Filters in Ansible Playbooks
Accessing Variables and Facts
In Ansible playbooks, you can use Jinja2 filters to access and manipulate variables and facts. This allows you to create more dynamic and flexible playbooks.
- name: Print a variable with the uppercase filter
debug:
msg: "{{ my_variable | upper }}"
Conditional Logic
Jinja2 filters can be used to implement conditional logic in your Ansible playbooks, such as the default
filter to provide a fallback value.
- name: Print a variable or a default value
debug:
msg: "{{ my_variable | default('default value') }}"
Jinja2 filters can be used to transform data, such as converting a dictionary to JSON or YAML format.
- name: Print a dictionary as JSON
debug:
msg: "{{ my_dictionary | to_json }}"
List and Dictionary Manipulation
Jinja2 filters can be used to manipulate lists and dictionaries, such as joining elements or selecting specific attributes.
- name: Join a list of items
debug:
msg: "{{ my_list | join(', ') }}"
Chaining Filters
Jinja2 filters can be chained together to perform multiple transformations on a variable or expression.
- name: Chain multiple filters
debug:
msg: "{{ my_variable | upper | replace('HELLO', 'GOODBYE') }}"