Debian Codegraph @

ansible_collections/community/general/plugins/modules/manageiq_user.py

raw
1 #!/usr/bin/python
2 # Copyright (c) 2017, Daniel Korn <[email protected]>
3 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
4 # SPDX-License-Identifier: GPL-3.0-or-later
5
6 from __future__ import annotations
7
8 DOCUMENTATION = r"""
9 module: manageiq_user
10
11 short_description: Management of users in ManageIQ
12 extends_documentation_fragment:
13 - community.general._manageiq
14 - community.general._attributes
15
16 author: Daniel Korn (@dkorn)
17 description:
18 - The manageiq_user module supports adding, updating and deleting users in ManageIQ.
19 attributes:
20 check_mode:
21 support: none
22 diff_mode:
23 support: none
24
25 options:
26 state:
27 type: str
28 description:
29 - V(absent) - user should not exist,
30 - V(present) - user should be.
31 choices: ['absent', 'present']
32 default: 'present'
33 userid:
34 type: str
35 description:
36 - The unique userid in manageiq, often mentioned as username.
37 required: true
38 name:
39 type: str
40 description:
41 - The users' full name.
42 password:
43 type: str
44 description:
45 - The users' password.
46 group:
47 type: str
48 description:
49 - The name of the group to which the user belongs.
50 email:
51 type: str
52 description:
53 - The users' E-mail address.
54 update_password:
55 type: str
56 default: always
57 choices: ['always', 'on_create']
58 description:
59 - V(always) updates passwords unconditionally.
60 - V(on_create) only sets the password for a newly created user.
61 """
62
63 EXAMPLES = r"""
64 - name: Create a new user in ManageIQ
65 community.general.manageiq_user:
66 userid: 'jdoe'
67 name: 'Jane Doe'
68 password: 'VerySecret'
69 group: 'EvmGroup-user'
70 email: '[email protected]'
71 manageiq_connection:
72 url: 'http://127.0.0.1:3000'
73 username: 'admin'
74 password: 'smartvm'
75 validate_certs: false # only do this when you trust the network!
76
77 - name: Create a new user in ManageIQ using a token
78 community.general.manageiq_user:
79 userid: 'jdoe'
80 name: 'Jane Doe'
81 password: 'VerySecret'
82 group: 'EvmGroup-user'
83 email: '[email protected]'
84 manageiq_connection:
85 url: 'http://127.0.0.1:3000'
86 token: 'sometoken'
87 validate_certs: false # only do this when you trust the network!
88
89 - name: Delete a user in ManageIQ
90 community.general.manageiq_user:
91 state: 'absent'
92 userid: 'jdoe'
93 manageiq_connection:
94 url: 'http://127.0.0.1:3000'
95 username: 'admin'
96 password: 'smartvm'
97 validate_certs: false # only do this when you trust the network!
98
99 - name: Delete a user in ManageIQ using a token
100 community.general.manageiq_user:
101 state: 'absent'
102 userid: 'jdoe'
103 manageiq_connection:
104 url: 'http://127.0.0.1:3000'
105 token: 'sometoken'
106 validate_certs: false # only do this when you trust the network!
107
108 - name: Update email of user in ManageIQ
109 community.general.manageiq_user:
110 userid: 'jdoe'
111 email: '[email protected]'
112 manageiq_connection:
113 url: 'http://127.0.0.1:3000'
114 username: 'admin'
115 password: 'smartvm'
116 validate_certs: false # only do this when you trust the network!
117
118 - name: Update email of user in ManageIQ using a token
119 community.general.manageiq_user:
120 userid: 'jdoe'
121 email: '[email protected]'
122 manageiq_connection:
123 url: 'http://127.0.0.1:3000'
124 token: 'sometoken'
125 validate_certs: false # only do this when you trust the network!
126 """
127
128 RETURN = r"""
129 """
130
131 from ansible.module_utils.basic import AnsibleModule
132
133 from ansible_collections.community.general.plugins.module_utils._manageiq import ManageIQ, manageiq_argument_spec
134
135
136 class ManageIQUser:
137 """
138 Object to execute user management operations in manageiq.
139 """
140
141 def __init__(self, manageiq):
142 self.manageiq = manageiq
143
144 self.module = self.manageiq.module
145 self.api_url = self.manageiq.api_url
146 self.client = self.manageiq.client
147
148 def group_id(self, description):
149 """Search for group id by group description.
150
151 Returns:
152 the group id, or send a module Fail signal if group not found.
153 """
154 group = self.manageiq.find_collection_resource_by("groups", description=description)
155 if not group: # group doesn't exist
156 self.module.fail_json(msg=f"group {description} does not exist in manageiq")
157
158 return group["id"]
159
160 def user(self, userid):
161 """Search for user object by userid.
162
163 Returns:
164 the user, or None if user not found.
165 """
166 return self.manageiq.find_collection_resource_by("users", userid=userid)
167
168 def compare_user(self, user, name, group_id, password, email):
169 """Compare user fields with new field values.
170
171 Returns:
172 false if user fields have some difference from new fields, true o/w.
173 """
174 found_difference = (
175 (name and user["name"] != name)
176 or (password is not None)
177 or (email and user["email"] != email)
178 or (group_id and user["current_group_id"] != group_id)
179 )
180
181 return not found_difference
182
183 def delete_user(self, user):
184 """Deletes a user from manageiq.
185
186 Returns:
187 a short message describing the operation executed.
188 """
189 try:
190 url = f"{self.api_url}/users/{user['id']}"
191 result = self.client.post(url, action="delete")
192 except Exception as e:
193 self.module.fail_json(msg=f"failed to delete user {user['userid']}: {e}")
194
195 return dict(changed=True, msg=result["message"])
196
197 def edit_user(self, user, name, group, password, email):
198 """Edit a user from manageiq.
199
200 Returns:
201 a short message describing the operation executed.
202 """
203 group_id = None
204 url = f"{self.api_url}/users/{user['id']}"
205
206 resource = dict(userid=user["userid"])
207 if group is not None:
208 group_id = self.group_id(group)
209 resource["group"] = dict(id=group_id)
210 if name is not None:
211 resource["name"] = name
212 if email is not None:
213 resource["email"] = email
214
215 # if there is a password param, but 'update_password' is 'on_create'
216 # then discard the password (since we're editing an existing user)
217 if self.module.params["update_password"] == "on_create":
218 password = None
219 if password is not None:
220 resource["password"] = password
221
222 # check if we need to update ( compare_user is true is no difference found )
223 if self.compare_user(user, name, group_id, password, email):
224 return dict(changed=False, msg=f"user {user['userid']} is not changed.")
225
226 # try to update user
227 try:
228 result = self.client.post(url, action="edit", resource=resource)
229 except Exception as e:
230 self.module.fail_json(msg=f"failed to update user {user['userid']}: {e}")
231
232 return dict(changed=True, msg=f"successfully updated the user {user['userid']}: {result}")
233
234 def create_user(self, userid, name, group, password, email):
235 """Creates the user in manageiq.
236
237 Returns:
238 the created user id, name, created_on timestamp,
239 updated_on timestamp, userid and current_group_id.
240 """
241 # check for required arguments
242 for key, value in dict(name=name, group=group, password=password).items():
243 if value in (None, ""):
244 self.module.fail_json(msg=f"missing required argument: {key}")
245
246 group_id = self.group_id(group)
247 url = f"{self.api_url}/users"
248
249 resource = {"userid": userid, "name": name, "password": password, "group": {"id": group_id}}
250 if email is not None:
251 resource["email"] = email
252
253 # try to create a new user
254 try:
255 result = self.client.post(url, action="create", resource=resource)
256 except Exception as e:
257 self.module.fail_json(msg=f"failed to create user {userid}: {e}")
258
259 return dict(changed=True, msg=f"successfully created the user {userid}: {result['results']}")
260
261
262 def main():
263 argument_spec = dict(
264 userid=dict(required=True, type="str"),
265 name=dict(),
266 password=dict(no_log=True),
267 group=dict(),
268 email=dict(),
269 state=dict(choices=["absent", "present"], default="present"),
270 update_password=dict(choices=["always", "on_create"], default="always"),
271 )
272 # add the manageiq connection arguments to the arguments
273 argument_spec.update(manageiq_argument_spec())
274
275 module = AnsibleModule(
276 argument_spec=argument_spec,
277 )
278
279 userid = module.params["userid"]
280 name = module.params["name"]
281 password = module.params["password"]
282 group = module.params["group"]
283 email = module.params["email"]
284 state = module.params["state"]
285
286 manageiq = ManageIQ(module)
287 manageiq_user = ManageIQUser(manageiq)
288
289 user = manageiq_user.user(userid)
290
291 # user should not exist
292 if state == "absent":
293 # if we have a user, delete it
294 if user:
295 res_args = manageiq_user.delete_user(user)
296 # if we do not have a user, nothing to do
297 else:
298 res_args = dict(changed=False, msg=f"user {userid}: does not exist in manageiq")
299
300 # user should exist
301 if state == "present":
302 # if we have a user, edit it
303 if user:
304 res_args = manageiq_user.edit_user(user, name, group, password, email)
305 # if we do not have a user, create it
306 else:
307 res_args = manageiq_user.create_user(userid, name, group, password, email)
308
309 module.exit_json(**res_args)
310
311
312 if __name__ == "__main__":
313 main()