I am trying to get the subnets from a json query in Ansible. My debug is result is as below:
"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
}
]
I am trying to get the name of the subnet. My Ansible play is as below:
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*
The error that I get , is as below:
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"}
Any ideas to help?
CodePudding user response:
subnets are a list, so you need to loop on subnets objects of your vnets and loop on all subnets in a vnet.
to do this, you can create a separate file to loop and you subnets and loop on this file:
loopfile:
- 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.*")
main file:
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 }}'
