
    Vhs                         d dl mZmZmZ eZdZdZdZd dl	Z	d dl
mZ d dlmZ d dlmZ d d	lmZ d dlmc mc mc mc mZ  G d
 de      Zd Zedk(  r e        yy)    )absolute_importdivisionprint_functiona  
module: zabbix_user
short_description: Create/update/delete Zabbix users
author:
    - sky-joker (@sky-joker)
description:
    - This module allows you to create, modify and delete Zabbix users.
requirements:
    - "python >= 3.9"
options:
    username:
        description:
            - Username.
            - username is the unique identifier used and cannot be updated using this module.
        required: true
        type: str
    name:
        description:
            - Name of the user.
        type: str
    surname:
        description:
            - Surname of the user.
        type: str
    usrgrps:
        description:
            - User groups to add the user to.
            - Required when I(state=present).
        required: false
        type: list
        elements: str
    passwd:
        description:
            - User's password.
            - Required unless all of the I(usrgrps) are set to use LDAP as frontend access.
        required: false
        type: str
    override_passwd:
        description:
            - Override password for the user.
            - Password will not be updated on subsequent runs without setting this value to yes.
        default: no
        type: bool
    current_passwd:
        description:
            - Current password for the user when overriding its password.
            - Required when overriding the logged in user's password.
            - https://www.zabbix.com/documentation/6.4/en/manual/api/reference/user/update
        required: false
        type: str
    lang:
        description:
            - Language code of the user's language.
        choices:
            - "en_GB"
            - "en_US"
            - "zh_CN"
            - "cs_CZ"
            - "fr_FR"
            - "he_IL"
            - "it_IT"
            - "ko_KR"
            - "ja_JP"
            - "nb_NO"
            - "pl_PL"
            - "pt_BR"
            - "pt_PT"
            - "ru_RU"
            - "sk_SK"
            - "tr_TR"
            - "uk_UA"
            - "default"
        type: str
    theme:
        description:
            - User's theme.
        choices:
            - "default"
            - "blue-theme"
            - "dark-theme"
        type: str
    autologin:
        description:
            - Whether to enable auto-login.
            - If enable autologin, cannot enable autologout.
        type: bool
    autologout:
        description:
            - User session life time in seconds. If set to 0, the session will never expire.
            - If enable autologout, cannot enable autologin.
        type: str
    refresh:
        description:
            - Automatic refresh period in seconds.
        type: str
    rows_per_page:
        description:
            - Amount of object rows to show per page.
        type: str
    after_login_url:
        description:
            - URL of the page to redirect the user to after logging in.
        type: str
    user_medias:
        description:
            - Set the user's media.
            - If not set, makes no changes to media.
        suboptions:
            mediatype:
                description:
                    - Media type name to set.
                default: "Email"
                type: str
            sendto:
                description:
                    - Address, user name or other identifier of the recipient.
                    - If C(mediatype) is Email, values are represented as array. For other types of Media types, value is represented as a string.
                required: true
                type: raw
            period:
                description:
                    - Time when the notifications can be sent as a time period or user macros separated by a semicolon.
                    - Please review the documentation for more information on the supported time period.
                    - https://www.zabbix.com/documentation/current/en/manual/appendix/time_period
                default: "1-7,00:00-24:00"
                type: str
            severity:
                description:
                    - Trigger severities to send notifications about.
                suboptions:
                   not_classified:
                       description:
                           - severity not_classified enable/disable.
                       default: true
                       type: bool
                   information:
                       description:
                           - severity information enable/disable.
                       default: true
                       type: bool
                   warning:
                       description:
                           - severity warning enable/disable.
                       default: true
                       type: bool
                   average:
                       description:
                           - severity average enable/disable.
                       default: true
                       type: bool
                   high:
                       description:
                           - severity high enable/disable.
                       default: true
                       type: bool
                   disaster:
                       description:
                           - severity disaster enable/disable.
                       default: true
                       type: bool
                default:
                  not_classified: true
                  information: true
                  warning: true
                  average: true
                  high: true
                  disaster: true
                type: dict
            active:
                description:
                    - Whether the media is enabled.
                default: true
                type: bool
        type: list
        elements: dict
    timezone:
        description:
            - User's time zone.
            - For the full list of supported time zones please refer to U(https://www.php.net/manual/en/timezones.php)
        type: str
        version_added: 1.2.0
    role_name:
        description:
            - User's role.
            - Default is C(User role) when creating a new user.
            - The default value will be removed at the version 2.0.0.
        type: str
        version_added: 1.2.0
    state:
        description:
            - State of the user.
            - On C(present), it will create if user does not exist or update the user if the associated data is different.
            - On C(absent) will remove a user if it exists.
        default: "present"
        choices: ["present", "absent"]
        type: str
extends_documentation_fragment:
- community.zabbix.zabbix

a  
# If you want to use Username and Password to be authenticated by Zabbix Server
- name: Set credentials to access Zabbix Server API
  ansible.builtin.set_fact:
    ansible_user: Admin
    ansible_httpapi_pass: zabbix

# If you want to use API token to be authenticated by Zabbix Server
# https://www.zabbix.com/documentation/current/en/manual/web_interface/frontend_sections/administration/general#api-tokens
- name: Set API token
  ansible.builtin.set_fact:
    ansible_zabbix_auth_key: 8ec0d52432c15c91fcafe9888500cf9a607f44091ab554dbee860f6b44fac895

- name: create a new zabbix user.
  # set task level variables as we change ansible_connection plugin here
  vars:
    ansible_network_os: community.zabbix.zabbix
    ansible_connection: httpapi
    ansible_httpapi_port: 443
    ansible_httpapi_use_ssl: true
    ansible_httpapi_validate_certs: false
    ansible_zabbix_url_path: "zabbixeu"  # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu
    ansible_host: zabbix-example-fqdn.org
  community.zabbix.zabbix_user:
    username: example
    name: user name
    surname: user surname
    usrgrps:
      - Guests
      - Disabled
    passwd: password
    lang: en_GB
    theme: blue-theme
    autologin: no
    autologout: "0"
    refresh: "30"
    rows_per_page: "200"
    after_login_url: ""
    user_medias:
      - mediatype: Email
        sendto:
          - example@example.com
          - example1@example.com
        period: 1-7,00:00-24:00
        severity:
          not_classified: no
          information: yes
          warning: yes
          average: yes
          high: yes
          disaster: yes
        active: no
    state: present

- name: delete existing zabbix user.
  # set task level variables as we change ansible_connection plugin here
  vars:
    ansible_network_os: community.zabbix.zabbix
    ansible_connection: httpapi
    ansible_httpapi_port: 443
    ansible_httpapi_use_ssl: true
    ansible_httpapi_validate_certs: false
    ansible_zabbix_url_path: "zabbixeu"  # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu
    ansible_host: zabbix-example-fqdn.org
  community.zabbix.zabbix_user:
    username: example
    state: absent
z
user_ids:
    description: User id created or changed
    returned: success
    type: dict
    sample: { "userids": [ "5" ] }
N)AnsibleModule)
ZabbixBase)helper_normalize_data)LooseVersionc                   B    e Zd Zd Zd Zd Zd Zd Zd Zd Z	d Z
d	 Zy
)Userc                     | j                   j                  j                  ddi      }	 |d   dk(  ry|d   dk(  ry| j                  j	                  d|z  	       y # t
        $ r)}| j                  j	                  d
|z  	       Y d }~y d }~ww xY w)Noutputextendauthentication_type0internal1LDAPzCFailed to query authentication type. Unknown authentication type %smsgz6Unhandled error while querying authentication type. %s)_zapiauthenticationget_module	fail_json	Exception)selfauthes      p/home/dcms/DCMS/lib/python3.12/site-packages/ansible_collections/community/zabbix/plugins/modules/zabbix_user.pyget_default_authenticationzUser.get_default_authentication1  s    zz((,,h-AB	)*c1!+,3&&] '   	LL""LPQR #  	s!   A A A 	B$BBc                    g dd|id}| j                   j                  j                  |      }|r|D cg c]	  }d|d   i }}t        |D cg c]  }|d   dk(  s| c}      rd}nht        |D cg c]  }|d   dk(  s	|d   d	k(  s| c}      rd
}n;t        |D cg c]  }|d   dk(  s| c}      r| j	                         }|dk(  rdnd
}t        |      t        |D cg c]  }|d   	 c}      z
  }|r| j                  j                  d|z         |fS | j                  j                  d       y c c}w c c}w c c}w c c}w c c}w )N)usrgrpidname
gui_accessr#   )r   filterr"   r$   r   T23Fr   r   zUser groups not found: %sr   zNo user groups found)r   	usergroupr   boolr    setr   r   )	r   usrgrpsparamsresgidsrequire_passworddefault_authenticationnot_found_groupss	            r   get_usergroups_by_namezUser.get_usergroups_by_nameB  sr   8w'
 jj""&&v.8;<1J*.<C< >1q#'=Q>?#' Tq1\?c#9Q|_PS=ST $) #@Q<C)?q@A *.)H)H)J&2j@De !  #7|cc2J1V92J.KK&&36FF '  (((LL""'=">; = ? U A 3Ks/   D<EE3E	E E.E%E
c                 `    | j                   j                  j                  dd|idddd      }|S )Nr   usernameT)r   r%   	getAccessselectMediasselectUsrgrps)r   userr   )r   r5   zbx_users      r   check_user_existzUser.check_user_existh  s:    ::??&&"%x0! (!)
     c                    t        j                  |      }|D ]Q  }| j                  j                  j	                  ddi      }|D ]  }|d   |d   k(  s|d   |d<   |d   |d<    n d|vr#| j
                  j                  d|d   z         n|d   d	k(  r^t        |d
   t              s.t        |d
   t              s| j
                  j                  d       t        |d
   t              r8|d
   g|d
<   n.t        |d
   t              s| j
                  j                  d       |d= d}dD ]  }|d   |   r|dz   }|d	z   } t        t        |d            |d<   |d   rd	|d<   Md|d<   T |S )Nr   r   r#   	mediatypemediatypeidtypezMedia type not found: %sr   r   sendtozBFor Email media type sendto parameter must be of type list or str.zIFor any other than Email media type sendto parameter must be of type str. )disasterhighaveragewarninginformationnot_classifiedseverityr      active)copydeepcopyr   r>   r   r   r   
isinstanceliststrint)r   user_mediascopy_user_medias
user_mediamedia_types
media_typeseverity_binary_numberseverity_keys           r   #convert_user_medias_parameter_typesz(User.convert_user_medias_parameter_typesu  s   ==5* 1	+J**..22Hh3GHK) 
f%K)@@0:=0IJ}-.8.@J{+	
 J.&&2Z5LL '  k*c1 #:h#7>%j&:C@..` "*X"6<0:80D/E
8,%j&:C@..g {+%'"! J j),7-Cc-I*-Cc-I*J &)-CQ)G%HJz"(#'*
8$'*
8$c1	+f  r<   c                     | j                   j                  j                  ddi      }|D ]  }|d   |k(  s|d   c S  | j                  j	                  d|z         y )Nr   r   r#   roleidzRole not found: %sr   )r   roler   r   r   )r   	role_namerolesr\   s       r   get_roleid_by_namezUser.get_roleid_by_name  sa    

##Xx$89 	&DF|y(H~%	& 	#7)#CDr<   c                    t        j                  |d         }g }|d   D ]  }|j                  d|d   i        t        |d       |d<   |d   |d<   dD ]  }||=  d|v r|d   r|d   D ]  }d	D ]
  }||v s||=   |d   d
   |||t        |d       |||	|
|||d}|r||d<   nd|v r|d   r|d= |r||d<   |r| j	                  |      nd |d<   ||d<   t        |      \  }}t        ||      \  }}d}i }t        j                  |||      sd}t        | j                        t        d      k\  r
|r||d<   |d= ||d}||fS )Nr   r+   r"   c                     | d   S Nr"    xs    r   <lambda>z6User.user_parameter_difference_check.<locals>.<lambda>  s
    1Z= r<   )keymediasrR   )rh   attempt_clockattempt_failed
attempt_ip
debug_modeusers_statusr$   )mediaiduseridro   c                     | d   S rb   rc   rd   s    r   rf   z6User.user_parameter_difference_check.<locals>.<lambda>  s
    AjM r<   ro   r5   r#   surnamer+   langtheme	autologin
autologoutrefreshrows_per_pageurlpasswdr[   timezoneTF6.4beforeafter)
rL   rM   appendsortedr_   r   zabbix_utilshelper_compare_dictionariesr	   _zbx_api_version)r   r:   r5   r#   rr   user_group_idsrz   rs   rt   ru   rv   rw   rx   ry   rR   r{   r]   override_passwdexisting_data	usrgrpidsusrgrpdel_keyrT   request_datadel_keys	_del_keys&user_parameter_difference_check_result	diff_dictdiff_paramss                                r   user_parameter_difference_checkz$User.user_parameter_difference_check  s   , hqk2	#I. 	?Fj&*<=>	?#))9P#Qi '4X'>m$
 		'G g&		' M)mM.J+M: 0
4 0G*,&w/00 qk(+ n2IJ"$*
 *5L'--2N!-0%+L" 3<D##I. 	X $,Z !6|!Dh#8#Q y15.	77-
 6;2--.,u2EE)4X& /!.F5{BBr<   c                    |d}i }||||||||	|
||d}|r,t        | j                        t        d      k  r||d<   n||d<   |r||d<   | j                  |      |d<   ||d<   t        |      \  }}i }| j                  j
                  s*	 | j                  j                  j                  |      }||fS d|d}||fS # t        $ r/}| j                  j                  d	|d
|       Y d }~||fS d }~ww xY w)Nz	User role)r5   r#   rr   r+   rs   rt   ru   rv   rw   rx   ry   z6.2rR   rh   rz   r[   r{   zFailed to create user : r   rB   r}   )r	   r   r_   r   r   
check_moder   r9   creater   r   )r   r5   r#   rr   r   rz   rs   rt   ru   rv   rw   rx   ry   rR   r0   r{   r]   user_idsr   r   r   r   s                         r   add_userzUser.add_user  sB   ( #I !%"$*
 D112l56II.9]+)4X&%+L" "&!8!8!CX#+Z "7"Ei||&&::??11,? $$ &(,?K$$  &&:BAF '   $$s   
%B< <	C4"C//C4c                    i }|d   d   |||||||	|
|||d}|r||d<   |r||d<   |r| j                  |      nd |d<   ||d<   t        |      \  }}t        | j                        t        d      k  r-	 |r||d	<   | j                  j
                  j                  |      }t        | j                        t        d      k\  r/	 |r||d<   | j                  j
                  j                  |      }|S |S # t        $ r,}| j                  j                  d
|d|       Y d }~d }~ww xY w# t        $ r-}| j                  j                  d
|d|       Y d }~|S d }~ww xY w)Nr   ro   rq   rz   current_passwdr[   r{   r|   rR   zFailed to update user r   r   rh   )
r_   r   r	   r   r   r9   updater   r   r   )r   r:   r5   r#   rr   r   rz   rs   rt   ru   rv   rw   rx   ry   rR   r{   r]   r   r   r   r   r   r   s                          r   update_userzUser.update_userT  s   ,  qk(+ %"$*
 %+L"1?-. 3<D##I. 	X $,Z "7"Ei--.e1DD2=L/::??11,? --.,u2EE-8L*::??11,? x  &&:BAF '    &&:BAF '   s0   3,C1 ,D) 1	D&:"D!!D&)	E2"EEc                 &   i }i }| j                   j                  s1	 | j                  j                  j	                  |d   d   g      }||fS |d   dd}||fS # t
        $ r/}| j                   j                  d|d|       Y d }~||fS d }~ww xY w)Nr   ro   zFailed to delete user r   r   rB   r}   )r   r   r   r9   deleter   r   )r   r:   r5   r   r   r   s         r   delete_userzUser.delete_user  s    ||&&::??118A;x3H2IJ $$ &.a[2>K$$  &&:BAF '   $$s   ,A 	B!"BBN)__name__
__module____qualname__r    r3   r;   rY   r_   r   r   r   r   rc   r<   r   r   r   0  s9    "$?L5 nE\C|@%DGR%r<   r   c                     t        j                         } | j                  t        d4i dt        dd      dt        d      dt        d      dt        d	d
      dt        ddd      dt        dddd      dt        ddd      dt        dg d      dt        dg d      dt        d      dt        d      dt        d      dt        d      dt        d      dt        d	dt        t        dd      t        d d      t        dd!      t        dt        t        dd      t        dd      t        dd      t        dd      t        dd      t        dd      "      t        dddddd"      #      t        dd      $      %      d&t        d      d't        d      d(t        dd)d)d*g+             t	        | d(d)dgggd,      }|j
                  d   }|j
                  d   }|j
                  d   }|j
                  d   }|j
                  d   }|j
                  d   }|j
                  d   }|j
                  d   }	|j
                  d   }
|j
                  d   }|j
                  d   }|j
                  d   }|j
                  d   }|j
                  d   }|j
                  d   }|j
                  d&   }|j
                  d'   }|j
                  d(   }||rd-}nd.}t        |      }|r|j                  |      }i }|j                  |      }|d)k(  r|j                  |      \  }}|r||j                  d/0       |rU|j                  |||||||	|
|||||||||      \  }}|j                  sJ|rH|j                  |||||||	|
||||||||||      }n%d}|j                  ||||||	|
|||||||||      \  }}|d*k(  r|rd}|j                  ||      \  }}nd}i }|j                  s)|r|j!                  d|1       y |j!                  d2       y r|j!                  d3       y |j!                  d3       y )5Nr5   rP   T)r@   requiredr#   )r@   rr   r+   rO   )r@   elementsrz   F)r@   r   no_logr   r)   )r@   r   defaultr   r   rs   )en_GBen_USzh_CNcs_CZfr_FRhe_ILit_ITko_KRja_JPnb_NOpl_PLpt_BRpt_PTru_RUsk_SKtr_TRuk_UAr   )r@   choicesrt   )r   z
blue-themez
dark-themeru   rv   rw   rx   after_login_urlrR   dictEmail)r@   r   rawz1-7,00:00-24:00)rH   rG   rF   rE   rD   rC   )r@   optionsr   )r>   rA   periodrI   rK   )r@   r   r   r{   r]   statepresentabsent)r@   r   r   )argument_specrequired_ifsupports_check_moder   r   zAUser password is required. One or more groups are not LDAP based.r   )changedr   )r   )r   diffrc   )r   zabbix_common_argument_specr   r   r   r,   r   rY   r;   r3   r   r   r   r   r   r   	exit_json)r   moduler5   r#   rr   r+   rz   r   r   rs   rt   ru   rv   rw   rx   r   rR   r{   r]   r   r9   r   r:   r   r0   diff_check_resultr   s                              r   mainr     sC    <<>M G	
ut4G	
5!G	
 e$G	
 fu5	G	

 UU4@G	
 !eU5G	
  UU4HG	
 G	
B E+RSCG	
D 'EG	
F 'GG	
H e$IG	
J E*KG	
L !e,MG	
N "w?UT:U4EF!# $+/VT+J(,&$(G$(fd$C$(fd$C!%64!@%)vt%D! !%+/(,$($(!%%)!&  VT:/OG	
H u%IG	
J &KG	
L E9y(>STMG	
IT #y9+67 F }}Z(H== DmmI&GmmI&G]]8$Fmm$56O]]#34N== DMM'"Ek*I|,JmmI&GMM/2Mmm$56O--.K}}Z(Hk*IMM'"EII<D>>{KH$$X.H	+/+F+Fw+O((~  [ !  -1-Q-Q#.*{( $$):++"!##"%* !%$(MM !%!Hk&  $$($4$4Xx$H!Hk %KTH=U+T<U=r<   __main__)
__future__r   r   r   r@   __metaclass__DOCUMENTATIONEXAMPLESRETURNrL   ansible.module_utils.basicr   >ansible_collections.community.zabbix.plugins.module_utils.baser   Aansible_collections.community.zabbix.plugins.module_utils.helpersr   #ansible.module_utils.compat.versionr	   	communityzabbixpluginsmodule_utilshelpersr   r   r   r   rc   r<   r   <module>r      st    A @GRCJ
  4 U = X X X{%: {%|J>Z zF r<   