ansible-collections / community.vmware

Ansible Collection for VMware
GNU General Public License v3.0
346 stars 334 forks source link

Allow Host Filtering to Work with Lowercase for vmware_vm_inventory like vmware_inventory.py #284

Open jamesmarshall24 opened 4 years ago

jamesmarshall24 commented 4 years ago
SUMMARY

In the previous dynamic inventory script for vmware (vmware_inventory.py), host_filters and groupby_patterns could correctly filter the JSON returned from vCenter as the keys were all set to lower(). In the latest introduction of host filtering from #137 , filters requires the exact casing returned which breaks filtering previously used with vmware_inventory.py

ISSUE TYPE
COMPONENT NAME

vmware_vm_inventory

ADDITIONAL INFORMATION

The following two examples should work the same.

This one does not filter.

filters:
- guest.guestfamily == 'linuxGuest'

This one does filter.

filters:
- guest.guestFamily == 'linuxGuest'
jamesmarshall24 commented 4 years ago

It also might be a good idea to make this configurable as I assume the current filtering has been adopted by some users. If there was a flag to set this, then users migrating their filters from vmware_inventory.py could drop in place while users matching keys with the correct casing could continue with their filters as usual.

Akasurde commented 4 years ago

@dacrystal Would you like to work on this? Thanks.

dacrystal commented 4 years ago

This have been discussed before:

https://github.com/ansible-collections/vmware/pull/80#issuecomment-613511792

I can propose an option property_name_format that have the following choices:

snake_case (Ansible way) lower_case (similar feature to the script; lower_var_keys) camel_case (pyvmomi)

I have drafted that feature in my fork topic/vmware-inventory-plugin-property-format. I just need to rebase it or something.

https://github.com/ansible-collections/vmware/blob/23f3621a4fe618d0aa465c21b37cca0f5f452db2/plugins/inventory/vmware_vm_inventory.py#L837-L838

...
-        if can_sanitize:  # to snake case
-            host_properties = camel_dict_to_snake_dict(host_properties)
+     # property_name_format
+      property_name_format = self.get_option('property_name_format')
+      if property_name_format.lower() == 'snake_case':
+           host_properties = camel_dict_to_snake_dict(host_properties)
+       elif property_name_format.lower() == 'lower_case':
+           host_properties = rename_dict_key(host_properties, str.lower)
...
+def rename_dict_key(item, rename_func):
+    if isinstance(item, dict):
+        new_dict = {}
+        for k, v in item.items():
+            new_dict[rename_func(k)] = rename_dict_key(v, rename_func)
+        return new_dict
+    elif isinstance(item, list):
+        new_list = []
+        for k in item:
+            new_list.append(rename_dict_key(k, rename_func))
+    else:
+        return item
...
ansibullbot commented 4 years ago

cc @Tomorrow9 @goneri @pgbidkar @warthog9 click here for bot help