From 1e4831e7448c5df2325f191a7cb49c0b3d4ed8c9 Mon Sep 17 00:00:00 2001 From: Orr Date: Mon, 30 Jul 2018 08:41:42 +0300 Subject: [PATCH] VMware: check if folder already exists before creation (#41588) * check if folder already exists before creation * added integration test --- .../modules/cloud/vmware/vcenter_folder.py | 8 ++++---- .../targets/vcenter_folder/tasks/main.yml | 18 ++++++++++++++++++ 2 files changed, 22 insertions(+), 4 deletions(-) diff --git a/lib/ansible/modules/cloud/vmware/vcenter_folder.py b/lib/ansible/modules/cloud/vmware/vcenter_folder.py index c8328ad66a..7bdcbc8b23 100644 --- a/lib/ansible/modules/cloud/vmware/vcenter_folder.py +++ b/lib/ansible/modules/cloud/vmware/vcenter_folder.py @@ -158,12 +158,12 @@ class VmwareFolderManager(PyVmomi): try: if parent_folder: folder = self.get_folder_by_name(folder_name=parent_folder) - if folder: + if folder and not self.get_folder_by_name(folder_name=folder_name, parent_folder=folder): folder.CreateFolder(folder_name) results['changed'] = True results['result'] = "Folder '%s' of type '%s' created under %s" \ " successfully." % (folder_name, folder_type, parent_folder) - else: + elif folder is None: self.module.fail_json(msg="Failed to find the parent folder %s" " for folder %s" % (parent_folder, folder_name)) else: @@ -208,13 +208,13 @@ class VmwareFolderManager(PyVmomi): " exception %s " % to_native(e)) self.module.exit_json(**results) - def get_folder_by_name(self, folder_name): + def get_folder_by_name(self, folder_name, parent_folder=None): """ Function to get managed object of folder by name Returns: Managed object of folder by name """ - folder_objs = get_all_objs(self.content, [vim.Folder]) + folder_objs = get_all_objs(self.content, [vim.Folder], parent_folder) for folder in folder_objs: if folder.name == folder_name: return folder diff --git a/test/integration/targets/vcenter_folder/tasks/main.yml b/test/integration/targets/vcenter_folder/tasks/main.yml index 49980e0b1d..addba1d5ba 100644 --- a/test/integration/targets/vcenter_folder/tasks/main.yml +++ b/test/integration/targets/vcenter_folder/tasks/main.yml @@ -81,6 +81,23 @@ - host - datastore - network + +- name: Recreate all types of sub folder + vcenter_folder: + hostname: "{{ vcsim }}" + username: "{{ vcsim_instance.json.username }}" + password: "{{ vcsim_instance.json.password }}" + validate_certs: no + datacenter: "{{ dc1 }}" + folder_name: "sub_{{ item }}_folder" + parent_folder: 'vm_folder' + state: present + register: recreate_folders + with_items: + - vm + - host + - datastore + - network - debug: msg="{{ all_folder_results }}" @@ -88,6 +105,7 @@ assert: that: - all_folder_results.changed + - not recreate_folders.changed #- name: Delete all types of folder # vcenter_folder: