
    VhVZ                     z    d dl mZmZmZ eZdZdZdZd dl	m
Z
 d dlmZmZ  G d de      Zd	 Zed
k(  r e        yy)    )absolute_importdivisionprint_functiona  
module: manageiq_group

short_description: Management of groups in ManageIQ
extends_documentation_fragment:
  - community.general.manageiq
  - community.general.attributes

author: Evert Mulder (@evertmulder)
description:
  - The manageiq_group module supports adding, updating and deleting groups in ManageIQ.
requirements:
  - manageiq-client

attributes:
  check_mode:
    support: none
  diff_mode:
    support: none

options:
  state:
    type: str
    description:
      - V(absent) - group should not exist,
      - V(present) - group should exist.
    choices: ['absent', 'present']
    default: 'present'
  description:
    type: str
    description:
      - The group description.
    required: true
  role_id:
    type: int
    description:
      - The the group role ID.
    required: false
  role:
    type: str
    description:
      - The the group role name.
      - The O(role_id) has precedence over the O(role) when supplied.
    required: false
    default:
  tenant_id:
    type: int
    description:
      - The tenant for the group identified by the tenant ID.
    required: false
    default:
  tenant:
    type: str
    description:
      - The tenant for the group identified by the tenant name.
      - The O(tenant_id) has precedence over the O(tenant) when supplied.
      - Tenant names are case sensitive.
    required: false
    default:
  managed_filters:
    description: The tag values per category.
    type: dict
    required: false
    default:
  managed_filters_merge_mode:
    type: str
    description:
      - In merge mode existing categories are kept or updated, new categories are added.
      - In replace mode all categories will be replaced with the supplied O(managed_filters).
    choices: [merge, replace]
    default: replace
  belongsto_filters:
    description: A list of strings with a reference to the allowed host, cluster or folder.
    type: list
    elements: str
    required: false
    default:
  belongsto_filters_merge_mode:
    type: str
    description:
      - In merge mode existing settings are merged with the supplied O(belongsto_filters).
      - In replace mode current values are replaced with the supplied O(belongsto_filters).
    choices: [merge, replace]
    default: replace
a;  
- name: Create a group in ManageIQ with the role EvmRole-user and tenant 'my_tenant'
  community.general.manageiq_group:
    description: 'MyGroup-user'
    role: 'EvmRole-user'
    tenant: 'my_tenant'
    manageiq_connection:
      url: 'http://127.0.0.1:3000'
      username: 'admin'
      password: 'smartvm'
      validate_certs: false # only do this when you trust the network!

- name: Create a group in ManageIQ with the role EvmRole-user and tenant with tenant_id 4
  community.general.manageiq_group:
    description: 'MyGroup-user'
    role: 'EvmRole-user'
    tenant_id: 4
    manageiq_connection:
      url: 'http://127.0.0.1:3000'
      username: 'admin'
      password: 'smartvm'
      validate_certs: false # only do this when you trust the network!

- name:
    - Create or update a group in ManageIQ with the role EvmRole-user and tenant my_tenant.
    - Apply 3 prov_max_cpu and 2 department tags to the group.
    - Limit access to a cluster for the group.
  community.general.manageiq_group:
    description: 'MyGroup-user'
    role: 'EvmRole-user'
    tenant: my_tenant
    managed_filters:
      prov_max_cpu:
        - '1'
        - '2'
        - '4'
      department:
        - defense
        - engineering
    managed_filters_merge_mode: replace
    belongsto_filters:
      - "/belongsto/ExtManagementSystem|ProviderName/EmsFolder|Datacenters/EmsFolder|dc_name/EmsFolder|host/EmsCluster|Cluster name"
    belongsto_filters_merge_mode: merge
    manageiq_connection:
      url: 'http://127.0.0.1:3000'
      username: 'admin'
      password: 'smartvm'
      validate_certs: false # only do this when you trust the network!

- name: Delete a group in ManageIQ
  community.general.manageiq_group:
    state: 'absent'
    description: 'MyGroup-user'
    manageiq_connection:
      url: 'http://127.0.0.1:3000'
      username: 'admin'
      password: 'smartvm'

- name: Delete a group in ManageIQ using a token
  community.general.manageiq_group:
    state: 'absent'
    description: 'MyGroup-user'
    manageiq_connection:
      url: 'http://127.0.0.1:3000'
      token: 'sometoken'
aG  
group:
  description: The group.
  returned: success
  type: complex
  contains:
    description:
      description: The group description.
      returned: success
      type: str
    id:
      description: The group ID.
      returned: success
      type: int
    group_type:
      description: The group type, system or user.
      returned: success
      type: str
    role:
      description: The group role name.
      returned: success
      type: str
    tenant:
      description: The group tenant name.
      returned: success
      type: str
    managed_filters:
      description: The tag values per category.
      returned: success
      type: dict
    belongsto_filters:
      description: A list of strings with a reference to the allowed host, cluster or folder.
      returned: success
      type: list
    created_on:
      description: Group creation date.
      returned: success
      type: str
      sample: "2018-08-12T08:37:55+00:00"
    updated_on:
      description: Group update date.
      returned: success
      type: int
      sample: "2018-08-12T08:37:55+00:00"
)AnsibleModule)ManageIQmanageiq_argument_specc                       e Zd ZdZd Zd Zd Zd Zed        Z	d Z
d Zd	 Zd
 Zed        Zed        Zed        Zed        Zy)ManageIQgroupzH
        Object to execute group management operations in manageiq.
    c                     || _         | j                   j                  | _        | j                   j                  | _        | j                   j                  | _        y N)manageiqmoduleapi_urlclient)selfr   s     t/home/dcms/DCMS/lib/python3.12/site-packages/ansible_collections/community/general/plugins/modules/manageiq_group.py__init__zManageIQgroup.__init__   s<     mm**}},,mm**    c                     | j                   j                  j                  j                  |      }t	        |      dk(  ry|d   S )zy Search for group object by description.
        Returns:
            the group, or None if group was not found.
        descriptionr   N)r   collectionsgroupsfind_bylen)r   r   r   s      r   groupzManageIQgroup.group   s@    
 ((//77K7Pv;!!9r   c                    |rH| j                   j                  d|      }|s(| j                  j                  dt	        |      z         |S |r| j                   j
                  j                  j                  |      }|s| j                  j                  d|z         t        |      dkD  r| j                  j                  d|z         |d   }|S y	)
z Search for tenant entity by name or id
        Returns:
            the tenant entity, None if no id or name was supplied
        tenantsz)Tenant with id '%s' not found in manageiqmsgnamez!Tenant '%s' not found in manageiq   z0Multiple tenants found in manageiq with name '%sr   N)	r   
get_entityr   	fail_jsonstrr   r   r   r   )r   	tenant_idtenant_nametenant
tenant_ress        r   r)   zManageIQgroup.tenant   s     [[++IyAF%%*UX[\eXf*f%gM![[44<<DD+DV
!KK)).QT_._)`z?Q&KK)).`cn.n)o#A r   c                    |rH| j                   j                  d|      }|s(| j                  j                  dt	        |      z         |S |r| j                   j
                  j                  j                  |      }|s| j                  j                  d|z         t        |      dkD  r| j                  j                  d|z         |d   S y	)
z Search for a role object by name or id.
        Returns:
            the role entity, None no id or name was supplied

            the role, or send a module Fail signal if role not found.
        rolesz'Role with id '%s' not found in manageiqr   r!   zRole '%s' not found in manageiqr#   z.Multiple roles found in manageiq with name '%sr   N)	r   r$   r   r%   r&   r   r,   r   r   )r   role_id	role_namerolerole_ress        r   r/   zManageIQgroup.role  s     ;;))'7;D%%*SVYZaVb*b%cK;;2288@@i@PKK)).OR[.[)\x=1$KK)).^aj.j)k{" r   c                 `    | r|s| S | s|r|S | j                         }|j                  |       |S )a   Create an merged update object for manageiq group filters.

            The input dict contain the tag values per category.
            If the new values contain the category, all tags for that category are replaced
            If the new values do not contain the category, the existing tags are kept

        Returns:
            the nested array with the merged values, used in the update post body
        )copyupdate)norm_current_valuesnorm_updated_valuesress      r   merge_dict_valueszManageIQgroup.merge_dict_values  s@     (;&& $)<&& "&&(

&'
r   c           	      l   	 | j                   d|d   }| j                  j                  |d      }d
   du r| j                  j                  |d          t        dd|d   d|d         S # t        $ r8}| j                  j                  d|d   dt        |             Y d	}~{d	}~ww xY w)z Deletes a group from manageiq.

        Returns:
            a dict of:
            changed: boolean indicating if the entity was updated.
            msg: a short message describing the operation executed.
        z/groups/iddelete)actionzfailed to delete group r   : r   NsuccessFmessageTzdeleted group 	 with id changedr    )r   r   post	Exceptionr   r%   r&   dict)r   r   urlresultes        r   delete_groupzManageIQgroup.delete_group8  s    	h$(LL%+>C[[%%c(%;F )%KK!!fY&7!816}1EuT{SU 	U  	hKK!!}I]_bcd_e&f!gg	hs   1A2 2	B3;.B..B3c	           	         |s|s|r|j                  ddg       	 |d   }	d}
i }|r|d   |k7  r||d<   d}
|r|d   |d	   k7  rt        |d	   
      |d<   d}
|r|	|d   k7  rt        |d	   
      |d<   d}
|s|rH|d   }d|vr| j                  |      }||d|d<   d}
n#|d   }| j	                  |||||      }|r||d<   d}
|
st        dd|d   z        S 	 | j
                  j                  |d   d|       d}
t        |
d|d   d|d	         S # t        $ r d}	Y w xY w# t        $ r8}| j                  j                  d|d   dt        |             Y d}~fd}~ww xY w)z Edit a manageiq group.

        Returns:
            a dict of:
            changed: boolean indicating if the entity was updated.
            msg: a short message describing the operation executed.
        miq_user_role_nameentitlement)
attributesNFr   Tr'   r9   r9   r)   r"   r/   filtersmanaged	belongstozgroup %s is not changed.r@   hrefeditr;   resourcezfailed to update group r<   r   zsuccessfully updated the group r?   )reloadAttributeErrorrD   %normalized_managed_tag_filters_to_miqedit_group_edit_filtersr   rB   rC   r   r%   r&   )r   r   r   r/   r)   norm_managed_filtersmanaged_filters_merge_modebelongsto_filtersbelongsto_filters_merge_modecurrent_rolerA   rU   rK   managed_tag_filters_post_bodycurrent_filtersnew_filtersrG   s                    r   
edit_groupzManageIQgroup.edit_groupM  s    '+<LL%9=$ILJ	  !56L 5/;>&1H]#GeK(F4L8!%!6HXGLDL0#tDz2HVG#4  .K+040Z0Z[o0p-2O^o&p#"-i"8"::?;OQk;LNjl *5HY'"G.}1EEG G
	aKKU6]6HMG BGBVX]^bXcdf 	fc  	 L	 \  	aKK!!vX[\]X^&_!``	as)   D #D$ D! D!$	E%-.E  E%c                    d}i }|j                  dt                     }|rt        |      }	n
t               }	||	k(  r	|d   |d<   n5|dk(  r |j                  |	       t        |      |d<   nt        |	      |d<   d}| j	                  |      }
|
|k(  rd|v rK|d   |d<   nB|dk(  r'| j                  |
|      }| j                  |      |d<   n| j                  |      |d<   d}|sy|S )z Edit a manageiq group filters.

        Returns:
            None if no the group was not updated
            If the group was updated the post body part for updating the group
        FrQ   mergeTrP   N)getsetr3   listmanageiq_filters_to_sorted_dictr7   rX   )r   r`   rZ   r[   r\   r]   filters_updatednew_filters_resourcecurrent_belongsto_setnew_belongsto_setnorm_current_filtersmerged_dicts               r   rY   z%ManageIQgroup.edit_group_edit_filters  s!     ! / 3 3K G #$5 6 # $550?0L -+w6%,,->?489N4O$[1489J4K$[1"O  $CCOT#77O+2A)2L$Y/)W4"445IK_`262\2\]h2i$Y/262\2\]q2r$Y/"O##r   c           	      2   t        |      j                         D ])  \  }}|dv s| j                  j                  d|z         + d| j                  z  }d|i}	|t        |d   	      |	d
<   |t        |d   	      |	d<   |s|r| j                  |      }
|
|d|	d<   	 | j                  j                  |d|	      }t        dd|z  d   d   d         S # t        $ r5}| j                  j                  d|dt        |             Y d}~Sd}~ww xY w)z Creates the group in manageiq.

        Returns:
            the created group id, name, created_on timestamp,
            updated_on timestamp.
        r   )N zmissing required argument: %sr   z	%s/groupsr   Nr9   rM   r/   r)   rO   rN   createrT   zfailed to create group r<   Tzsuccessfully created group %sresultsr   )rA   r    group_id)
rD   itemsr   r%   r   rX   r   rB   rC   r&   )r   r   r/   r)   rZ   r\   keyvaluerE   rU   r_   rF   rG   s                r   create_groupzManageIQgroup.create_group  sC    ;7==? 	QJC
"%%*IC*O%P	Q DLL(!;/#tDz2HV!%!6HX#4,0,V,VWk,l).KZk"lHY	_[[%%c(X%NF /+=I&q)$/
 	
  	_KK!!VYZ[V\&]!^^	_s    C 	D!+DDc                 :    | sy t        | j                               S r   )rg   values)rZ   s    r   rX   z3ManageIQgroup.normalized_managed_tag_filters_to_miq  s    #(//122r   c                     | j                  d      }|sy i }|D ].  }|j                          |d   j                  d      d   }|||<   0 |S )NrP   r   /   )re   sortsplit)r`   current_managed_filtersr6   tag_listru   s        r   rh   z-ManageIQgroup.manageiq_filters_to_sorted_dict  s_    "1"5"5i"@&/ 	 HMMO1+##C(+CCH	 
 
r   c                    | sy i }| D ]v  }g }t        | |   t              s!|j                  dj                  |             | |   D ]  }d|z   dz   |z   }|j	                  |         |sb|j                          |||<   x |S )Nz.Entry "{0}" of managed_filters must be a list!r   z	/managed/r{   )
isinstancerg   r%   formatappendr}   )managed_filtersr   r6   cat_key	cat_arraytagsmiq_managed_tags          r   -normalize_user_managed_filters_to_sorted_dictz;ManageIQgroup.normalize_user_managed_filters_to_sorted_dict  s    & 
	)GIog6=  %U%\%\]d%e f'0 2"-"7#"="D  12  (G
	) 
r   c                    	 | d   }d}d}d| d   v r}| d   d   }|j                  d      }|j                  d      }|rQi }|D ]J  }|d   j                  d      d	   }g }|D ]%  }	|j                  |	j                  d      d
          ' |||<   L t	        | d   | d   || d   d   ||| d   | d   | d   	      S # t         $ r d}Y w xY w)z Creates the ansible result object from a manageiq group entity

        Returns:
            a dict with the group id, description, role, tenant, filters, group_type, created_on, updated_on
        rJ   NrN   rK   rQ   rP   r   r{   r|      r9   r   r)   r"   
group_type
created_on
updated_on)	r9   r   r/   r)   r   r\   r   r   r   )rW   re   r~   r   rD   )
r   r.   r   r\   rN   group_managed_filtersr   ru   r   ts
             r   create_result_groupz!ManageIQgroup.create_result_group  s    	23I  m,,M*95G 'K 8$+KK	$:!$"$ 5 0H"1+++C03CD% 5AGGCLO45+/OC(0 T{m,?6*+/\*\*\*

 
	
%  	I	s   B8 8CCN)__name__
__module____qualname____doc__r   r   r)   r/   staticmethodr7   rH   rb   rY   rw   rX   rh   r   r    r   r   r
   r
      s    +	00  4U*BfH1$f#
J 3 3    $ $
 $
r   r
   c                     t        t        dd      t        ddgd      t        dd      t        dd      t        dd      t        dd      t        dd	      t        dd
dgd      t        ddd      t        dd
dgd      
      } | j                  t                      t        |       }|j                  d   }|j                  d   }|j                  d   }|j                  d   }|j                  d   }|j                  d   }|j                  d   }|j                  d   }	|j                  d   }
|j                  d   }t        |      }t        |      }|j                  |      }|dk(  r$|r|j                  |      }nt        dd|z        }|dk(  r|j                  ||      }|j                  ||      }|j                  ||      }|r|j                  ||||||	|
|      }n4|j                  |||||
      }|j                  j                  d|d         }|j!                  dg d !       |j#                  |      |d"<    |j$                  d#i  y )$NTr&   )requiredtypeabsentpresent)choicesdefaultFintrD   rd   replace)r   r   r   rg   )r   r   elements)
r   stater-   r/   r'   r)   r   r[   r\   r]   )argument_specr   r   r-   r/   r'   r)   r   r[   r\   r]   z%group '%s' does not exist in manageiqr@   r   rs   	resources)rJ   r)   rK   )expandrL   r   r   )rD   r3   r   r   paramsr   r
   r   rH   r)   r/   r   rb   rw   r   r$   rV   r   	exit_json)r   r   r   r   r-   r.   r'   r(   r   r[   r\   r]   r   manageiq_groupr   res_argsr)   r/   rZ   s                      r   mainr   9  sq   $U3Hi0)De%05u-E2U/e&9#')@T^g#hFUK%)57IBV`i%jM /12#F --.KMM'"EmmI&Gf%Ik*I--)Kmm$56O!'/K!L&9:#)==1O#P H"8,N  -E %2259H ;kIKH
 	&&y+>""7I6-[[\kmst%00T61EGa1BD`bH &22;fNbduvHOO..x*9MNEK4cd*>>uEF x r   __main__N)
__future__r   r   r   r   __metaclass__DOCUMENTATIONEXAMPLESRETURNansible.module_utils.basicr   Cansible_collections.community.general.plugins.module_utils.manageiqr   r   objectr
   r   r   r   r   r   <module>r      s_    C BTlAF,
\ 5 p`
F `
FC!L zF r   