Debian Codegraph @

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

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: (c) 2018, Abhijeet Kasurde <[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_host_config_manager
15 short_description: Manage advanced system settings of an ESXi host
16 description:
17 - This module can be used to manage advanced system settings of an ESXi host when ESXi hostname or Cluster name is given.
18 author:
19 - Abhijeet Kasurde (@Akasurde)
20 options:
21 cluster_name:
22 description:
23 - Name of the cluster.
24 - Settings are applied to every ESXi host in given cluster.
25 - If O(esxi_hostname) is not given, this parameter is required.
26 type: str
27 esxi_hostname:
28 description:
29 - ESXi hostname.
30 - Settings are applied to this ESXi host.
31 - If O(cluster_name) is not given, this parameter is required.
32 type: str
33 options:
34 description:
35 - A dictionary of advanced system settings.
36 - Invalid options will cause module to error.
37 - Note that the list of advanced options (with description and values) can be found by running `vim-cmd hostsvc/advopt/options`.
38 default: {}
39 type: dict
40 extends_documentation_fragment:
41 - vmware.vmware.base_options
42
43 '''
44
45 EXAMPLES = r'''
46 - name: Manage Log level setting for all ESXi hosts in given Cluster
47 community.vmware.vmware_host_config_manager:
48 hostname: '{{ vcenter_hostname }}'
49 username: '{{ vcenter_username }}'
50 password: '{{ vcenter_password }}'
51 cluster_name: cluster_name
52 options:
53 'Config.HostAgent.log.level': 'info'
54 delegate_to: localhost
55
56 - name: Manage Log level setting for an ESXi host
57 community.vmware.vmware_host_config_manager:
58 hostname: '{{ vcenter_hostname }}'
59 username: '{{ vcenter_username }}'
60 password: '{{ vcenter_password }}'
61 esxi_hostname: '{{ esxi_hostname }}'
62 options:
63 'Config.HostAgent.log.level': 'verbose'
64 delegate_to: localhost
65
66 - name: Manage multiple settings for an ESXi host
67 community.vmware.vmware_host_config_manager:
68 hostname: '{{ vcenter_hostname }}'
69 username: '{{ vcenter_username }}'
70 password: '{{ vcenter_password }}'
71 esxi_hostname: '{{ esxi_hostname }}'
72 options:
73 'Config.HostAgent.log.level': 'verbose'
74 'Annotations.WelcomeMessage': 'Hello World'
75 'Config.HostAgent.plugins.solo.enableMob': false
76 delegate_to: localhost
77 '''
78
79 RETURN = r'''#
80 '''
81
82 try:
83 from pyVmomi import vim, vmodl, VmomiSupport
84 except ImportError:
85 pass
86
87 from ansible.module_utils.basic import AnsibleModule
88 from ansible_collections.community.vmware.plugins.module_utils.vmware import PyVmomi, is_boolean, is_integer, is_truthy
89 from ansible_collections.vmware.vmware.plugins.module_utils.argument_spec import base_argument_spec
90 from ansible.module_utils.common.text.converters import to_native
91
92
93 class VmwareConfigManager(PyVmomi):
94 def __init__(self, module):
95 super(VmwareConfigManager, self).__init__(module)
96 cluster_name = self.params.get('cluster_name', None)
97 esxi_host_name = self.params.get('esxi_hostname', None)
98 self.options = self.params.get('options', dict())
99 self.hosts = self.get_all_host_objs(cluster_name=cluster_name, esxi_host_name=esxi_host_name)
100
101 def set_host_configuration_facts(self):
102 changed_list = []
103 message = ''
104 for host in self.hosts:
105 option_manager = host.configManager.advancedOption
106 host_facts = {}
107 for s_option in option_manager.supportedOption:
108 host_facts[s_option.key] = dict(option_type=s_option.optionType, value=None)
109
110 for option in option_manager.QueryOptions():
111 if option.key in host_facts:
112 host_facts[option.key].update(
113 value=option.value,
114 )
115
116 change_option_list = []
117 for option_key, option_value in self.options.items():
118 if option_key in host_facts:
119 # We handle all supported types here so we can give meaningful errors.
120 option_type = host_facts[option_key]['option_type']
121 if is_boolean(option_value) and isinstance(option_type, vim.option.BoolOption):
122 option_value = is_truthy(option_value)
123 elif (isinstance(option_value, int) or is_integer(option_value))\
124 and isinstance(option_type, vim.option.IntOption):
125 option_value = VmomiSupport.vmodlTypes['int'](option_value)
126 elif (isinstance(option_value, int) or is_integer(option_value, 'long'))\
127 and isinstance(option_type, vim.option.LongOption):
128 option_value = VmomiSupport.vmodlTypes['long'](option_value)
129 elif isinstance(option_value, float) and isinstance(option_type, vim.option.FloatOption):
130 pass
131 elif isinstance(option_value, str) and isinstance(option_type, (vim.option.StringOption, vim.option.ChoiceOption)):
132 pass
133 else:
134 self.module.fail_json(msg="Provided value is of type %s."
135 " Option %s expects: %s" % (type(option_value), option_key, type(option_type)))
136
137 if option_value != host_facts[option_key]['value']:
138 change_option_list.append(vim.option.OptionValue(key=option_key, value=option_value))
139 changed_list.append(option_key)
140 else: # Don't silently drop unknown options. This prevents typos from falling through the cracks.
141 self.module.fail_json(msg="Unsupported option %s" % option_key)
142 if change_option_list:
143 if self.module.check_mode:
144 changed_suffix = ' would be changed.'
145 else:
146 changed_suffix = ' changed.'
147 if len(changed_list) > 2:
148 message = ', '.join(changed_list[:-1]) + ', and ' + str(changed_list[-1])
149 elif len(changed_list) == 2:
150 message = ' and '.join(changed_list)
151 elif len(changed_list) == 1:
152 message = changed_list[0]
153 message += changed_suffix
154 if self.module.check_mode is False:
155 try:
156 option_manager.UpdateOptions(changedValue=change_option_list)
157 except (vmodl.fault.SystemError, vmodl.fault.InvalidArgument) as e:
158 self.module.fail_json(msg="Failed to update option/s as one or more OptionValue "
159 "contains an invalid value: %s" % to_native(e.msg))
160 except vim.fault.InvalidName as e:
161 self.module.fail_json(msg="Failed to update option/s as one or more OptionValue "
162 "objects refers to a non-existent option : %s" % to_native(e.msg))
163 else:
164 message = 'All settings are already configured.'
165
166 self.module.exit_json(changed=bool(changed_list), msg=message)
167
168
169 def main():
170 argument_spec = base_argument_spec()
171 argument_spec.update(
172 cluster_name=dict(type='str', required=False),
173 esxi_hostname=dict(type='str', required=False),
174 options=dict(type='dict', default=dict(), required=False),
175 )
176
177 module = AnsibleModule(
178 argument_spec=argument_spec,
179 supports_check_mode=True,
180 required_one_of=[
181 ['cluster_name', 'esxi_hostname'],
182 ]
183 )
184
185 vmware_host_config = VmwareConfigManager(module)
186 vmware_host_config.set_host_configuration_facts()
187
188
189 if __name__ == "__main__":
190 main()