如何测试 Ansible 列表变量中的字符串条件?

How to test a string condtion deep in Ansible list variable?

我在我的 Ansible 剧本中注册了一个列表变量 lxcs_info.results,其中填充了以下 LXC 相关数据:

ok: [webserver] => {
    "lxcs_info": {
        "changed": false, 
        "results": [
            {
                "_ansible_item_result": true, 
                "changed": false, 
                "invocation": {
                    "module_args": {
                        "name": "cndev", 
                        "state": "started", 
                        "template": "ubuntu", 
                    }, 
                    "module_name": "lxc_container"
                }, 
                "item": {
                    "backing_store": "dir", , 
                    "container_config": [
                        "lxc.group = dev", 
                        "lxc.group = mdblxc", 
                        "lxc.network.type = veth", 
                        "lxc.network.link = lxcbr0"
                    ], 
                    "name": "cndev", 
                    "state": "started", 
                    "template": "ubuntu",
                }, 
                "lxc_container": {
                    "interfaces": [
                        "eth0", 
                        "lo"
                    ], 
                    "ips": [
                        "10.0.3.2"
                    ], 
                    "name": "cndev", 
                    "state": "running"
                }
            },
            {
            # another result-item like the above
            },
            {
            # yet another item with same structure as above
            }
        ]
    }
}

因为我主要对 container_config 部分感兴趣,所以我需要一个任务来根据这些项目的内容条件执行命令,特别是在 [=25 中的内容的条件下=] 正好是 lxc.group = mdblxc

我应该如何为它编写 when-子句?我已经尝试完成以下任务,

- name: Test task
  debug: msg="Found mdblxc in {{ item }}"
  with_items: lxcs_info.results
  when: item.item.container_config.0.lxc.group == "mdblxc"

但它不起作用 - ansible-playbook 失败并出现错误:

fatal: [webserver]: FAILED! => {
  "failed": true,
  "msg": "The conditional check '( item.item.container_config.0.lxc.group == \"mdblxc\")' failed.
          The error was: error while evaluating conditional (( item.item.container_config.0.lxc.group == \"mdblxc\" ): 'unicode object' has no attribute 'lxc'

          The error appears to have been in 'mytask.yaml': line nnn, column 3, but may
          be elsewhere in the file depending on the exact syntax problem.

          The offending line appears to be:
            with_items: lxcs_info.results
          - name: Test task
            ^ here
         "
}

如果您仔细观察 container_config,您会注意到它是一个字符串项列表。
您无法访问字符串 "lxc.group = mdblxc".

lxc.group

所以你的when语句应该是这样的:

when: '"lxc.group = mdblxc" in item.item.container_config'