首页 文章

Ansible:遍历结果返回值yum模块

提问于
浏览
0

问题:我有许多需要包更新的节点 . 有些节点安装了这些软件包,有些则没有 . 目标是1.检查是否使用yum模块安装了软件包 . 2.如果已安装软件包并且更新可用,则运行yum update

我知道这可以通过命令或shell轻松完成,但效率很低 .

tasks:
  - name: check if packages are installed
    yum: list="{{ item }}"
    with_items:
      - acpid
      - c-ares
      - automake
   register: packages


  - debug:
      var: packages

会产生the results

我想要ansible做的是只有当yum:list看到包已安装并且从上面的结果中获得升级时才更新包 .

我不确定使用yum模块是否可行 .

快速简便的方法就是使用命令:

tasks:
  - name: check if packages are installed
    command: yum update -y {{ item }}
    with_items:
      - acpid
      - c-ares 
      - automake

因为yum update package只会在安装包时更新它 .

1 回答

  • 0

    Ansible loops文档有section about using register in a loop .

    看一下 debug 任务的输出,您可以看到 packages 变量有一个名为 results 的键,其中包含第一个任务中 with_items 循环的结果 . 大型结构如下所示:

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

    每个单独的结果都有一个键 item ,其中包含该结果的循环迭代器的值,以及 results 键,其中包含 list 选项返回 yum 模块的包列表(可能为空) .

    考虑到这一点,你可以像这样循环结果:

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

    when 条件仅匹配 list 操作返回非空结果的结果 .

    要升级匹配的包:

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

相关问题