feat(role): add plugin for listing available roles and their privileges
This commit is contained in:
63
plugins/module_utils/proxmox_datacenter_role.py
Normal file
63
plugins/module_utils/proxmox_datacenter_role.py
Normal file
@ -0,0 +1,63 @@
|
||||
from dataclasses import dataclass, field
|
||||
from typing import List, Tuple
|
||||
|
||||
from ansible_collections.finallycoffee.proxmox.plugins.module_utils.common import _proxmox_request, ProxmoxAuthInfo
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ProxmoxRole:
|
||||
name: str
|
||||
privileges: List = field(default_factory=lambda: [])
|
||||
built_in: bool = False
|
||||
|
||||
|
||||
def get_roles(auth_info: ProxmoxAuthInfo) -> List['ProxmoxRoles']:
|
||||
role_answer = _proxmox_request('get', '/access/roles', auth_info).json()
|
||||
return list(map(
|
||||
lambda r: ProxmoxRole(r['roleid'], r['privs'].split(','), bool(r.get('special', False)) is True),
|
||||
role_answer['data']
|
||||
))
|
||||
|
||||
|
||||
def set_role_data(auth_info: ProxmoxAuthInfo, role: str, privileges: list[str], dry_run: bool, state: str = 'present') -> Tuple[dict, dict]:
|
||||
existing_role = _proxmox_request('get', f"/access/roles/{role}", auth_info)
|
||||
existing_role_data = existing_role.json()['data']
|
||||
new_role_data = ''
|
||||
if state == 'present' or state == 'exact':
|
||||
if existing_role.ok:
|
||||
# When state is present, we only append all listed privs to existing roles,
|
||||
# otherwise we set the role's permission list directly
|
||||
changeset = {
|
||||
'privs': ','.join(privileges),
|
||||
'append': False if (state == 'exact') else True
|
||||
}
|
||||
if not dry_run:
|
||||
role_res = _proxmox_request('put', f"/access/roles/{role}", auth_info, data=changeset)
|
||||
role_res.raise_for_status()
|
||||
else:
|
||||
# For new roles, state being exact or present is the same thing
|
||||
if not dry_run:
|
||||
role_res = _proxmox_request('post', '/access/roles', auth_info, data=({
|
||||
'roleId': role,
|
||||
'privs': ','.join(privileges)
|
||||
}))
|
||||
role_res.raise_for_status()
|
||||
if not dry_run:
|
||||
if role_res.ok:
|
||||
new_role_data = _proxmox_request('get', f"/access/roles/{role}", auth_info).json()['data']
|
||||
else:
|
||||
new_role_data = {'role': role, 'privs': privileges}
|
||||
else:
|
||||
if existing_role.ok:
|
||||
existing_role_data = existing_role.json()['data']
|
||||
if not dry_run:
|
||||
role_res = _proxmox_request('delete', f"/access/role/{role}", auth_info)
|
||||
role_res.raise_for_status()
|
||||
if role_res.ok:
|
||||
new_role_data = None
|
||||
else:
|
||||
new_role_data = None
|
||||
else:
|
||||
new_role_data = None
|
||||
return existing_role_data, new_role_data
|
||||
|
Reference in New Issue
Block a user