问题
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 yum module. 2. if package is installed and update is available then run yum update
I know this is easily done via command or shell but very inefficient.
tasks:
- name: check if packages are installed
yum: list="{{ item }}"
with_items:
- acpid
- c-ares
- automake
register: packages
- debug:
var: packages
will produce the results
What i want ansible to do is to update the package only when yum: list sees the package as installed and an upgrade available from the above results.
I'm not sure if that is possible using the yum module.
The quick and easy way would just to use command:
tasks:
- name: check if packages are installed
command: yum update -y {{ item }}
with_items:
- acpid
- c-ares
- automake
since yum update package will only update a package if it is installed.
回答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: latest
with_items: "{{ packages.results }}"
when: item.results
来源:https://stackoverflow.com/questions/46591718/ansible-iterate-over-a-results-return-value-yum-module