Skip to content Skip to sidebar Skip to footer

Ansible: Iterate Over A Results Return Value Yum Module

Problem: I have many nodes that need package updates. Some of the nodes have these packages installed and some do not. The goal is to 1. check if a package is installed using the

Solution 1:

The Ansible loops documentation has a section about using register in a loop.

Taking a look at the output of your debug task, you can see that your packages variable has a key named results that contains the results of your with_items loop in the first task. The large structure looks like this:

{"packages":{"changed":false,"msg":"All items completed","results":[{"item":"...","results":[]},{"item":"...","results":[]}]}}

Each individual result has a key item that contains the value of the loop iterator for that result, and a results key that contains the list of packages (possible empty) returned by the list option to the yum module.

With that in mind, you could loop over the results like this:

-debug:msg:"{{ item.item }}"with_items:"{{ packages.results }}"when:item.results

The when condition matches only those results for which the list operation returned a non-empty result.

To upgrade matching packages:

-yum:name:"{{ item.item }}"state:latestwith_items:"{{ packages.results }}"when:item.results

Solution 2:

The ansible.builtin.yum: module already updates only if a package is installed. You can loop over a list of items using the loop: directive, or if it's a short list, declare the variable within the task block and use the yum module's ability to operate over a list. Like the quick and dirty version.

-name:updatealistofpackagesyum:name:"{{ packagelist }}"state:latestvars:packagelist:-acpid-c-ares-automake

Or, even simpler:

-name:updatealistofpackagesyum:name:-acpid-c-ares-automakestate:latest

Many more examples are available and all the parameters are defined here: Ansible Docs article about yum

Post a Comment for "Ansible: Iterate Over A Results Return Value Yum Module"