You have to filter the keys, a direct address is not possible, because you don't know the exact name.
- name: Gather the package facts
ansible.builtin.package_facts:
- name: Filter package names
set_fact:
filtered_package_names: "{{ ansible_facts.packages | list
| map('regex_search', '^vim.*') | select('string') | list }}"
- name: Print filtered packages
debug:
var: filtered_package_names
- name: Print package details from all filtered packages
debug:
msg: "{{ ansible_facts.packages[item] }}"
with_items: "{{ filtered_package_names }}"
With list
a list of the keys is created, then you can filter this list with regex_search
, afterwards the list is reduced to the filter result.
== Edit begin
There is a smarter filter method. Instead of using map(regex_search) / select(string)
, you could use directly select(match)
, so the filtering would look like:
- name: Filter package names
set_fact:
filtered_package_names: "{{ ansible_facts.packages | list
| select('match', '^vim.*') | list }}"
== Edit end
The result is a list of package names that match your regex.
If you need more information about one of the packages, you can then use ansible_facts.packages[_your_item]
to get the rest of the information.
Example output of the above tasks:
TASK [Gather the package facts] ****************************************************************************************
ok: [localhost]
TASK [Filter package names] ********************************************************************************************
ok: [localhost]
TASK [Print filtered packages] *****************************************************************************************
ok: [localhost] => {
"filtered_package_names": [
"vim",
"vim-common",
"vim-runtime",
"vim-tiny"
]
}
TASK [Print package details] *******************************************************************************************
ok: [localhost] => (item=vim) => {
"msg": [
{
"arch": "amd64",
"category": "editors",
"name": "vim",
"origin": "Ubuntu",
"source": "apt",
"version": "2:8.1.2269-1ubuntu5.7"
}
]
}
ok: [localhost] => (item=vim-common) => {
"msg": [
{
"arch": "all",
"category": "editors",
"name": "vim-common",
"origin": "Ubuntu",
"source": "apt",
"version": "2:8.1.2269-1ubuntu5.7"
}
]
}
ok: [localhost] => (item=vim-runtime) => {
"msg": [
{
"arch": "all",
"category": "editors",
"name": "vim-runtime",
"origin": "Ubuntu",
"source": "apt",
"version": "2:8.1.2269-1ubuntu5.7"
}
]
}
ok: [localhost] => (item=vim-tiny) => {
"msg": [
{
"arch": "amd64",
"category": "editors",
"name": "vim-tiny",
"origin": "Ubuntu",
"source": "apt",
"version": "2:8.1.2269-1ubuntu5.7"
}
]
}