【问题标题】:Ansible: iterate over a results return value yum moduleAnsible:迭代结果返回值 yum 模块
【发布时间】:2017-10-05 17:38:11
【问题描述】:

问题:我有很多需要更新包的节点。有些节点安装了这些软件包,有些则没有。 目标是 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 只会更新已安装的包。

【问题讨论】:

  • 为什么不使用快速简便的方法?

标签: python dictionary ansible nested-lists


【解决方案1】:

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 选项返回的包列表(可能为空) 987654332@模块。

考虑到这一点,您可以像这样遍历结果:

- 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

【讨论】:

    【解决方案2】:

    ansible.builtin.yum: 模块只有在安装了软件包时才会更新。您可以使用loop: 指令遍历项目列表,或者如果它是一个短列表,则在任务块中声明变量并使用 yum 模块对列表进行操作的能力。喜欢又快又脏的版本。

    - name: update a list of packages
      yum:
        name: "{{ packagelist }}"
        state: latest
      vars:
        packagelist:
          - acpid
          - c-ares 
          - automake
    

    或者,更简单:

    - name: update a list of packages
      yum:
        name:
          - acpid
          - c-ares 
          - automake
        state: latest
    

    还有更多示例可用,所有参数都在此处定义: Ansible Docs article about yum

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-12-18
      • 2019-12-29
      • 2022-08-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多