Ansible: iterate over a results return value yum module

前端 未结 2 1936
失恋的感觉
失恋的感觉 2021-01-17 01:12

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 us

2条回答
  •  天命终不由人
    2021-01-17 01:52

    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
    

提交回复
热议问题