Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to map multiple attributes using Jinja/Ansible?

Tags:

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 
like image 538
sdot257 Avatar asked Jul 28 '15 19:07

sdot257


Video Answer


2 Answers

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 }}" 
like image 64
bmaupin Avatar answered Oct 14 '22 17:10

bmaupin


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(',')}}" 
like image 24
KrapivchenkoN Avatar answered Oct 14 '22 18:10

KrapivchenkoN