Ansible:以更紧凑的方式使用 with_items?

问题描述 投票:0回答:1

考虑以下测试手册:

---
- name: Playbook
  hosts: localhost
  become: false
  gather_facts: false
  vars:
    plugins:
      - name: diff
        enabled: true
        dependencies:
          - python3-jsonpatch
          - python3-kubernetes
        repository:
          name: helm-diff
          org: databus23
        version: v3.9.6
      - name: git
        enabled: false
        repository:
          name: helm-git
          org: aslafy-z
        version: v0.16.0
  tasks:
    - name: Loop
      block:
        - name: List plugin names
          ansible.builtin.debug:
            msg: '{{ item.name }}'
          when: item.enabled
          with_items: "{{ plugins }}"

        - name: List dependencies
          ansible.builtin.debug:
            msg: '{{ item }}'
          with_items: "{{ plugins | selectattr('enabled', 'eq', true) | selectattr('dependencies', 'defined') | map(attribute='dependencies') }}"

这会产生预期的结果:

TASK [List plugin names] ***
ok: [localhost] => (item={'name': 'diff', 'enabled': True, 'dependencies': ['python3-jsonpatch', 'python3-kubernetes'], 'repository': {'name': 'helm-diff', 'org': 'databus23'}, 'version': 'v3.9.6'}) =>
  msg: diff

TASK [List dependencies] ***
ok: [localhost] => (item=python3-jsonpatch) =>
  msg: python3-jsonpatch
ok: [localhost] => (item=python3-kubernetes) =>
  msg: python3-kubernetes

是否有更好的方法可以使

with_items
的使用更加紧凑到第二个任务中,最好与第一个任务中使用的组合
with
条件一起使用?

我将使用上面列出的相同

with_items
循环执行多个任务,我不知道是否有办法将多个任务分组在同一个
with_items
循环下。

谢谢您的建议。

ansible
1个回答
0
投票

如果您使用

json_query
过滤器,您可以像这样编写任务:

- name: List dependencies
  ansible.builtin.debug:
    msg: "{{ item }}"
  loop: "{{ plugins | json_query('[].dependencies[]') }}"

产生输出:

TASK [List dependencies] **********************************************************************************************************************
ok: [localhost] => (item=python3-jsonpatch) => {
    "msg": "python3-jsonpatch"
}
ok: [localhost] => (item=python3-kubernetes) => {
    "msg": "python3-kubernetes"
}

根据您的目标,您可以删除

loop
并改为写:

- name: List dependencies
  ansible.builtin.debug:
    msg: "{{ plugins | json_query('[].dependencies[]') }}"

这会生成一个合并的依赖项列表:

TASK [List dependencies] **********************************************************************************************************************
ok: [localhost] => {
    "msg": [
        "python3-jsonpatch",
        "python3-kubernetes"
    ]
}
© www.soinside.com 2019 - 2024. All rights reserved.