| 1 |
#!/usr/bin/python |
| 2 |
# -*- coding: utf-8 -*- |
| 3 |
|
| 4 |
# Copyright: (c) 2018, Ansible Project |
| 5 |
# Copyright: (c) 2018, Abhijeet Kasurde <[email protected]> |
| 6 |
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 7 |
# SPDX-License-Identifier: GPL-3.0-or-later |
| 8 |
|
| 9 |
from __future__ import absolute_import, division, print_function |
| 10 |
__metaclass__ = type |
| 11 |
|
| 12 |
|
| 13 |
DOCUMENTATION = r''' |
| 14 |
--- |
| 15 |
module: vmware_category |
| 16 |
short_description: Manage VMware categories |
| 17 |
description: |
| 18 |
- This module can be used to create / delete / update VMware categories. |
| 19 |
- Tag feature is introduced in vSphere 6 version, so this module is not supported in the earlier versions of vSphere. |
| 20 |
author: |
| 21 |
- Abhijeet Kasurde (@Akasurde) |
| 22 |
requirements: |
| 23 |
- vSphere Automation SDK |
| 24 |
options: |
| 25 |
category_name: |
| 26 |
description: |
| 27 |
- The name of category to manage. |
| 28 |
required: true |
| 29 |
type: str |
| 30 |
category_description: |
| 31 |
description: |
| 32 |
- The category description. |
| 33 |
- This is required if O(state=present). |
| 34 |
- This parameter is ignored when O(state=absent). |
| 35 |
default: '' |
| 36 |
type: str |
| 37 |
category_cardinality: |
| 38 |
description: |
| 39 |
- The category cardinality. |
| 40 |
- This parameter is ignored, when updating existing category. |
| 41 |
- V(single) means an object can only be assigned one of the tags in this category. |
| 42 |
For example, if a O(category_name=Operating System), then different tags of this category would be "Windows", "Linux", and so on. |
| 43 |
In this case a VM object can be assigned only one of these tags and hence the cardinality of the associated category here is V(single). |
| 44 |
- V(multiple) means an object can be assigned several of the tags in this category. |
| 45 |
For example, if a O(category_name=Server), then different tags of this category would be "AppServer", "DatabaseServer" and so on. |
| 46 |
In this case a VM object can be assigned more than one of the above tags and hence the cardinality of the associated category here is V(multiple). |
| 47 |
choices: ['multiple', 'single'] |
| 48 |
default: 'multiple' |
| 49 |
type: str |
| 50 |
new_category_name: |
| 51 |
description: |
| 52 |
- The new name for an existing category. |
| 53 |
- This value is used while updating an existing category. |
| 54 |
type: str |
| 55 |
state: |
| 56 |
description: |
| 57 |
- The state of category. |
| 58 |
- If set to V(present) and category does not exists, then category is created. |
| 59 |
- If set to V(present) and category exists, then category is updated. |
| 60 |
- If set to V(absent) and category exists, then category is deleted. |
| 61 |
- If set to V(absent) and category does not exists, no action is taken. |
| 62 |
- Process of updating category only allows name, description change. |
| 63 |
default: 'present' |
| 64 |
choices: [ 'present', 'absent' ] |
| 65 |
type: str |
| 66 |
associable_object_types: |
| 67 |
description: |
| 68 |
- List of object types that can be associated with the given category. |
| 69 |
choices: |
| 70 |
- All objects |
| 71 |
- Cluster |
| 72 |
- Content Library |
| 73 |
- Datacenter |
| 74 |
- Datastore |
| 75 |
- Datastore Cluster |
| 76 |
- Distributed Port Group |
| 77 |
- Distributed Switch |
| 78 |
- Folder |
| 79 |
- Host |
| 80 |
- Library item |
| 81 |
- Network |
| 82 |
- Host Network |
| 83 |
- Opaque Network |
| 84 |
- Resource Pool |
| 85 |
- vApp |
| 86 |
- Virtual Machine |
| 87 |
type: list |
| 88 |
elements: str |
| 89 |
extends_documentation_fragment: |
| 90 |
- vmware.vmware.base_options |
| 91 |
- vmware.vmware.additional_rest_options |
| 92 |
|
| 93 |
''' |
| 94 |
|
| 95 |
EXAMPLES = r''' |
| 96 |
- name: Create a category |
| 97 |
community.vmware.vmware_category: |
| 98 |
hostname: "{{ vcenter_hostname }}" |
| 99 |
username: "{{ vcenter_username }}" |
| 100 |
password: "{{ vcenter_password }}" |
| 101 |
category_name: Sample_Cat_0001 |
| 102 |
category_description: Sample Description |
| 103 |
category_cardinality: 'multiple' |
| 104 |
state: present |
| 105 |
|
| 106 |
- name: Rename category |
| 107 |
community.vmware.vmware_category: |
| 108 |
hostname: "{{ vcenter_hostname }}" |
| 109 |
username: "{{ vcenter_username }}" |
| 110 |
password: "{{ vcenter_password }}" |
| 111 |
category_name: Sample_Category_0001 |
| 112 |
new_category_name: Sample_Category_0002 |
| 113 |
state: present |
| 114 |
|
| 115 |
- name: Update category description |
| 116 |
community.vmware.vmware_category: |
| 117 |
hostname: "{{ vcenter_hostname }}" |
| 118 |
username: "{{ vcenter_username }}" |
| 119 |
password: "{{ vcenter_password }}" |
| 120 |
category_name: Sample_Category_0001 |
| 121 |
category_description: Some fancy description |
| 122 |
state: present |
| 123 |
|
| 124 |
- name: Delete category |
| 125 |
community.vmware.vmware_category: |
| 126 |
hostname: "{{ vcenter_hostname }}" |
| 127 |
username: "{{ vcenter_username }}" |
| 128 |
password: "{{ vcenter_password }}" |
| 129 |
category_name: Sample_Category_0002 |
| 130 |
state: absent |
| 131 |
|
| 132 |
- name: Create category with 2 associable object types |
| 133 |
community.vmware.vmware_category: |
| 134 |
hostname: '{{ vcenter_hostname }}' |
| 135 |
username: '{{ vcenter_username }}' |
| 136 |
password: '{{ vcenter_password }}' |
| 137 |
category_name: 'Sample_Category_0003' |
| 138 |
category_description: 'sample description' |
| 139 |
associable_object_types: |
| 140 |
- Datastore |
| 141 |
- Cluster |
| 142 |
state: present |
| 143 |
''' |
| 144 |
|
| 145 |
RETURN = r''' |
| 146 |
category_results: |
| 147 |
description: dictionary of category metadata |
| 148 |
returned: on success |
| 149 |
type: dict |
| 150 |
sample: { |
| 151 |
"category_id": "urn:vmomi:InventoryServiceCategory:d7120bda-9fa5-4f92-9d71-aa1acff2e5a8:GLOBAL", |
| 152 |
"msg": "Category NewCat_0001 updated." |
| 153 |
} |
| 154 |
''' |
| 155 |
|
| 156 |
from ansible.module_utils.common.text.converters import to_native |
| 157 |
from ansible.module_utils.basic import AnsibleModule |
| 158 |
from ansible_collections.community.vmware.plugins.module_utils.vmware_rest_client import VmwareRestClient |
| 159 |
from ansible_collections.vmware.vmware.plugins.module_utils.argument_spec import rest_compatible_argument_spec |
| 160 |
|
| 161 |
try: |
| 162 |
from pyVmomi.VmomiSupport import XMLNS_VMODL_BASE |
| 163 |
except ImportError: |
| 164 |
XMLNS_VMODL_BASE = "urn:vim25" |
| 165 |
|
| 166 |
try: |
| 167 |
from com.vmware.cis.tagging_client import CategoryModel |
| 168 |
from com.vmware.vapi.std.errors_client import Error |
| 169 |
except ImportError: |
| 170 |
pass |
| 171 |
|
| 172 |
|
| 173 |
class VmwareCategory(VmwareRestClient): |
| 174 |
def __init__(self, module): |
| 175 |
super(VmwareCategory, self).__init__(module) |
| 176 |
self.category_service = self.api_client.tagging.Category |
| 177 |
self.global_categories = dict() |
| 178 |
self.category_name = self.params.get('category_name') |
| 179 |
self.get_all_categories() |
| 180 |
|
| 181 |
def ensure_state(self): |
| 182 |
"""Manage internal states of categories. """ |
| 183 |
desired_state = self.params.get('state') |
| 184 |
states = { |
| 185 |
'present': { |
| 186 |
'present': self.state_update_category, |
| 187 |
'absent': self.state_create_category, |
| 188 |
}, |
| 189 |
'absent': { |
| 190 |
'present': self.state_delete_category, |
| 191 |
'absent': self.state_unchanged, |
| 192 |
} |
| 193 |
} |
| 194 |
states[desired_state][self.check_category_status()]() |
| 195 |
|
| 196 |
def state_create_category(self): |
| 197 |
"""Create category.""" |
| 198 |
category_spec = self.category_service.CreateSpec() |
| 199 |
category_spec.name = self.category_name |
| 200 |
category_spec.description = self.params.get('category_description') |
| 201 |
|
| 202 |
if self.params.get('category_cardinality') == 'single': |
| 203 |
category_spec.cardinality = CategoryModel.Cardinality.SINGLE |
| 204 |
else: |
| 205 |
category_spec.cardinality = CategoryModel.Cardinality.MULTIPLE |
| 206 |
|
| 207 |
associable_object_types = self.params.get('associable_object_types') |
| 208 |
|
| 209 |
def append_namespace(object_name): |
| 210 |
return '%s:%s' % (XMLNS_VMODL_BASE, object_name) |
| 211 |
|
| 212 |
associable_data = { |
| 213 |
# With Namespace |
| 214 |
'cluster': append_namespace('ClusterComputeResource'), |
| 215 |
'datastore': append_namespace('Datastore'), |
| 216 |
'datastore cluster': append_namespace('StoragePod'), |
| 217 |
'folder': append_namespace('Folder'), |
| 218 |
'host': append_namespace('HostSystem'), |
| 219 |
'library item': append_namespace('com.vmware.content.library.Item'), |
| 220 |
|
| 221 |
# Without Namespace |
| 222 |
'datacenter': 'Datacenter', |
| 223 |
'distributed port group': 'DistributedVirtualPortgroup', |
| 224 |
'distributed switch': ['VmwareDistributedVirtualSwitch', 'DistributedVirtualSwitch'], |
| 225 |
'content library': 'com.vmware.content.Library', |
| 226 |
'resource pool': 'ResourcePool', |
| 227 |
'vapp': 'VirtualApp', |
| 228 |
'virtual machine': 'VirtualMachine', |
| 229 |
'network': ['Network', 'HostNetwork', 'OpaqueNetwork'], |
| 230 |
'host network': 'HostNetwork', |
| 231 |
'opaque network': 'OpaqueNetwork', |
| 232 |
} |
| 233 |
obj_types_set = [] |
| 234 |
if associable_object_types: |
| 235 |
for obj_type in associable_object_types: |
| 236 |
lower_obj_type = obj_type.lower() |
| 237 |
if lower_obj_type == 'all objects': |
| 238 |
for category in list(associable_data.values()): |
| 239 |
if isinstance(category, list): |
| 240 |
obj_types_set.extend(category) |
| 241 |
else: |
| 242 |
obj_types_set.append(category) |
| 243 |
break |
| 244 |
if lower_obj_type in associable_data: |
| 245 |
value = associable_data.get(lower_obj_type) |
| 246 |
if isinstance(value, list): |
| 247 |
obj_types_set.extend(value) |
| 248 |
else: |
| 249 |
obj_types_set.append(value) |
| 250 |
else: |
| 251 |
obj_types_set.append(obj_type) |
| 252 |
|
| 253 |
category_spec.associable_types = set(obj_types_set) |
| 254 |
|
| 255 |
category_id = '' |
| 256 |
try: |
| 257 |
category_id = self.category_service.create(category_spec) |
| 258 |
except Error as error: |
| 259 |
self.module.fail_json(msg="%s" % self.get_error_message(error)) |
| 260 |
|
| 261 |
msg = "No category created" |
| 262 |
changed = False |
| 263 |
if category_id: |
| 264 |
changed = True |
| 265 |
msg = "Category '%s' created." % category_spec.name |
| 266 |
|
| 267 |
self.module.exit_json(changed=changed, |
| 268 |
category_results=dict(msg=msg, category_id=category_id)) |
| 269 |
|
| 270 |
def state_unchanged(self): |
| 271 |
"""Return unchanged state.""" |
| 272 |
self.module.exit_json(changed=False) |
| 273 |
|
| 274 |
def state_update_category(self): |
| 275 |
"""Update category.""" |
| 276 |
category_id = self.global_categories[self.category_name]['category_id'] |
| 277 |
changed = False |
| 278 |
results = dict(msg="Category %s is unchanged." % self.category_name, |
| 279 |
category_id=category_id) |
| 280 |
|
| 281 |
category_update_spec = self.category_service.UpdateSpec() |
| 282 |
change_list = [] |
| 283 |
old_cat_desc = self.global_categories[self.category_name]['category_description'] |
| 284 |
new_cat_desc = self.params.get('category_description') |
| 285 |
if new_cat_desc and new_cat_desc != old_cat_desc: |
| 286 |
category_update_spec.description = new_cat_desc |
| 287 |
results['msg'] = 'Category %s updated.' % self.category_name |
| 288 |
change_list.append(True) |
| 289 |
|
| 290 |
new_cat_name = self.params.get('new_category_name') |
| 291 |
if new_cat_name in self.global_categories: |
| 292 |
self.module.fail_json(msg="Unable to rename %s as %s already" |
| 293 |
" exists in configuration." % (self.category_name, new_cat_name)) |
| 294 |
old_cat_name = self.global_categories[self.category_name]['category_name'] |
| 295 |
|
| 296 |
if new_cat_name and new_cat_name != old_cat_name: |
| 297 |
category_update_spec.name = new_cat_name |
| 298 |
results['msg'] = 'Category %s updated.' % self.category_name |
| 299 |
change_list.append(True) |
| 300 |
|
| 301 |
if any(change_list): |
| 302 |
try: |
| 303 |
self.category_service.update(category_id, category_update_spec) |
| 304 |
changed = True |
| 305 |
except Error as error: |
| 306 |
self.module.fail_json(msg="%s" % self.get_error_message(error)) |
| 307 |
|
| 308 |
self.module.exit_json(changed=changed, |
| 309 |
category_results=results) |
| 310 |
|
| 311 |
def state_delete_category(self): |
| 312 |
"""Delete category.""" |
| 313 |
category_id = self.global_categories[self.category_name]['category_id'] |
| 314 |
try: |
| 315 |
self.category_service.delete(category_id=category_id) |
| 316 |
except Error as error: |
| 317 |
self.module.fail_json(msg="%s" % self.get_error_message(error)) |
| 318 |
self.module.exit_json(changed=True, |
| 319 |
category_results=dict(msg="Category '%s' deleted." % self.category_name, |
| 320 |
category_id=category_id)) |
| 321 |
|
| 322 |
def check_category_status(self): |
| 323 |
""" |
| 324 |
Check if category exists or not |
| 325 |
Returns: 'present' if category found, else 'absent' |
| 326 |
|
| 327 |
""" |
| 328 |
if self.category_name in self.global_categories: |
| 329 |
return 'present' |
| 330 |
return 'absent' |
| 331 |
|
| 332 |
def get_all_categories(self): |
| 333 |
"""Retrieve all category information.""" |
| 334 |
try: |
| 335 |
|
| 336 |
for category in self.category_service.list(): |
| 337 |
category_obj = self.category_service.get(category) |
| 338 |
self.global_categories[category_obj.name] = dict( |
| 339 |
category_description=category_obj.description, |
| 340 |
category_used_by=category_obj.used_by, |
| 341 |
category_cardinality=str(category_obj.cardinality), |
| 342 |
category_associable_types=category_obj.associable_types, |
| 343 |
category_id=category_obj.id, |
| 344 |
category_name=category_obj.name, |
| 345 |
) |
| 346 |
except Error as error: |
| 347 |
self.module.fail_json(msg=self.get_error_message(error)) |
| 348 |
except Exception as exc_err: |
| 349 |
self.module.fail_json(msg=to_native(exc_err)) |
| 350 |
|
| 351 |
|
| 352 |
def main(): |
| 353 |
argument_spec = rest_compatible_argument_spec() |
| 354 |
argument_spec.update( |
| 355 |
category_name=dict(type='str', required=True), |
| 356 |
category_description=dict(type='str', default='', required=False), |
| 357 |
category_cardinality=dict(type='str', choices=["multiple", "single"], default="multiple"), |
| 358 |
new_category_name=dict(type='str'), |
| 359 |
state=dict(type='str', choices=['present', 'absent'], default='present'), |
| 360 |
associable_object_types=dict( |
| 361 |
type='list', |
| 362 |
choices=[ |
| 363 |
'All objects', 'Cluster', 'Content Library', 'Datacenter', |
| 364 |
'Datastore', 'Datastore Cluster', 'Distributed Port Group', 'Distributed Switch', |
| 365 |
'Folder', 'Host', 'Library item', 'Network', |
| 366 |
'Host Network', 'Opaque Network', 'Resource Pool', 'vApp', |
| 367 |
'Virtual Machine', |
| 368 |
], |
| 369 |
elements='str', |
| 370 |
), |
| 371 |
) |
| 372 |
module = AnsibleModule(argument_spec=argument_spec) |
| 373 |
|
| 374 |
vmware_category = VmwareCategory(module) |
| 375 |
vmware_category.ensure_state() |
| 376 |
|
| 377 |
|
| 378 |
if __name__ == '__main__': |
| 379 |
main() |