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



我正试图从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 %}nn
The error appears to be in '/myplay.yml': line 41, column 7, but maynbe elsewhere in the file depending on the exact syntax problem.nn
The offending line appears to be:nnn - name: get subnet namen ^ heren"}

有什么想法可以帮忙吗?

子网是一个列表,因此您需要在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 }}'

最新更新