循环 with_subelements ansible

loop over with_subelements ansible

您好有以下变量:

couchbase:
 - name: incre1
   ipaddress:
    - 10.16.9.177
    - 10.16.9.178
   buckets:
    - AA1
    - aa1

我的 plabook 有以下内容:

 - debug:
    msg: "Running backup as {{CBBACKUPMGR}} backup -r {{ item.1 }} --cluster couchbase://{{ item.0.ipaddress }}"
   register: example
   with_subelements:
     - "{{ couchbase }}"
     -  buckets

我想遍历 ipaddress,然后用 buckets,所以基本上我想看看:

Running backup as /opt/ouchbase backup -r AA1 --cluster couchbase://10.16.9.177
Running backup as /opt/ouchbase backup -r aa1 --cluster couchbase://10.16.9.177
Running backup as /opt/ouchbase backup -r AA1 --cluster couchbase://10.16.9.178
Running backup as /opt/ouchbase backup -r aa1 --cluster couchbase://10.16.9.178

但是,当 运行 我看到的剧本如下:

Running backup as /opt/ouchbase backup -r AA1 --cluster couchbase://[u'10.16.9.177', u'10.16.9.178']
Running backup as /opt/ouchbase backup -r aa1 --cluster couchbase://[u'10.16.9.177', u'10.16.9.178']

那不是 with_subelements 所做的。如果您使用此 "debug" 循环来打印 {{ item }},您将看到在每次迭代中,它都会创建一个列表:

  1. 来自 couchbase 列表的包含您指定的子元素的父元素,没有该子元素的散列和​​
  2. 该迭代的子元素的值。

这是输出:

TASK [debug] ********************************************************************************************************************************************************************************************************
ok: [localhost] => (item=None) => {
    "msg": [
        {
            "ipaddress": [
                "10.16.9.177", 
                "10.16.9.178"
            ], 
            "name": "incre1"
        }, 
        "AA1"
    ]
}
ok: [localhost] => (item=None) => {
    "msg": [
        {
            "ipaddress": [
                "10.16.9.177", 
                "10.16.9.178"
            ], 
            "name": "incre1"
        }, 
        "aa1"
    ]
}

PLAY RECAP

正如您所阐明的,您的目的是生成 ipaddressbuckets 之间的所有可能组合。

要做到这一点,请尝试这个任务:

  - debug:
      msg: "Running backup as {{CBBACKUPMGR}} backup -r {{ item[0] }} --cluster couchbase://{{ item[1] }}"
    register: example
    with_items:
      - "{{ lookup('nested', couchbase[0].ipaddress, couchbase[0].buckets) }}"

这假设您的 couchbase 列表变量只有一个元素,就像您的示例中一样。

结果:

TASK [debug] ********************************************************************************************************************************************************************************************************
ok: [localhost] => (item=None) => {
    "msg": "Running backup as /opt/ouchbase backup -r 10.16.9.177 --cluster couchbase://AA1"
}
ok: [localhost] => (item=None) => {
    "msg": "Running backup as /opt/ouchbase backup -r 10.16.9.177 --cluster couchbase://aa1"
}
ok: [localhost] => (item=None) => {
    "msg": "Running backup as /opt/ouchbase backup -r 10.16.9.178 --cluster couchbase://AA1"
}
ok: [localhost] => (item=None) => {
    "msg": "Running backup as /opt/ouchbase backup -r 10.16.9.178 --cluster couchbase://aa1"
}

PLAY RECAP

希望对您有所帮助。