'How to use the jinja2 output as an ansible directive instead of a chain of characters?
I am currently displaying some vars with 'extract':
- name: Display hostvars over conditionnal
hosts: all
tasks:
- debug:
msg: "{{
ansible_play_hosts
| map('extract', hostvars, inventory_hostname)
|selectattr('ansible_distribution', 'regex', 'Rocky|CentOS' )
|selectattr('ansible_distribution_major_version', '==', '8' )
|flatten
}}"
The result is a list of name that match to those conditions:
TASK [debug]
ok: [ancolie-lba] => {
"msg": [
"vm703-dev"
]
}
and now I'd like to template this display with jinja2 ansible_facts.j2
{{'{{'}}
ansible_play_hosts
|map('extract', hostvars)
{% for condition in conditions %}
|selectattr('{{condition.attribute}}', '{{condition.verb}}', '{{condition.text}}' )
{% endfor %}
|flatten
{{'}}'}}
so as to use the jinja2 output file like follow:
- block:
- name: generate a conf
template:
src: ansible_facts.j2
dest: /tmp/ansible_facts
- debug:
msg: "{{lookup('file', '/tmp/ansible_facts')}}"
tags: template
delegate_to: localhost
vars:
conditions:
- attribute: 'ansible_distribution'
verb: 'regex'
text: 'Rocky|CentOS'
- attribute: 'ansible_distribution_major_version'
verb: '=='
text: '8'
But it seems that ansible interprets the lookup output as a chain character instead of excuting the filters as initially:
What is returned:
"msg": "{{ansible_play_hosts|map('extract', hostvars, os)|selectattr('ansible_distribution', 'regex', 'Rocky|CentOS' )|selectattr('ansible_distribution_major_version', '==', '8' )|flatten}}"
Expected result:
TASK [debug] *********************************************************************************************************************************************************************************
ok: [ancolie-lba] => {
"msg": [
"vm703-dev"
]
}
How to use the jinja2 output as an ansible directive instead of a chain of characters?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
