I have a json file (/tmp/lst_instalaciones_wordpress.json) on a group of servers. This json has the info about some Wordpress installs (domain, path, version...)
{
"id": 1,
"name": "My blog",
"version": "5.9.1",
"fullPath": "/var/www/vhosts/myblog"
}
{
"id": 2,
"name": "My blog2",
"version": "5.9.2",
"fullPath": "/var/www/vhosts/myblog2"
}
{
"id": 3,
"name": "My blog3",
"version": "5.7.6",
"fullPath": "/var/www/vhosts/myblog3"
}
{
"id": 4,
"name": "My blog4",
"version": "5.9.2",
"fullPath": "/var/www/vhosts/myblog4"
}
I slurped it in a var:
- slurp:
src: /tmp/lst_instalaciones_wordpress.json
register: fichero_json
- set_fact:
lst_versiones: "{{ fichero_json.content | b64decode | from_json}}"
I have a list of all the versions, and I need to print how much installs are for each versions.
all_vers:
- 5.7.6
- 5.9.1
- 5.9.2
I'am trying different options like this but nothing works:
- set_fact:
all_installs_vers: "{{ lst_versiones | json_query('[?version==`'{{item}}'`].version') | length }}"
with_items: "{{all_vers}}"
CodePudding user response:
Given the fixed YAML
shell> cat tmp/lst_instalaciones_wordpress.yml
---
[
{
"id": 1,
"name": "My blog",
"version": "5.9.1",
"fullPath": "/var/www/vhosts/myblog"
},
{
"id": 2,
"name": "My blog2",
"version": "5.9.2",
"fullPath": "/var/www/vhosts/myblog2"
},
{
"id": 3,
"name": "My blog3",
"version": "5.7.6",
"fullPath": "/var/www/vhosts/myblog3"
},
{
"id": 4,
"name": "My blog4",
"version": "5.9.2",
"fullPath": "/var/www/vhosts/myblog4"
}
]
Read the file and decode the list
- slurp:
src: tmp/lst_instalaciones_wordpress.yml
register: fichero_json
- set_fact:
lst_versiones: "{{ fichero_json.content|b64decode|from_yaml }}"
gives
lst_versiones:
- fullPath: /var/www/vhosts/myblog
id: 1
name: My blog
version: 5.9.1
- fullPath: /var/www/vhosts/myblog2
id: 2
name: My blog2
version: 5.9.2
- fullPath: /var/www/vhosts/myblog3
id: 3
name: My blog3
version: 5.7.6
- fullPath: /var/www/vhosts/myblog4
id: 4
name: My blog4
version: 5.9.2
Then, given the list of the versions
all_vers:
- 5.7.6
- 5.9.1
- 5.9.2
iterate the list, select the version, count the items and combine the dictionary
- set_fact:
all_installs_vers: "{{ all_installs_vers|d({})|
combine({item: _val|int}) }}"
loop: "{{ all_vers }}"
vars:
_val: "{{ lst_versiones|selectattr('version', 'eq', item)|length }}"
gives
all_installs_vers:
5.7.6: 1
5.9.1: 1
5.9.2: 2
CodePudding user response:
Another solution with only one step
- set_fact:
versions: "{{ versions | d({}) | combine({ item.version: nbversion }) }}"
loop: '{{ lst_versiones }}'
vars:
nbversion: >-
{{ (versions[item.version] | int 1) if versions[item.version] is defined
else (1 | int) }}
result if you debug versions:
ok: [localhost] => {
"msg": {
"5.7.6": "1",
"5.9.1": "1",
"5.9.2": "2"
}
}