Debian Codegraph @

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

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: (c) 2022, sky-joker
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 DOCUMENTATION = r'''
12 module: vmware_host_user_manager
13 short_description: Manage users of ESXi
14 author:
15 - sky-joker (@sky-joker)
16 description:
17 - This module can add, update or delete local users on ESXi host.
18 options:
19 esxi_hostname:
20 description:
21 - Name of the ESXi host that is managing the local user.
22 type: str
23 required: true
24 user_name:
25 description:
26 - Name of the local user.
27 aliases:
28 - local_user_name
29 type: str
30 required: true
31 user_password:
32 description:
33 - The local user password.
34 - If you'd like to update the password, requires O(override_user_password=true).
35 aliases:
36 - local_user_password
37 type: str
38 user_description:
39 description:
40 - The local user description.
41 aliases:
42 - local_user_description
43 type: str
44 override_user_password:
45 description:
46 - If the local user exists and updates the password, change this parameter value is true.
47 default: false
48 type: bool
49 state:
50 description:
51 - If set to V(present), add a new local user or update information.
52 - If set to V(absent), delete the local user.
53 default: present
54 type: str
55 choices:
56 - present
57 - absent
58 extends_documentation_fragment:
59 - vmware.vmware.base_options
60 '''
61
62 EXAMPLES = r'''
63 - name: Add new local user to ESXi host
64 community.vmware.vmware_host_user_manager:
65 hostname: "{{ vcenter_hostname }}"
66 username: "{{ vcenter_username }}"
67 password: "{{ vcenter_password }}"
68 validate_certs: false
69 esxi_hostname: "{{ esxi1 }}"
70 user_name: example
71 user_description: "example user"
72 user_password: "{{ local_user_password }}"
73 state: present
74
75 - name: Update the local user password in ESXi host
76 community.vmware.vmware_host_user_manager:
77 hostname: "{{ vcenter_hostname }}"
78 username: "{{ vcenter_username }}"
79 password: "{{ vcenter_password }}"
80 validate_certs: false
81 esxi_hostname: "{{ esxi1 }}"
82 user_name: example
83 user_description: "example user"
84 user_password: "{{ local_user_password }}"
85 override_user_password: true
86 state: present
87
88 - name: Delete the local user in ESXi host
89 community.vmware.vmware_host_user_manager:
90 hostname: "{{ vcenter_hostname }}"
91 username: "{{ vcenter_username }}"
92 password: "{{ vcenter_password }}"
93 validate_certs: false
94 esxi_hostname: "{{ esxi1 }}"
95 user_name: example
96 state: absent
97 '''
98
99 RETURN = r'''
100 msg:
101 description: The executed result for the module.
102 returned: always
103 type: str
104 sample: >-
105 {
106 "msg": "Added the new user.
107 }
108 '''
109
110 try:
111 from pyVmomi import vim
112 except ImportError:
113 pass
114
115 from ansible.module_utils.basic import AnsibleModule
116 from ansible.module_utils.common.text.converters import to_text
117 from ansible_collections.community.vmware.plugins.module_utils.vmware import PyVmomi
118 from ansible_collections.vmware.vmware.plugins.module_utils.argument_spec import base_argument_spec
119
120
121 class VmwareHostUserManager(PyVmomi):
122 def __init__(self, module):
123 super(VmwareHostUserManager, self).__init__(module)
124 self.esxi_hostname = module.params["esxi_hostname"]
125 self.user_name = module.params["user_name"]
126 self.user_password = module.params["user_password"]
127 self.user_description = module.params["user_description"]
128 self.override_user_password = module.params["override_user_password"]
129 self.state = module.params["state"]
130
131 def search_user(self):
132 """
133 Search the specified user from ESXi
134
135 Returns: searched user
136 """
137 searchStr = self.user_name
138 exactMatch = True
139 findUsers = True
140 findGroups = False
141 user_account = self.host_obj.configManager.userDirectory.RetrieveUserGroups(None, searchStr, None, None, exactMatch, findUsers, findGroups)
142 return user_account
143
144 def ensure_user_info_diff(self, user_account):
145 """
146 Ensure a user information difference.
147 The method can check a user description difference only.
148 Also, it can't get the set password via vSphere API.
149
150 Returns: bool
151 """
152 if user_account.fullName != self.user_description and self.user_description is not None:
153 return True
154
155 return False
156
157 def add_user(self):
158 """
159 Add a new user
160 """
161 user_spec = vim.host.LocalAccountManager.AccountSpecification(
162 id=self.user_name,
163 description=self.user_description,
164 password=self.user_password
165 )
166 try:
167 self.host_obj.configManager.accountManager.CreateUser(user_spec)
168 except Exception as e:
169 self.module.fail_json(msg="Failed to add a new user: %s" % to_text(e.msg))
170
171 def update_user(self):
172 """
173 Update a user information
174 """
175 user_spec = vim.host.LocalAccountManager.AccountSpecification(
176 id=self.user_name,
177 description=self.user_description
178 )
179
180 if self.user_password and self.override_user_password:
181 user_spec.password = self.user_password
182
183 try:
184 self.host_obj.configManager.accountManager.UpdateUser(user_spec)
185 except Exception as e:
186 self.module.fail_json(msg="Failed to update a new password: %s" % to_text(e))
187
188 def remove_user(self):
189 """
190 Remove a user
191 """
192 try:
193 self.host_obj.configManager.accountManager.RemoveUser(self.user_name)
194 except Exception as e:
195 self.module.fail_json(msg="Failed to remove a user: %s" % to_text(e.msg))
196
197 def execute(self):
198 # The host name is unique in vCenter, so find the host from the whole.
199 self.host_obj = self.find_hostsystem_by_name(self.esxi_hostname)
200 if self.host_obj is None:
201 self.module.fail_json(msg="Cannot find the specified ESXi host: %s" % self.params['esxi_hostname'])
202
203 # Search the specified user
204 user_account = self.search_user()
205
206 changed = False
207 msg = "The change will not occur for the user information."
208 if self.state == "present":
209 if user_account:
210 user_diff = self.ensure_user_info_diff(user_account[0])
211 # If you want to update a user password, require the override_user_passwd is true.
212 if user_diff or self.override_user_password:
213 changed = True
214 if self.module.check_mode:
215 msg = "The user information will be updated."
216 else:
217 msg = "Updated the user information."
218 self.update_user()
219 else:
220 changed = True
221 if self.module.check_mode:
222 msg = "The new user will be added."
223 else:
224 msg = "Added the new user."
225 self.add_user()
226
227 if self.state == "absent":
228 if user_account:
229 changed = True
230 if self.module.check_mode:
231 msg = "The user will be removed."
232 else:
233 msg = "Removed the user."
234 self.remove_user()
235
236 self.module.exit_json(changed=changed, msg=msg)
237
238
239 def main():
240 argument_spec = base_argument_spec()
241 argument_spec.update(
242 esxi_hostname=dict(type="str", required=True),
243 user_name=dict(type="str", required=True, aliases=["local_user_name"]),
244 user_password=dict(type="str", aliases=["local_user_password"], no_log=True),
245 user_description=dict(type="str", aliases=["local_user_description"]),
246 override_user_password=dict(type="bool", default=False, no_log=False),
247 state=dict(type="str", default="present", choices=["present", "absent"])
248 )
249
250 module = AnsibleModule(
251 argument_spec=argument_spec,
252 supports_check_mode=True,
253 required_if=[
254 ('override_user_password', True, ['user_password']),
255 ]
256 )
257 vmware_host_user_manager = VmwareHostUserManager(module)
258 vmware_host_user_manager.execute()
259
260
261 if __name__ == "__main__":
262 main()