Debian Codegraph @

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

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
5 # SPDX-License-Identifier: GPL-3.0-or-later
6
7 from __future__ import absolute_import, division, print_function
8 __metaclass__ = type
9
10
11 DOCUMENTATION = r'''
12 ---
13 module: vmware_host_custom_attributes
14 short_description: Manage custom attributes from VMware for the given ESXi host
15 description:
16 - This module can be used to add, remove and update custom attributes for the given ESXi host.
17 author:
18 - Hunter Christain (@exp-hc)
19 options:
20 esxi_hostname:
21 description:
22 - Name of the ESXi host to work with.
23 - This is a required parameter
24 required: true
25 type: str
26 state:
27 description:
28 - The action to take.
29 - If set to V(present), then custom attribute is added or updated.
30 - If set to V(absent), then custom attribute is removed.
31 default: 'present'
32 choices: ['present', 'absent']
33 type: str
34 attributes:
35 description:
36 - A list of name and value of custom attributes that needs to be manage.
37 - Value of custom attribute is not required and will be ignored, if O(state=absent).
38 suboptions:
39 name:
40 description:
41 - Name of the attribute.
42 type: str
43 required: true
44 value:
45 description:
46 - Value of the attribute.
47 type: str
48 default: ''
49 default: []
50 type: list
51 elements: dict
52 extends_documentation_fragment:
53 - vmware.vmware.base_options
54
55 '''
56
57 EXAMPLES = r'''
58 - name: Add ESXi host custom attributes
59 community.vmware.vmware_host_custom_attributes:
60 hostname: "{{ vcenter_hostname }}"
61 username: "{{ vcenter_username }}"
62 password: "{{ vcenter_password }}"
63 esxi_hostname: host1
64 state: present
65 attributes:
66 - name: MyAttribute
67 value: MyValue
68 delegate_to: localhost
69 register: attributes
70
71 - name: Remove ESXi host Attribute
72 community.vmware.vmware_host_custom_attributes:
73 hostname: "{{ vcenter_hostname }}"
74 username: "{{ vcenter_username }}"
75 password: "{{ vcenter_password }}"
76 esxi_hostname: host1
77 state: absent
78 attributes:
79 - name: MyAttribute
80 delegate_to: localhost
81 register: attributes
82 '''
83
84 RETURN = r'''
85 custom_attributes:
86 description: metadata about the ESXi host attributes
87 returned: changed
88 type: dict
89 sample: {
90 "mycustom": "my_custom_value",
91 "mycustom_2": "my_custom_value_2",
92 "sample_1": "sample_1_value",
93 "sample_2": "sample_2_value",
94 "sample_3": "sample_3_value"
95 }
96 '''
97
98 try:
99 from pyVmomi import vim
100 except ImportError:
101 pass
102
103 from ansible.module_utils.basic import AnsibleModule
104 from ansible_collections.community.vmware.plugins.module_utils.vmware import PyVmomi
105 from ansible_collections.vmware.vmware.plugins.module_utils.argument_spec import base_argument_spec
106
107
108 class HostAttributeManager(PyVmomi):
109 def __init__(self, module):
110 super(HostAttributeManager, self).__init__(module)
111 self.esxi_hostname = module.params.get('esxi_hostname')
112 self.host = self.find_hostsystem_by_name(self.esxi_hostname)
113
114 def set_custom_field(self, host, user_fields):
115 result_fields = dict()
116 change_list = list()
117 changed = False
118
119 for field in user_fields:
120 field_key = self.check_exists(field['name'])
121 found = False
122 field_value = field.get('value', '')
123
124 for k, v in [(x.name, v.value) for x in self.custom_field_mgr for v in host.customValue if x.key == v.key]:
125 if k == field['name']:
126 found = True
127 if v != field_value:
128 if not self.module.check_mode:
129 self.content.customFieldsManager.SetField(entity=host, key=field_key.key, value=field_value)
130 result_fields[k] = field_value
131 change_list.append(True)
132 if not found and field_value != "":
133 if not field_key and not self.module.check_mode:
134 field_key = self.content.customFieldsManager.AddFieldDefinition(name=field['name'], moType=vim.HostSystem)
135 change_list.append(True)
136 if not self.module.check_mode:
137 self.content.customFieldsManager.SetField(entity=host, key=field_key.key, value=field_value)
138 result_fields[field['name']] = field_value
139
140 if any(change_list):
141 changed = True
142
143 return {'changed': changed, 'failed': False, 'custom_attributes': result_fields}
144
145 def check_exists(self, field):
146 for x in self.custom_field_mgr:
147 # The custom attribute should be either global (managedObjectType == None) or host specific
148 if x.managedObjectType in (None, vim.HostSystem) and x.name == field:
149 return x
150 return False
151
152
153 def main():
154 argument_spec = base_argument_spec()
155 argument_spec.update(
156 esxi_hostname=dict(type='str', required=True),
157 state=dict(type='str', default='present',
158 choices=['absent', 'present']),
159 attributes=dict(
160 type='list',
161 default=[],
162 elements='dict',
163 options=dict(
164 name=dict(type='str', required=True),
165 value=dict(type='str', default=''),
166 )
167 ),
168 )
169
170 module = AnsibleModule(
171 argument_spec=argument_spec,
172 supports_check_mode=True,
173 )
174
175 pyv = HostAttributeManager(module)
176 results = {'changed': False, 'failed': False, 'instance': dict()}
177
178 # Check if the virtual machine exists before continuing
179 host = pyv.host
180
181 if host:
182 # host already exists
183 if module.params['state'] == "present":
184 results = pyv.set_custom_field(host, module.params['attributes'])
185 elif module.params['state'] == "absent":
186 results = pyv.set_custom_field(host, module.params['attributes'])
187 module.exit_json(**results)
188 else:
189 # host does not exists
190 module.fail_json(msg="Unable to manage custom attributes for non-existing"
191 " host %s" % pyv.esxi_hostname)
192
193
194 if __name__ == '__main__':
195 main()