从 Ansible 中的 json 文件获取项目时出错

Error getting an item from json file in Ansible

我正在尝试从 Ansible 中的 json 查询中获取子网。我的调试结果如下:

"msg": [
    {
    "address_prefix": "10.10.2.0/23",
    "id": "/subscriptions/xxxxxxxxx-xxxxxxxxxxx-xxxxxxxx-xxx/resourceGroups/myRG/providers/Microsoft.Network/virtualNetworks/MYVNET/subnets/MySubnet",
    "name": "MySubnet",
    "network_security_group": "/subscriptions/xxxxxxxxx-xxxxxxxxxxx-xxxxxxxx-xxx/resourceGroups/MYVNET/providers/Microsoft.Network/networkSecurityGroups/mynsg",
    "provisioning_state": "Succeeded",
    "route_table": null
    }
]

我正在尝试获取子网的名称。我的Ansible玩法如下:

  tasks:
    - name: "Retrieve resourcegroup infos"
      azure_rm_virtualnetwork_info:
      register: object_vnet

    - name: get subnet name 
      debug: msg='{{ item.value }}'
      with_dict: "{{ object_vnet.virtualnetworks }}"
      when:
        - item.key == 'subnets'
        - item.value.name is match *MySub*

我得到的错误如下:

        fatal: [localhost]: FAILED! => {"msg": "The conditional check 'item.value.name is match *-MySub*' failed. 
The error was: template error while templating string: unexpected 'end of statement block'. 
    String: {% if item.value.name is match *MySub* %} True {% else %} False {% endif %}\n\n
    The error appears to be in '/myplay.yml': line 41, column 7, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\n
    The offending line appears to be:\n\n\n - name: get subnet name\n ^ here\n"}

有什么帮助的想法吗?

子网是一个列表,因此您需要在 vnet 的子网对象上循环并在 vnet 中的所有子网上循环。

为此,您可以创建一个单独的文件来循环,然后在该文件上创建子网和循环:

循环文件:

- name: create facts azure_subnets_result
  set_fact: 
    azure_subnets_result: >-
      {{
        ( azure_subnets_result | default([]) )
        + [ az_sub_item ]
      }}
  loop_control:
    loop_var: az_sub_item
  loop: "{{ az_sub }}"
  when: (az_sub_item.name | lower ) is match(".*mysub.*")

主文件:

tasks:
    - name: "Retrieve resourcegroup infos"
      azure_rm_virtualnetwork_info:
      register: object_vnet

    - name: create azure_subnets object
      set_fact: 
        azure_subnets: "{{ object_vnet.virtualnetworks | json_query(vnet_query) }}"
      vars:
        vnet_query: "[*].subnets"

    - name: loop on all object subnets and all sub objects
      include_tasks: loop.yml
      loop_control:
        loop_var: az_sub
      loop: "{{ azure_subnets }}"


    - name: debug message
      debug: msg='{{ azure_subnets_result }}'