| 1 |
#!/usr/bin/python |
| 2 |
# |
| 3 |
# Copyright (c) 2025, Jeffrey van Pelt (@Thulium-Drake) <[email protected]> |
| 4 |
# Copyright (c) 2025, Kevin Quick <[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-FileCopyrightText: (c) 2025, Jeffrey van Pelt (@Thulium-Drake) <[email protected]> |
| 7 |
# SPDX-FileCopyrightText: (c) 2025, Kevin Quick <[email protected]> |
| 8 |
# SPDX-License-Identifier: GPL-3.0-or-later |
| 9 |
|
| 10 |
|
| 11 |
DOCUMENTATION = r""" |
| 12 |
module: proxmox_user |
| 13 |
short_description: User management for Proxmox VE cluster |
| 14 |
description: |
| 15 |
- Create or delete a user for Proxmox VE clusters. |
| 16 |
author: |
| 17 |
- Jeffrey van Pelt (@Thulium-Drake) |
| 18 |
- Kevin Quick (@kevinquick) |
| 19 |
version_added: "1.2.0" |
| 20 |
attributes: |
| 21 |
check_mode: |
| 22 |
support: full |
| 23 |
diff_mode: |
| 24 |
support: none |
| 25 |
options: |
| 26 |
userid: |
| 27 |
description: |
| 28 |
- The user name. |
| 29 |
- Must include the desired PVE authentication realm. |
| 30 |
type: str |
| 31 |
aliases: ["name"] |
| 32 |
required: true |
| 33 |
state: |
| 34 |
description: |
| 35 |
- Indicate desired state of the user. |
| 36 |
choices: ['present', 'absent'] |
| 37 |
default: present |
| 38 |
type: str |
| 39 |
comment: |
| 40 |
description: |
| 41 |
- Specify the description for the user. |
| 42 |
type: str |
| 43 |
enable: |
| 44 |
description: |
| 45 |
- Whether or not the account is active. |
| 46 |
type: bool |
| 47 |
default: true |
| 48 |
email: |
| 49 |
description: |
| 50 |
- Email address for the user. |
| 51 |
type: str |
| 52 |
expire: |
| 53 |
description: |
| 54 |
- Expiration date of the user in seconds after epoch. |
| 55 |
- 0 means no expiration date. |
| 56 |
type: int |
| 57 |
default: 0 |
| 58 |
firstname: |
| 59 |
description: |
| 60 |
- First name of the user. |
| 61 |
type: str |
| 62 |
lastname: |
| 63 |
description: |
| 64 |
- Last name of the user. |
| 65 |
type: str |
| 66 |
groups: |
| 67 |
description: |
| 68 |
- List of groups the user is a member of. |
| 69 |
type: list |
| 70 |
elements: str |
| 71 |
keys: |
| 72 |
description: |
| 73 |
- Keys for two factor authentication (yubico). |
| 74 |
type: str |
| 75 |
password: |
| 76 |
description: |
| 77 |
- Initial password. |
| 78 |
- Only for PVE Authentication Realm users. |
| 79 |
- Parameter is ignored when user already exists or O(state=absent). |
| 80 |
type: str |
| 81 |
tokens: |
| 82 |
description: List of API tokens associated to the user. |
| 83 |
type: list |
| 84 |
elements: dict |
| 85 |
suboptions: |
| 86 |
comment: |
| 87 |
description: Short description of the token. |
| 88 |
type: str |
| 89 |
expire: |
| 90 |
description: Expiration date in seconds since EPOCH. Zero means no expiration. |
| 91 |
type: int |
| 92 |
default: 0 |
| 93 |
privsep: |
| 94 |
description: Describe if the API token is further restricted with ACLs or is fully privileged. |
| 95 |
type: bool |
| 96 |
default: true |
| 97 |
aliases: ["privilege_separation"] |
| 98 |
tokenid: |
| 99 |
description: |
| 100 |
- Token name. |
| 101 |
- Case sensitive and must be unique per user. |
| 102 |
type: str |
| 103 |
aliases: ["name"] |
| 104 |
required: true |
| 105 |
|
| 106 |
extends_documentation_fragment: |
| 107 |
- community.proxmox.proxmox.actiongroup_proxmox |
| 108 |
- community.proxmox.proxmox.documentation |
| 109 |
- community.proxmox.attributes |
| 110 |
""" |
| 111 |
|
| 112 |
EXAMPLES = r""" |
| 113 |
- name: Create new Proxmox VE user |
| 114 |
community.proxmox.proxmox_user: |
| 115 |
name: user@pve |
| 116 |
comment: Expires on 2026-01-01 00:00:00 |
| 117 |
email: [email protected] |
| 118 |
enable: true |
| 119 |
expire: 1767222000 |
| 120 |
firstname: User |
| 121 |
groups: |
| 122 |
- admins |
| 123 |
password: GoBananas! |
| 124 |
tokens: |
| 125 |
- tokenid: MyToken |
| 126 |
comment: Expires on 2026-01-01 00:00:00 |
| 127 |
expire: 1767222000 |
| 128 |
privsep: false |
| 129 |
lastname: Some Guy |
| 130 |
|
| 131 |
- name: Delete a Proxmox VE user |
| 132 |
community.proxmox.proxmox_user: |
| 133 |
name: user@pve |
| 134 |
state: absent |
| 135 |
""" |
| 136 |
|
| 137 |
RETURN = r""" |
| 138 |
userid: |
| 139 |
description: The user name. |
| 140 |
returned: success |
| 141 |
type: str |
| 142 |
sample: test |
| 143 |
secrets: |
| 144 |
description: Dictionary of API tokens associated with their secret. |
| 145 |
returned: success |
| 146 |
type: dict |
| 147 |
msg: |
| 148 |
description: A short message on what the module did. |
| 149 |
returned: always |
| 150 |
type: str |
| 151 |
sample: "User administrators successfully created" |
| 152 |
""" |
| 153 |
|
| 154 |
from ansible_collections.community.proxmox.plugins.module_utils.proxmox import ( |
| 155 |
ProxmoxAnsible, |
| 156 |
ansible_to_proxmox_bool, |
| 157 |
create_proxmox_module, |
| 158 |
is_not_found_error, |
| 159 |
) |
| 160 |
|
| 161 |
|
| 162 |
def module_args(): |
| 163 |
return dict( |
| 164 |
userid=dict(type="str", aliases=["name"], required=True), |
| 165 |
comment=dict(type="str"), |
| 166 |
email=dict(type="str"), |
| 167 |
enable=dict(default=True, type="bool"), |
| 168 |
expire=dict(default=0, type="int"), |
| 169 |
firstname=dict(type="str"), |
| 170 |
groups=dict(type="list", elements="str"), |
| 171 |
lastname=dict(type="str"), |
| 172 |
keys=dict(type="str", no_log=True), |
| 173 |
password=dict(type="str", no_log=True), |
| 174 |
tokens=dict( |
| 175 |
type="list", |
| 176 |
no_log=False, |
| 177 |
elements="dict", |
| 178 |
options=dict( |
| 179 |
tokenid=dict( |
| 180 |
type="str", aliases=["name"], no_log=False, required=True |
| 181 |
), # no_log is necessary to pass the CI |
| 182 |
comment=dict(type="str"), |
| 183 |
expire=dict(type="int", default=0), |
| 184 |
privsep=dict(type="bool", default=True, aliases=["privilege_separation"]), |
| 185 |
), |
| 186 |
), |
| 187 |
state=dict(default="present", choices=["present", "absent"]), |
| 188 |
) |
| 189 |
|
| 190 |
|
| 191 |
def module_options(): |
| 192 |
return {} |
| 193 |
|
| 194 |
|
| 195 |
class ProxmoxUserAnsible(ProxmoxAnsible): |
| 196 |
def is_user_existing(self, userid): |
| 197 |
"""Check whether user already exist |
| 198 |
|
| 199 |
:param userid: str - name of the user |
| 200 |
:return: dict|bool - user data if exists, False otherwise |
| 201 |
""" |
| 202 |
try: |
| 203 |
user_data = self.proxmox_api.access.users(userid).get() |
| 204 |
return user_data |
| 205 |
except Exception as e: |
| 206 |
if is_not_found_error(e): |
| 207 |
return False |
| 208 |
else: |
| 209 |
self.module.fail_json(msg=f"Unable to retrieve user {userid}: {e}") |
| 210 |
|
| 211 |
def _user_needs_update(self, existing_user, comment, email, enable, expire, firstname, lastname, groups, keys): # noqa: PLR0913 |
| 212 |
"""Check if user needs updating by comparing current vs desired state""" |
| 213 |
# Check standard fields |
| 214 |
fields = [ |
| 215 |
("comment", comment, ""), |
| 216 |
("email", email, ""), |
| 217 |
("enable", enable, 1), |
| 218 |
("expire", expire, 0), |
| 219 |
("firstname", firstname, ""), |
| 220 |
("lastname", lastname, ""), |
| 221 |
("keys", keys, ""), |
| 222 |
] |
| 223 |
|
| 224 |
for field, new_value, default in fields: |
| 225 |
if new_value is not None and existing_user.get(field, default) != new_value: |
| 226 |
return True |
| 227 |
|
| 228 |
# Check groups (API returns list, we send comma-separated string) |
| 229 |
if groups is not None: |
| 230 |
existing_groups_str = ",".join(existing_user.get("groups", [])) |
| 231 |
if existing_groups_str != groups: |
| 232 |
return True |
| 233 |
|
| 234 |
return False |
| 235 |
|
| 236 |
def _tokens_need_update(self, existing_tokens, new_tokens): |
| 237 |
"""Check if tokens need updating by comparing current vs desired state""" |
| 238 |
existing_tokens = existing_tokens or {} |
| 239 |
new_tokens = new_tokens or [] |
| 240 |
|
| 241 |
# If the number of tokens is different, we need an update |
| 242 |
if len(existing_tokens) != len(new_tokens): |
| 243 |
return True |
| 244 |
|
| 245 |
# Check tokens - If any token is different or missing, we consider an update is needed. |
| 246 |
for token in new_tokens: |
| 247 |
existing_token = existing_tokens.get(token["tokenid"]) |
| 248 |
if not existing_token: |
| 249 |
return True |
| 250 |
if ( |
| 251 |
existing_token.get("comment", "") != (token["comment"] or "") |
| 252 |
or existing_token.get("expire", 0) != token["expire"] |
| 253 |
or bool(existing_token.get("privsep")) != token["privsep"] |
| 254 |
): |
| 255 |
return True |
| 256 |
|
| 257 |
return False |
| 258 |
|
| 259 |
def create_update_delete_tokens(self, userid: str, tokens: list) -> set: |
| 260 |
result_tokens = {} |
| 261 |
existing_tokens = {} |
| 262 |
tokens = tokens or [] |
| 263 |
candidate_token_ids = [t["tokenid"] for t in tokens] |
| 264 |
|
| 265 |
try: |
| 266 |
existing_tokens = self.is_user_existing(userid).get("tokens", {}) or {} |
| 267 |
except AttributeError: |
| 268 |
self.module.fail_json( |
| 269 |
changed=False, |
| 270 |
userid=userid, |
| 271 |
msg=f"Failed to manage tokens for unknown user with ID {userid}", |
| 272 |
) |
| 273 |
|
| 274 |
for token in tokens: |
| 275 |
try: |
| 276 |
if token["tokenid"] not in existing_tokens: |
| 277 |
resp = ( |
| 278 |
self.proxmox_api.access.users(userid) |
| 279 |
.token(token["tokenid"]) |
| 280 |
.post( |
| 281 |
tokenid=token["tokenid"], |
| 282 |
comment=token["comment"], |
| 283 |
expire=token["expire"], |
| 284 |
privsep=ansible_to_proxmox_bool(token["privsep"]), |
| 285 |
) |
| 286 |
) |
| 287 |
result_tokens[token["tokenid"]] = resp["value"] |
| 288 |
else: |
| 289 |
self.proxmox_api.access.users(userid).token(token["tokenid"]).put( |
| 290 |
comment=token["comment"], |
| 291 |
expire=token["expire"], |
| 292 |
privsep=ansible_to_proxmox_bool(token["privsep"]), |
| 293 |
) |
| 294 |
except Exception as e: |
| 295 |
self.module.fail_json( |
| 296 |
changed=False, |
| 297 |
userid=userid, |
| 298 |
msg=f"Failed to create or update token '{token['tokenid']}' for user with ID {userid}: {e}", |
| 299 |
) |
| 300 |
|
| 301 |
for existing_token in existing_tokens: |
| 302 |
try: |
| 303 |
if existing_token not in candidate_token_ids: |
| 304 |
self.proxmox_api.access.users(userid).token(existing_token).delete() |
| 305 |
except Exception as e: |
| 306 |
self.module.fail_json( |
| 307 |
changed=False, |
| 308 |
userid=userid, |
| 309 |
msg=f"Failed to delete token '{existing_token}' for user with ID {userid}: {e}", |
| 310 |
) |
| 311 |
return result_tokens |
| 312 |
|
| 313 |
def create_update_user( # noqa: PLR0913 |
| 314 |
self, |
| 315 |
userid, |
| 316 |
comment=None, |
| 317 |
email=None, |
| 318 |
enable=True, |
| 319 |
expire=0, |
| 320 |
firstname=None, |
| 321 |
groups=None, |
| 322 |
password=None, |
| 323 |
tokens=None, |
| 324 |
keys=None, |
| 325 |
lastname=None, |
| 326 |
): |
| 327 |
"""Create or update Proxmox VE user |
| 328 |
|
| 329 |
:param userid: str - name of the user |
| 330 |
:param comment: str, optional - Description of a user |
| 331 |
:param email: str, optional - Email of the user |
| 332 |
:param enable: bool, optional - Whether or not user is active |
| 333 |
:param expire: str, optional - Expiration date of the user |
| 334 |
:param firstname: str, optional - First name of the user |
| 335 |
:param groups: list, optional - Groups that the user should be a member of |
| 336 |
:param password: str, optional - Password of the user, PVE realm only |
| 337 |
:param tokens: list, optional - API tokens associated to the user |
| 338 |
:param keys: str, optional - 2FA keys for the user |
| 339 |
:param lastname: str, optional - Lastname of the user |
| 340 |
:return: None |
| 341 |
""" |
| 342 |
# Translate input to make API happy |
| 343 |
enable = int(enable) |
| 344 |
groups = ",".join(groups) if groups else None |
| 345 |
existing_user = self.is_user_existing(userid) |
| 346 |
if tokens is None: |
| 347 |
tokens = [] |
| 348 |
if existing_user: |
| 349 |
needs_update = self._user_needs_update( |
| 350 |
existing_user, comment, email, enable, expire, firstname, lastname, groups, keys |
| 351 |
) or self._tokens_need_update(existing_user.get("tokens"), tokens) |
| 352 |
if not needs_update and not password: |
| 353 |
self.module.exit_json(changed=False, userid=userid, msg=f"User {userid} already up to date") |
| 354 |
if self.module.check_mode: |
| 355 |
self.module.exit_json( |
| 356 |
changed=needs_update or bool(password), |
| 357 |
userid=userid, |
| 358 |
msg=f"Would update {userid} (check mode)", |
| 359 |
) |
| 360 |
|
| 361 |
if needs_update: |
| 362 |
try: |
| 363 |
# Build update parameters - only include non-None values |
| 364 |
update_params = {"enable": enable} |
| 365 |
for field, value in [ |
| 366 |
("comment", comment), |
| 367 |
("email", email), |
| 368 |
("expire", expire), |
| 369 |
("firstname", firstname), |
| 370 |
("lastname", lastname), |
| 371 |
("groups", groups), |
| 372 |
("keys", keys), |
| 373 |
]: |
| 374 |
if value is not None: |
| 375 |
update_params[field] = value |
| 376 |
self.proxmox_api.access.users(userid).put(**update_params) |
| 377 |
|
| 378 |
result_tokens = self.create_update_delete_tokens(userid, tokens) |
| 379 |
|
| 380 |
self.module.exit_json( |
| 381 |
changed=True, userid=userid, secrets=result_tokens, msg=f"User {userid} updated" |
| 382 |
) |
| 383 |
except Exception as e: |
| 384 |
self.module.fail_json( |
| 385 |
changed=False, userid=userid, msg=f"Failed to update user with ID {userid}: {e}" |
| 386 |
) |
| 387 |
|
| 388 |
# We have no way of testing if the user's password needs to be changed |
| 389 |
# so, if it's provided we will update it anyway |
| 390 |
if password: |
| 391 |
try: |
| 392 |
self.proxmox_api.access.password.put(userid=userid, password=password) |
| 393 |
self.module.exit_json(changed=True, userid=userid, msg=f"User {userid} updated") |
| 394 |
except Exception as e: |
| 395 |
self.module.fail_json( |
| 396 |
changed=False, |
| 397 |
userid=userid, |
| 398 |
msg=f"Failed to update user password for user ID {userid}: {e}", |
| 399 |
) |
| 400 |
|
| 401 |
if self.module.check_mode: |
| 402 |
self.module.exit_json(changed=True, userid=userid, msg=f"Would create user {userid} (check mode)") |
| 403 |
|
| 404 |
# if the user is new, post it to the API |
| 405 |
try: |
| 406 |
self.proxmox_api.access.users.post( |
| 407 |
userid=userid, |
| 408 |
comment=comment, |
| 409 |
email=email, |
| 410 |
enable=enable, |
| 411 |
expire=expire, |
| 412 |
firstname=firstname, |
| 413 |
groups=groups, |
| 414 |
password=password, |
| 415 |
keys=keys, |
| 416 |
lastname=lastname, |
| 417 |
) |
| 418 |
|
| 419 |
result_tokens = self.create_update_delete_tokens(userid, tokens) |
| 420 |
|
| 421 |
self.module.exit_json(changed=True, userid=userid, secrets=result_tokens, msg=f"Created user {userid}") |
| 422 |
except Exception as e: |
| 423 |
self.module.fail_json(msg=f"Failed to create user with ID {userid}: {e}") |
| 424 |
|
| 425 |
def delete_user(self, userid): |
| 426 |
"""Delete Proxmox VE user |
| 427 |
|
| 428 |
:param userid: str - name of the user |
| 429 |
:return: None |
| 430 |
""" |
| 431 |
if not self.is_user_existing(userid): |
| 432 |
self.module.exit_json(changed=False, userid=userid, msg=f"User {userid} doesn't exist") |
| 433 |
|
| 434 |
if self.module.check_mode: |
| 435 |
self.module.exit_json(changed=False, userid=userid, msg=f"Would deleted user with ID {userid} (check mode)") |
| 436 |
|
| 437 |
try: |
| 438 |
self.proxmox_api.access.users(userid).delete() |
| 439 |
self.module.exit_json(changed=True, userid=userid, msg=f"Deleted user with ID {userid}") |
| 440 |
except Exception as e: |
| 441 |
self.module.fail_json(msg=f"Failed to delete user with ID {userid}: {e}") |
| 442 |
|
| 443 |
|
| 444 |
def main(): |
| 445 |
module = create_proxmox_module(module_args(), **module_options()) |
| 446 |
proxmox = ProxmoxUserAnsible(module) |
| 447 |
|
| 448 |
userid = module.params["userid"] |
| 449 |
comment = module.params["comment"] |
| 450 |
email = module.params["email"] |
| 451 |
enable = module.params["enable"] |
| 452 |
expire = module.params["expire"] |
| 453 |
firstname = module.params["firstname"] |
| 454 |
groups = module.params["groups"] |
| 455 |
lastname = module.params["lastname"] |
| 456 |
keys = module.params["keys"] |
| 457 |
password = module.params["password"] |
| 458 |
tokens = module.params["tokens"] |
| 459 |
state = module.params["state"] |
| 460 |
|
| 461 |
# Convert empty strings to None for proper comparison |
| 462 |
for param in ["comment", "email", "firstname", "lastname", "keys"]: |
| 463 |
if locals()[param] == "": |
| 464 |
locals()[param] = None |
| 465 |
|
| 466 |
if state == "present": |
| 467 |
proxmox.create_update_user( |
| 468 |
userid, comment, email, enable, expire, firstname, groups, password, tokens, keys, lastname |
| 469 |
) |
| 470 |
else: |
| 471 |
proxmox.delete_user(userid) |
| 472 |
|
| 473 |
|
| 474 |
if __name__ == "__main__": |
| 475 |
main() |