简体   繁体   English

是否可以使用Ansible Playbook与with_dict和with_nested一起循环?

[英]Is it possible to Loop with with_dict and with_nested together using Ansible Playbook?

I am trying to loop over a hash and arrays associated with it like this: 我试图循环哈希和与之关联的数组,如下所示:

Var: VAR:

  dictionary:
    aword: [ ant, den ]
    bword: [ fat, slim ]

Task: 任务:

name: Create symlinks
command: do something with item[0] over item[1]
with_nested:
  - "{{ item.key }}"
  - "{{ item.value }}"
with_dict: dictionary

This does not work. 这不起作用。 Am I doing something wrong or Ansible doesn't support such iteration? 我做错了什么或Ansible不支持这样的迭代?

I solved this one using 我用这个解决了这个

with_subelements

like this 像这样

vars: 瓦尔:

dictionary:
- name: aword
  words:
    - ant
    - den
- name: bword
  words:
    - fat
    - slim

Task: 任务:

name: Create symlinks
command: do something with item.0.name over item.1
with_subelements: 
  - dictionary
  - words

For completeness, this can also be accomplished using with_nested by creating nested lists in Ansible. 为了完整with_nested ,这也可以通过在Ansible中创建嵌套列表使用with_nested来完成。 Doing so allows the same looping behavior without requiring setting a var/fact. 这样做允许相同的循环行为,而无需设置var / fact。 This is useful for when you want to instantiate the nested lists on the task itself. 当您想要在任务本身上实例化嵌套列表时,这非常有用。

Like so: 像这样:

---

- hosts: localhost
  connection: local
  become: false

  tasks:

    - debug:
        msg: "do something with {{ item[0] }} over {{ item[1] }}"
      with_nested:
        - - ant  # note the two hyphens to create a list of lists
          - den

        - - fat
          - slim

Output: 输出:

TASK [debug] ********************************************************************************************
ok: [localhost] => (item=[u'ant', u'fat']) => {
    "changed": false,
    "item": [
        "ant",
        "fat"
    ],
    "msg": "do something with ant over fat"
}
ok: [localhost] => (item=[u'ant', u'slim']) => {
    "changed": false,
    "item": [
        "ant",
        "slim"
    ],
    "msg": "do something with ant over slim"
}
ok: [localhost] => (item=[u'den', u'fat']) => {
    "changed": false,
    "item": [
        "den",
        "fat"
    ],
    "msg": "do something with den over fat"
}
ok: [localhost] => (item=[u'den', u'slim']) => {
    "changed": false,
    "item": [
        "den",
        "slim"
    ],
    "msg": "do something with den over slim"
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM