Debian Codegraph @

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

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright, (c) 2022, Mario Lenz <[email protected]>
5 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
6 # SPDX-License-Identifier: GPL-3.0-or-later
7
8 from __future__ import absolute_import, division, print_function
9 __metaclass__ = type
10
11
12 DOCUMENTATION = r'''
13 ---
14 module: vmware_custom_attribute_manager
15 version_added: '3.2.0'
16 short_description: Manage custom attributes from VMware for the given vSphere object
17 description:
18 - This module can be used to add, remove and update custom attributes for the given vSphere object.
19 author:
20 - Mario Lenz (@mariolenz)
21 options:
22 custom_attributes:
23 description:
24 - A list of name and value of custom attributes that needs to be manage.
25 - Value of custom attribute is not required and will be ignored if O(state=absent).
26 suboptions:
27 name:
28 description:
29 - Name of the attribute.
30 type: str
31 required: true
32 value:
33 description:
34 - Value of the attribute.
35 type: str
36 default: ''
37 required: true
38 type: list
39 elements: dict
40 object_name:
41 description:
42 - Name of the vSphere object to work with.
43 type: str
44 required: true
45 object_type:
46 description:
47 - Type of the object the custom attribute is associated with.
48 type: str
49 choices:
50 - Cluster
51 - Datacenter
52 - Datastore
53 - DistributedVirtualPortgroup
54 - DistributedVirtualSwitch
55 - Folder
56 - HostSystem
57 - ResourcePool
58 - VirtualMachine
59 required: true
60 state:
61 description:
62 - If set to V(present), the custom attribute is set to the given value.
63 - If set to V(absent), the custom attribute is cleared. The given value is ignored in this case.
64 default: 'present'
65 choices: ['present', 'absent']
66 type: str
67 extends_documentation_fragment:
68 - vmware.vmware.base_options
69
70 '''
71
72 EXAMPLES = r'''
73 - name: Add virtual machine custom attributes
74 community.vmware.vmware_custom_attribute_manager:
75 hostname: "{{ vcenter_hostname }}"
76 username: "{{ vcenter_username }}"
77 password: "{{ vcenter_password }}"
78 object_name: vm1
79 object_type: VirtualMachine
80 state: present
81 custom_attributes:
82 - name: MyAttribute
83 value: MyValue
84 delegate_to: localhost
85
86 - name: Add multiple virtual machine custom attributes
87 community.vmware.vmware_custom_attribute_manager:
88 hostname: "{{ vcenter_hostname }}"
89 username: "{{ vcenter_username }}"
90 password: "{{ vcenter_password }}"
91 object_name: vm1
92 object_type: VirtualMachine
93 state: present
94 custom_attributes:
95 - name: MyAttribute
96 value: MyValue
97 - name: MyAttribute2
98 value: MyValue2
99 delegate_to: localhost
100
101 - name: Remove virtual machine Attribute
102 community.vmware.vmware_custom_attribute_manager:
103 hostname: "{{ vcenter_hostname }}"
104 username: "{{ vcenter_username }}"
105 password: "{{ vcenter_password }}"
106 object_name: vm1
107 object_type: VirtualMachine
108 state: absent
109 custom_attributes:
110 - name: MyAttribute
111 delegate_to: localhost
112 register: attributes
113 '''
114
115 RETURN = r'''
116 '''
117
118 try:
119 from pyVmomi import vim
120 except ImportError:
121 pass
122
123 from ansible.module_utils.basic import AnsibleModule
124 from ansible_collections.community.vmware.plugins.module_utils.vmware import PyVmomi, find_obj
125 from ansible_collections.vmware.vmware.plugins.module_utils.argument_spec import base_argument_spec
126
127
128 class CustomAttributeManager(PyVmomi):
129 def __init__(self, module):
130 super(CustomAttributeManager, self).__init__(module)
131
132 if not self.is_vcenter():
133 self.module.fail_json(msg="You have to connect to a vCenter server!")
134
135 object_types_map = {
136 'Cluster': vim.ClusterComputeResource,
137 'Datacenter': vim.Datacenter,
138 'Datastore': vim.Datastore,
139 'DistributedVirtualPortgroup': vim.DistributedVirtualPortgroup,
140 'DistributedVirtualSwitch': vim.DistributedVirtualSwitch,
141 'Folder': vim.Folder,
142 'HostSystem': vim.HostSystem,
143 'ResourcePool': vim.ResourcePool,
144 'VirtualMachine': vim.VirtualMachine
145 }
146
147 self.object_type = object_types_map[self.params['object_type']]
148
149 self.object_name = self.params['object_name']
150 self.obj = find_obj(self.content, [self.object_type], self.params['object_name'])
151 if self.obj is None:
152 module.fail_json(msg="Unable to manage custom attributes for non-existing"
153 " object %s." % self.object_name)
154
155 self.ca_list = self.params['custom_attributes'].copy()
156
157 for ca in self.ca_list:
158 for av_field in self.obj.availableField:
159 if av_field.name == ca['name']:
160 ca['key'] = av_field.key
161 break
162
163 for ca in self.ca_list:
164 if 'key' not in ca:
165 self.module.fail_json(msg="Custom attribute %s does not exist for object type %s." % (ca['name'], self.params['object_type']))
166
167 def set_custom_attributes(self):
168 changed = False
169 obj_cas_set = [x.key for x in self.obj.value]
170
171 for ca in self.ca_list:
172 if ca['key'] not in obj_cas_set:
173 changed = True
174 if not self.module.check_mode:
175 self.content.customFieldsManager.SetField(entity=self.obj, key=ca['key'], value=ca['value'])
176 continue
177 for x in self.obj.customValue:
178 if ca['key'] == x.key and ca['value'] != x.value:
179 changed = True
180 if not self.module.check_mode:
181 self.content.customFieldsManager.SetField(entity=self.obj, key=ca['key'], value=ca['value'])
182
183 return {'changed': changed, 'failed': False}
184
185 def remove_custom_attributes(self):
186 changed = False
187
188 for ca in self.ca_list:
189 for x in self.obj.customValue:
190 if ca['key'] == x.key and x.value != '':
191 changed = True
192 if not self.module.check_mode:
193 self.content.customFieldsManager.SetField(entity=self.obj, key=ca['key'], value='')
194
195 return {'changed': changed, 'failed': False}
196
197
198 def main():
199 argument_spec = base_argument_spec()
200 argument_spec.update(
201 custom_attributes=dict(
202 type='list',
203 required=True,
204 elements='dict',
205 options=dict(
206 name=dict(type='str', required=True),
207 value=dict(type='str', default=''),
208 )
209 ),
210 object_name=dict(type='str', required=True),
211 object_type=dict(type='str', required=True, choices=[
212 'Cluster',
213 'Datacenter',
214 'Datastore',
215 'DistributedVirtualPortgroup',
216 'DistributedVirtualSwitch',
217 'Folder',
218 'HostSystem',
219 'ResourcePool',
220 'VirtualMachine'
221 ]),
222 state=dict(type='str', default='present',
223 choices=['absent', 'present']),
224 )
225
226 module = AnsibleModule(
227 argument_spec=argument_spec,
228 supports_check_mode=True,
229 )
230
231 pyv = CustomAttributeManager(module)
232 results = {'changed': False, 'failed': False}
233
234 if module.params['state'] == "present":
235 results = pyv.set_custom_attributes()
236 elif module.params['state'] == "absent":
237 results = pyv.remove_custom_attributes()
238
239 module.exit_json(**results)
240
241
242 if __name__ == '__main__':
243 main()