Is it possible to map multiple attributes using Jinja/Ansible?
Using Jinja statements:
- set_fact:
php_command_result:
results: [{"value":{"svn_tag":"20150703r1_6.36_homeland"},"key":"ui"},{"value":{"svn_tag":"20150702r1_6.36_homeland"},"key":"api"}]
- debug:
msg: "{% for result in php_command_result.results %}\
{{ result.key }} - {{ result.value.svn_tag }} |
{% endfor %}"
Outputs:
ok: [localhost] => {
"msg": "ui - 20150703r1_6.36_homeland | api - 20150702r1_6.36_homeland | "
}
If you want the results on separate lines:
- debug:
msg: "{% set output = [] %}\
{% for result in php_command_result.results %}\
{{ output.append( result.key ~ ' - ' ~ result.value.svn_tag) }}\
{% endfor %}\
{{ output }}"
Outputs:
ok: [localhost] => {
"msg": [
"ui - 20150703r1_6.36_homeland",
"api - 20150702r1_6.36_homeland"
]
}
Either of these can be put on one line if desired:
- debug:
msg: "{% for result in php_command_result.results %}{{ result.key }} - {{ result.value.svn_tag }} | {% endfor %}"
- debug:
msg: "{% set output = [] %}{% for result in php_command_result.results %}{{ output.append( result.key ~ ' - ' ~ result.value.svn_tag) }}{% endfor %}{{ output }}"
Here is solution without custom filter_plugin or running shell command. However, it requires additional fact to be set in a with_items loop(php_fmt).
- hosts: localhost
connection: local
gather_facts: false
tasks:
- set_fact:
php_command_result:
results: '[{"value":{"svn_tag":"20150703r1_6.36_homeland"},"key":"ui"},{"value":{"svn_tag":"20150702r1_6.36_homeland"},"key":"api"}]'
- set_fact:
php_fmt: "{{ php_fmt|default([])|union([item.key+' -- '+item.value.svn_tag ]) }}"
with_items: "{{ php_command_result.results }}"
- debug:
msg: "{{php_fmt|join(',')}}"