I would like to build an output that shows the key and value of a variable.
The following works perfectly ...
# Format in Ansible msg="{{ php_command_result.results | map(attribute='item') | join(', ') }}" # Output {'value': {'svn_tag': '20150703r1_6.36_homeland'}, 'key': 'ui'}, {'value': {'svn_tag': '20150702r1_6.36_homeland'}, 'key': 'api'}
What I would like is to show the key
and svn_tag
together as so:
I'm able to display either the key
or svn_tag
but getting them to go together doesn't work.
msg="{{ php_command_result.results | map(attribute='item.key') | join(', ') }}" # Output ui, api
However, this is what I want.
# Desired Output api - 20150702r1_6.36_homeland ui - 20150703r1_6.36_homeland
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(',')}}"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With