Debian Codegraph @

ansible_collections/community/vmware/plugins/modules/vmware_guest_custom_attributes.py

raw
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_guest_custom_attributes
16 short_description: Manage custom attributes from VMware for the given virtual machine
17 description:
18 - This module can be used to add, remove and update custom attributes for the given virtual machine.
19 author:
20 - Jimmy Conner (@cigamit)
21 - Abhijeet Kasurde (@Akasurde)
22 options:
23 name:
24 description:
25 - Name of the virtual machine to work with.
26 - This is required parameter, if O(uuid) or O(moid) is not supplied.
27 type: str
28 state:
29 description:
30 - The action to take.
31 - If set to V(present), then custom attribute is added or updated.
32 - If set to V(absent), then custom attribute value is removed.
33 default: 'present'
34 choices: ['present', 'absent']
35 type: str
36 uuid:
37 description:
38 - UUID of the virtual machine to manage if known. This is VMware's unique identifier.
39 - This is required parameter, if O(name) or O(moid) is not supplied.
40 type: str
41 moid:
42 description:
43 - Managed Object ID of the instance to manage if known, this is a unique identifier only within a single vCenter instance.
44 - This is required if O(name) or O(uuid) is not supplied.
45 type: str
46 use_instance_uuid:
47 description:
48 - Whether to use the VMware instance UUID rather than the BIOS UUID.
49 default: false
50 type: bool
51 folder:
52 description:
53 - Absolute path to find an existing guest.
54 - This is required parameter, if O(name) is supplied and multiple virtual machines with same name are found.
55 type: str
56 datacenter:
57 description:
58 - Datacenter name where the virtual machine is located in.
59 type: str
60 attributes:
61 description:
62 - A list of name and value of custom attributes that needs to be manage.
63 - Value of custom attribute is not required and will be ignored, if O(state=absent).
64 suboptions:
65 name:
66 description:
67 - Name of the attribute.
68 type: str
69 required: true
70 value:
71 description:
72 - Value of the attribute.
73 type: str
74 default: ''
75 default: []
76 type: list
77 elements: dict
78 extends_documentation_fragment:
79 - vmware.vmware.base_options
80
81 '''
82
83 EXAMPLES = r'''
84 - name: Add virtual machine custom attributes
85 community.vmware.vmware_guest_custom_attributes:
86 hostname: "{{ vcenter_hostname }}"
87 username: "{{ vcenter_username }}"
88 password: "{{ vcenter_password }}"
89 uuid: 421e4592-c069-924d-ce20-7e7533fab926
90 state: present
91 attributes:
92 - name: MyAttribute
93 value: MyValue
94 delegate_to: localhost
95 register: attributes
96
97 - name: Add multiple virtual machine custom attributes
98 community.vmware.vmware_guest_custom_attributes:
99 hostname: "{{ vcenter_hostname }}"
100 username: "{{ vcenter_username }}"
101 password: "{{ vcenter_password }}"
102 uuid: 421e4592-c069-924d-ce20-7e7533fab926
103 state: present
104 attributes:
105 - name: MyAttribute
106 value: MyValue
107 - name: MyAttribute2
108 value: MyValue2
109 delegate_to: localhost
110 register: attributes
111
112 - name: Remove virtual machine Attribute
113 community.vmware.vmware_guest_custom_attributes:
114 hostname: "{{ vcenter_hostname }}"
115 username: "{{ vcenter_username }}"
116 password: "{{ vcenter_password }}"
117 uuid: 421e4592-c069-924d-ce20-7e7533fab926
118 state: absent
119 attributes:
120 - name: MyAttribute
121 delegate_to: localhost
122 register: attributes
123
124 - name: Remove virtual machine Attribute using Virtual Machine MoID
125 community.vmware.vmware_guest_custom_attributes:
126 hostname: "{{ vcenter_hostname }}"
127 username: "{{ vcenter_username }}"
128 password: "{{ vcenter_password }}"
129 moid: vm-42
130 state: absent
131 attributes:
132 - name: MyAttribute
133 delegate_to: localhost
134 register: attributes
135 '''
136
137 RETURN = r'''
138 custom_attributes:
139 description: metadata about the virtual machine attributes
140 returned: always
141 type: dict
142 sample: {
143 "mycustom": "my_custom_value",
144 "mycustom_2": "my_custom_value_2",
145 "sample_1": "sample_1_value",
146 "sample_2": "sample_2_value",
147 "sample_3": "sample_3_value"
148 }
149 '''
150
151 try:
152 from pyVmomi import vim
153 except ImportError:
154 pass
155
156 from ansible.module_utils.basic import AnsibleModule
157 from ansible_collections.community.vmware.plugins.module_utils.vmware import PyVmomi
158 from ansible_collections.vmware.vmware.plugins.module_utils.argument_spec import base_argument_spec
159
160
161 class VmAttributeManager(PyVmomi):
162 def __init__(self, module):
163 super(VmAttributeManager, self).__init__(module)
164
165 # Initialize the variables.
166 # Make the diff_config variable to check the difference between a new and existing config.
167 # https://docs.ansible.com/ansible/latest/reference_appendices/common_return_values.html#diff
168 self.diff_config = dict(before={}, after={})
169
170 # reuslt_fields is the variable for the return value after the job finish.
171 self.result_fields = {}
172
173 # update_custom_attributes is the variable for storing the custom attributes to update.
174 self.update_custom_attributes = []
175
176 # changed variable is the flag of whether the target changed.
177 # https://docs.ansible.com/ansible/latest/reference_appendices/common_return_values.html#changed
178 self.changed = False
179
180 def set_custom_field(self, vm, user_fields):
181 """Add or update the custom attribute and value.
182
183 Args:
184 vm (vim.VirtualMachine): The managed object of a virtual machine.
185 user_fields (list): list of the specified custom attributes by user.
186
187 Returns:
188 The dictionary for the ansible return value.
189 """
190 self.check_exists(vm, user_fields)
191 if self.module.check_mode is True:
192 self.module.exit_json(changed=self.changed, diff=self.diff_config)
193
194 # If update_custom_attributes variable has elements, add or update the custom attributes and values.
195 for field in self.update_custom_attributes:
196 if 'key' in field:
197 self.content.customFieldsManager.SetField(entity=vm, key=field['key'], value=field['value'])
198 else:
199 field_key = self.content.customFieldsManager.AddFieldDefinition(name=field['name'],
200 moType=vim.VirtualMachine)
201 self.content.customFieldsManager.SetField(entity=vm, key=field_key.key, value=field['value'])
202
203 # Set result_fields for the return value.
204 self.result_fields[field['name']] = field['value']
205
206 return {'changed': self.changed, 'failed': False, 'custom_attributes': self.result_fields}
207
208 def remove_custom_field(self, vm, user_fields):
209 """Remove the value from the existing custom attribute.
210
211 Args:
212 vm (vim.VirtualMachine): The managed object of a virtual machine.
213 user_fields (list): list of the specified custom attributes by user.
214
215 Returns:
216 The dictionary for the ansible return value.
217 """
218 # All custom attribute values will set blank to remove the value.
219 for v in user_fields:
220 v['value'] = ''
221
222 self.check_exists(vm, user_fields)
223 if self.module.check_mode is True:
224 self.module.exit_json(changed=self.changed, diff=self.diff_config)
225
226 # If update_custom_attributes variable has elements, remove the custom attribute values.
227 for field in self.update_custom_attributes:
228 self.content.customFieldsManager.SetField(entity=vm, key=field['key'], value=field['value'])
229
230 # Set result_fields for the return value.
231 self.result_fields[field['name']] = field['value']
232
233 return {'changed': self.changed, 'failed': False, 'custom_attributes': self.result_fields}
234
235 def check_exists(self, vm, user_fields):
236 """Check the existing custom attributes and values.
237
238 In the function, the below processing is executed.
239
240 Gather the existing custom attributes from the virtual machine and make update_custom_attributes for updating
241 if it has differences between the existing configuration and the user_fields.
242
243 And set diff key for checking between before and after configuration to self.diff_config.
244
245 Args:
246 vm (vim.VirtualMachine): The managed object of a virtual machine.
247 user_fields (list): list of the specified custom attributes by user.
248 """
249 # Gather the available existing custom attributes based on user_fields
250 existing_custom_attributes = []
251 for k, n in [(x.key, x.name) for x in self.custom_field_mgr
252 # vmware_guest_custome_attributes must work with self moref type of custom attributes or with global custom attributes
253 if x.managedObjectType == vim.VirtualMachine or x.managedObjectType is None
254 for v in user_fields
255 if x.name == v['name']]:
256 existing_custom_attributes.append({
257 "key": k,
258 "name": n
259 })
260
261 # Gather the values of set the custom attribute.
262 for e in existing_custom_attributes:
263 for v in vm.customValue:
264 if e['key'] == v.key:
265 e['value'] = v.value
266
267 # When add custom attribute as a new one, it has not the value key.
268 # Add the value key to avoid unintended behavior in the difference check.
269 if 'value' not in e:
270 e['value'] = ''
271
272 # Select the custom attribute and value to update the configuration.
273 _user_fields_for_diff = []
274 for v in user_fields:
275 for e in existing_custom_attributes:
276 if v['name'] == e['name'] and v['value'] != e['value']:
277 self.update_custom_attributes.append({
278 "name": v['name'],
279 "value": v['value'],
280 "key": e['key']
281 })
282
283 if v['name'] == e['name']:
284 _user_fields_for_diff.append({
285 "name": v['name'],
286 "value": v['value']
287 })
288 # Add the custom attribute as a new one if the state is present and existing_custom_attribute has not the custom attribute name.
289 if v['name'] not in [x['name'] for x in existing_custom_attributes] and self.params['state'] == "present":
290 self.update_custom_attributes.append(v)
291 _user_fields_for_diff.append({
292 "name": v['name'],
293 "value": v['value']
294 })
295
296 # If the custom attribute exists to update, the changed is set to True.
297 if self.update_custom_attributes:
298 self.changed = True
299
300 # Add custom_attributes key for the difference between before and after configuration to check.
301 self.diff_config['before']['custom_attributes'] = sorted(
302 [x for x in existing_custom_attributes if x.pop('key', None)], key=lambda k: k['name']
303 )
304 self.diff_config['after']['custom_attributes'] = sorted(_user_fields_for_diff, key=lambda k: k['name'])
305
306
307 def main():
308 argument_spec = base_argument_spec()
309 argument_spec.update(
310 datacenter=dict(type='str'),
311 name=dict(type='str'),
312 folder=dict(type='str'),
313 uuid=dict(type='str'),
314 moid=dict(type='str'),
315 use_instance_uuid=dict(type='bool', default=False),
316 state=dict(type='str', default='present',
317 choices=['absent', 'present']),
318 attributes=dict(
319 type='list',
320 default=[],
321 elements='dict',
322 options=dict(
323 name=dict(type='str', required=True),
324 value=dict(type='str', default=''),
325 )
326 ),
327 )
328
329 module = AnsibleModule(
330 argument_spec=argument_spec,
331 supports_check_mode=True,
332 required_one_of=[
333 ['name', 'uuid', 'moid']
334 ],
335 )
336
337 if module.params.get('folder'):
338 # FindByInventoryPath() does not require an absolute path
339 # so we should leave the input folder path unmodified
340 module.params['folder'] = module.params['folder'].rstrip('/')
341
342 pyv = VmAttributeManager(module)
343 results = {'changed': False, 'failed': False, 'instance': dict()}
344
345 # Check if the virtual machine exists before continuing
346 vm = pyv.get_vm()
347
348 if vm:
349 # virtual machine already exists
350 if module.params['state'] == "present":
351 results = pyv.set_custom_field(vm, module.params['attributes'])
352 elif module.params['state'] == "absent":
353 results = pyv.remove_custom_field(vm, module.params['attributes'])
354 module.exit_json(**results)
355 else:
356 # virtual machine does not exists
357 vm_id = (module.params.get('name') or module.params.get('uuid') or module.params.get('moid'))
358 module.fail_json(msg="Unable to manage custom attributes for non-existing"
359 " virtual machine %s" % vm_id)
360
361
362 if __name__ == '__main__':
363 main()