diff --git a/filter_plugins/xml2dict.py b/filter_plugins/xml2dict.py new file mode 100644 index 0000000..2501365 --- /dev/null +++ b/filter_plugins/xml2dict.py @@ -0,0 +1,30 @@ +class FilterModule(object): + + def filters(self): + return { + 'xml2dict': self.xml2dict, + } + + def xml2dict(self, value): + from xml.etree import ElementTree + # return json.dumps(xmltodict.parse(value)) + res = {} + + if isinstance(value, list): + for item in value: + e = self.xml2dict(item['get_xml']) + res[e['name']] = e + return res + + e = ElementTree.fromstring(value) + + def rp(root, result): + for element in root: + result[element.tag] = rp(element, {}) + result[element.tag].update(element.attrib) + if not result[element.tag]: + result[element.tag] = element.text + return result + + rp(e, res) + return res diff --git a/tasks/networks.yml b/tasks/networks.yml index 3c74095..e33fb53 100644 --- a/tasks/networks.yml +++ b/tasks/networks.yml @@ -1,4 +1,56 @@ --- +- name: Get current state of libvirt networks + virt_net: + name: "{{ item.name }}" + command: get_xml + with_items: "{{ libvirt_host_networks }}" + become: True + register: qemu_stackhpc_net_xml + +- name: Convert state of libvirt networks to dict + set_fact: + qemu_stackhpc_net: "{{ qemu_stackhpc_net_xml.results | xml2dict }}" + +- name: Stop all misconfigured networks + virt_net: + name: "{{ item.name }}" + state: inactive + uri: "{{ libvirt_host_uri | default(omit, true) }}" + when: > + 'forward' in qemu_stackhpc_net[item.name] and + 'mode' in qemu_stackhpc_net[item.name].forward and + qemu_stackhpc_net[item.name].forward.mode == 'nat' and + ( + qemu_stackhpc_net[item.name].ip.address != item.ip or + qemu_stackhpc_net[item.name].ip.netmask != item.netmask or + (qemu_stackhpc_net[item.name].ip.dhcp.range.start if 'dhcp' in qemu_stackhpc_net[item.name].ip else '') != + (item.dhcp_start if 'dhcp_start' in item else '') or + (qemu_stackhpc_net[item.name].ip.dhcp.range.end if 'dhcp' in qemu_stackhpc_net[item.name].ip else '') != + (item.dhcp_end if 'dhcp_end' in item else '') + ) + with_items: "{{ libvirt_host_networks }}" + become: True + +- name: Remove all misconfigured networks + virt_net: + name: "{{ item.name }}" + command: undefine + when: > + 'forward' in qemu_stackhpc_net[item.name] and + 'mode' in qemu_stackhpc_net[item.name].forward and + qemu_stackhpc_net[item.name].forward.mode == 'nat' and + ( + qemu_stackhpc_net[item.name].ip.address != item.ip or + qemu_stackhpc_net[item.name].ip.netmask != item.netmask or + (qemu_stackhpc_net[item.name].ip.dhcp.range.start if 'dhcp' in qemu_stackhpc_net[item.name].ip else '') != + (item.dhcp_start if 'dhcp_start' in item else '') or + (qemu_stackhpc_net[item.name].ip.dhcp.range.end if 'dhcp' in qemu_stackhpc_net[item.name].ip else '') != + (item.dhcp_end if 'dhcp_end' in item else '') + ) + with_items: "{{ libvirt_host_networks }}" + become: True + + - name: Ensure libvirt networks are defined virt_net: name: "{{ item.name }}"