
    Vhj                         d dl mZmZmZ eZddgdd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Z d dlmZ d d	lZd Zd Zd Zd Zd Zd Zd Zd Z e!dk(  r e         y	y	)    )absolute_importdivisionprint_functionz1.1preview	certified)metadata_versionstatussupported_bya  
---
module: cyberark_user
short_description: CyberArk User Management using PAS Web Services SDK.
author:
  - Edward Nunez (@enunez-cyberark)
  - Cyberark Bizdev (@cyberark-bizdev)
  - Erasmo Acosta (@erasmix)
  - James Stutes (@jimmyjamcabd)
version_added: '1.0.0'
description:
    - CyberArk User Management using PAS Web Services SDK,
      It currently supports the following actions Get User Details, Add User,
      Update User, Delete User.

options:
    username:
        description:
            - The name of the user who will be queried (for details), added,
              updated or deleted.
        type: str
        required: true
    state:
        description:
            - Specifies the state needed for the user present for create user,
              absent for delete user.
        type: str
        choices: [ absent, present ]
        default: present
    logging_level:
        description:
            - Parameter used to define the level of troubleshooting output to
              the C(logging_file) value.
        required: false
        choices: [NOTSET, DEBUG, INFO]
        default: NOTSET
        type: str
    logging_file:
        description:
            - Setting the log file name and location for troubleshooting logs.
        required: false
        default: /tmp/ansible_cyberark.log
        type: str
    cyberark_session:
        description:
            - Dictionary set by a CyberArk authentication containing the
              different values to perform actions on a logged-on CyberArk
              session, please see M(cyberark.pas.cyberark_authentication) module for an
              example of cyberark_session.
        type: dict
        required: true
    initial_password:
        description:
            - The password that the new user will use to log on the first time.
            - This password must meet the password policy requirements.
            - This parameter is required when state is present -- Add User.
        type: str
    new_password:
        description:
            - The user updated password. Make sure that this password meets
              the password policy requirements.
        type: str
    email:
        description:
            - The user email address.
        type: str
    first_name:
        description:
            - The user first name.
        type: str
    last_name:
        description:
            - The user last name.
        type: str
    change_password_on_the_next_logon:
        description:
            - Whether or not the user must change their password in their
              next logon.
        type: bool
        default: false
    domain_name:
        description:
            - The name of the user domain.
        type: str
    member_type:
        description:
            - The type of member.
        type: str
    expiry_date:
        description:
            - The date and time when the user account will expire and become
              disabled.
        type: str
    user_type_name:
        description:
            - The type of user.
            - The parameter defaults to C(EPVUser).
        type: str
    disabled:
        description:
            - Whether or not the user will be disabled.
        type: bool
        default: false
    location:
        description:
            - The Vault Location for the user.
        type: str
    group_name:
        description:
            - The name of the group the user will be added to.
            - Causes an additional lookup in cyberark
            - Will be ignored if vault_id is used
            - Will cause a failure if group is missing or more than one group with that name exists
        type: str
    timeout:
        description:
            - How long to wait for the server to send data before giving up
        type: float
        default: 10
    vault_id:
        description:
            - The ID of the user group to add the user to
            - Prefered over group_name
        type: int
    authorization:
        description:
            - A list of authorization options for this user.
            - Options can include AddSafes and AuditUsers
            - The default provides backwards compatability with older versions of the collection
        type: list
        elements: str
        default:
          - AddSafes
          - AuditUsers
a9  
- name: Logon to CyberArk Vault using PAS Web Services SDK
  cyberark_authentication:
    api_base_url: https://components.cyberark.local
    use_shared_logon_authentication: true

- name: Create user & immediately add it to a group
  cyberark_user:
    username: username
    initial_password: password
    user_type_name: EPVUser
    change_password_on_the_next_logon: false
    group_name: GroupOfUser
    state: present
    cyberark_session: '{{ cyberark_session }}'

- name: Make sure user is present and reset user credential if present
  cyberark_user:
    username: Username
    new_password: password
    disabled: false
    state: present
    cyberark_session: '{{ cyberark_session }}'

- name: Logoff from CyberArk Vault
  cyberark_authentication:
    state: absent
    cyberark_session: '{{ cyberark_session }}'
a  
changed:
    description: Whether there was a change done.
    type: bool
    returned: always
cyberark_user:
    description: Dictionary containing result properties.
    returned: always
    type: complex
    contains:
        result:
            description: user properties when state is present
            type: dict
            returned: success
status_code:
    description: Result HTTP Status code
    returned: success
    type: int
    sample: 200
N)AnsibleModule)to_text)http_client)	HTTPError)open_url)quotec                 d    dj                  | j                  d      |j                  d            S )Nz{baseurl}/{endpoint}/)baseurlendpoint)formatrstriplstrip)api_base_url	end_points     n/home/dcms/DCMS/lib/python3.12/site-packages/ansible_collections/cyberark/pas/plugins/modules/cyberark_user.pyconstruct_urlr      s0    !((1D1DS1IT]TdTdehTi(jj    c           	         | j                   d   }| j                   d   }|d   }|d   }i }dj                  |      }t        ||      }d|d   d	d
}	 t        |d||| j                   d         }	dt	        j
                  |	j                               i}d||	j                         fS # t        t        j                  f$ rZ}
|
j                  dk(  rdd |
j                  fcY d }
~
S | j                  d|dt        |
      ||
j                         Y d }
~
y d }
~
wt        $ r-}| j                  d|dt        |      |d       Y d }~y d }~ww xY w)Nusernamecyberark_sessionr   validate_certs</PasswordVault/WebServices/PIMServices.svc/Users/{pusername}	pusernameapplication/jsontoken$CyberArk/1.0 (Ansible; cyberark.pas)zContent-TypeAuthorizationz
User-AgentGETtimeoutmethodheadersr    r*   resultF  zWError while performing user_details.Please validate parameters provided.
*** end_point=
 ==> msgr-   status_codez;Unknown error while performing user_details.
*** end_point=
)paramsr   r   r   jsonloadsreadgetcoder   httplibHTTPExceptioncode	fail_jsonr   	Exception)moduler   r   r   r    r.   r   urlr-   responsehttp_exceptionunknown_exceptions               r   user_detailsrE      s}    }}Z(H}}%78#N3L%&67N FNUU`hUiI
i
0C +)'2<G'
)MM),
 DJJx}}78vx//122w,,- #%4!4!455
 GN35
  *//  	 	  

  124  	 	
 	


s1   AB( (EDE$-DE"#E

Ec           	      t	   | j                   d   }| j                   d   }|d   }|d   }i }i }d|d   dd}	|d	k(  rNd
}
||d<   dt        | j                   j                               v r9| j                   d   *| j                   d   |d<   n|dk(  rdj                  |      }
d| j                   v r!| j                   d   | j                   d   |d<   d| j                   v r!| j                   d   | j                   d   |d<   d| j                   v r!| j                   d   | j                   d   |d<   d| j                   v r!| j                   d   | j                   d   |d<   d| j                   v r!| j                   d   | j                   d   |d<   d| j                   v r!| j                   d   | j                   d   |d<   d| j                   v r3| j                   d   $| j                   d   |d<   | j                   d   |d<   d | j                   v r!| j                   d    | j                   d    |d!<   d"| j                   v r!| j                   d"   | j                   d"   |d#<   | j                   j	                  d$d       | j                   d$   |d%<   t        j                  d&|z   d'z   t        j                  | j                         z          t        j                  d(t        j                  |             t        j                  d)t        j                  |             |dk(  rd| j                   vs| j                   d   gt        j                  d*       d+}g d,}|D ]F  }t        j                  d-|       ||v s||v s#||   ||   k7  s/t        j                  d.|       d/}H nd/}|rt        j                  d0       t        |
      }	 t        |||	t        j                  |      || j                   d1   2      }d3t        j                  |j                               i}d/||j                         fS d+|d:fS # t        t         j"                  f$ r8}| j%                  d4|d5t'        |      ||	|j(                  6       Y d }~y d }~wt*        $ r.}| j%                  d7|d8t'        |      ||	d96       Y d }~y d }~ww xY w);Nr   r   r   r    r$   r%   r&   r'   POSTzPasswordVault/api/UsersUserNameinitial_passwordInitialPasswordPUTr!   r"   new_passwordNewPasswordemailEmail
first_name	FirstName	last_nameLastName!change_password_on_the_next_logonChangePasswordOnTheNextLogonexpiry_date
ExpiryDateuser_type_nameUserTypeNameuserTypedisabledDisabledlocationLocationauthorizationvaultAuthorizationzHTTPMethod = z module.params = zExisting Info: %szpayload => %sz Verifying if needs to be updatedF)
rO   rQ   rS   rU   rW   rY   r\   r^   rY   r`   z#### field_name : %szChanging value for %sTz%Proceeding to either update or creater*   r,   r-   datar    r*   r.   z]Error while performing user_add_or_update.Please validate parameters provided.
*** end_point=r0   r2   payloadr-   r3   zAUnknown error while performing user_add_or_update.
*** end_point=r4   r5      )r6   listkeysr   getloggingdebugr7   dumpsinfor   r   r8   r9   r:   r   r;   r<   r>   r   r=   r?   )r@   
HTTPMethodexisting_infor   r   r   r    r.   rd   r-   r   proceedupdateable_fields
field_namerA   rB   rC   rD   s                     r   user_add_or_updaterr     s    }}Z(H}}%78#N3L%&67N FG*)'2<G V-	&
$v}}'9'9';"<<01=)/7I)JG%&	u	RYYdlYm	 &6==+H+T!'~!>&--FMM'$:$F!==1v}}$|)D)P%}}\:fmm#k(B(N$mmK8
 	,v}}<MM=>J28--/3
./ %&--*F*R &m < 	FMM)MM*+7"(--0@"A$mm,<=
V]]"v}}Z'@'L$mmJ7
V]]"v}}Z'@'L$mmJ7
}}$/;(.o(F$% MM*$'::TZZ=VV MM%tzz-'@AMM/4::g#67Ufmm+v}}^/L/T78
 , 	JMM0*=g%-/J'=+DD5zB	 <=L)4(	  !ZZ(-i0H 

8==? ;<F&("2"2"4558 }c**5 7001 	
 GN35
  *//  
 
  	 G$568    	 		s%   A(P1 1R7
.Q==R7	$R22R7c           	         | j                   d   }| j                   d   }|d   }|d   }t        |dj                  |            }d|d   d	d
}	 t        |d||| j                   d         }t	        j
                  |j                               }d }	|d   D ](  }
|
d   |k(  s|	|
d   }	| j                  d|z         * t        j                  d||	       |	S # t        t        j                  f$ r9}t        |      }| j                  d|d|||j                         Y d }~y d }~wt        $ r-}| j                  d|dt        |      |d       Y d }~y d }~ww xY w)Nr   r   r   r    z*PasswordVault/api/Users?search={pusername}r"   r$   r%   r&   r'   r)   r*   r+   Usersidz?Found more than one user matching %s, this should be impossibler2   z!Resolved username {%s} to ID {%s}zVError while performing user_search.Please validate parameters provided.
*** end_point=r0   r1   z:Unknown error while performing user search.
*** end_point=r4   r5   )r6   r   r   r   r7   r8   r9   r>   ri   rj   r   r;   r<   r   r=   r?   )r@   r   r   r   r    rA   r-   rB   usersuser_iduserrC   exception_textrD   s                 r   resolve_username_to_idr{     s   }}Z(H}}%78#N3L%&67N
&R&Y&Ydl&Y&m
nC*)'2<G
*
)MM),
 

8==?+ 'N 	{DJ8+?"4jG$$*kow*x$z	{ 	98WMw,,- 	
 0 N$ &++ 	 	
 	
  
 G-.0  	 	
 	

s+   AC "7C E 3/D''E 3#EE c           	      |   | j                   d   }|d   }|d   }i }t        |       }|d|d fS dj                  |      }d|d   d	d
}t        ||      }	 t	        |d||| j                   d         }	di i}d||	j                         fS # t        t        j                  f$ rd}
t        |
      }|
j                  dk(  rd|v rdi i}d||
j                  fcY d }
~
S | j                  d|d|||
j                         Y d }
~
y d }
~
wt        $ r-}| j                  d|dt        |      |d       Y d }~y d }~ww xY w)Nr   r   r    Fz&PasswordVault/api/Users/{pvaultuserid})pvaultuseridr$   r%   r&   r'   DELETEr*   r+   r.   Tr/   	ITATS003EzVError while performing user_delete.Please validate parameters provided.
*** end_point=r0   r1   z:Unknown error while performing user_delete.
*** end_point=r4   r5   )r6   r{   r   r   r   r:   r   r;   r<   r   r=   r>   r?   )r@   r   r   r    r.   vault_user_idr   r-   rA   rB   rC   rz   rD   s                r   user_deleter     s    }}%78#N3L%&67N F*62Mvt$$9AA}A]I +)'2<G
 i
0C,
 )MM),
 Bfh..011w,,-  0#%+*G^F6>#6#677
 N,
  *//  	 	  

  124  	 	
 	


s0   3B
 
D;#0DD;$DD;#D66D;c                    | j                   d   }| j                   d   }|d   }|d   }d|d   dd}t        |d	j                  t        |      
            }	 t	        |d||| j                   d         }t        j                  |j                               }d }	|d   D ](  }
|
d   |k(  s|	|
d   }	| j                  d|z         * t        j                  d||	       |	S # t        t        j                  f$ r;}| j                  d|d|dt        |      i ||j                         Y d }~y d }~wt         $ r1}| j                  d|d|dt        |      i |d       Y d }~y d }~ww xY w)N
group_namer   r   r    r$   r%   r&   r'   z1/PasswordVault/api/UserGroups?search={pgroupname}
pgroupnamer)   r*   r+   value	groupNameru   z;Found more than one group matching %s. Use vault_id insteadrv   zResolved group_name %s to ID %szError while looking up group z.
*** end_point=r0   rc   z%Unknown error while looking up group r4   r5   )r6   r   r   r   r   r7   r8   r9   r>   ri   rj   r   r;   r<   r   r=   r?   )r@   r   r   r   r    r-   rA   rB   groupsgroup_idgrouprC   rD   s                r   resolve_group_name_to_idr   8  s   |,J}}%78#N3L%&67N*)'2<G
 &Y&`&`lqr|l}&`&~
C'
)MM),
 HMMO, G_ 	yE[!Z/#$T{H$$*gku*v$x	y 	7XNw,,- 
3 79&++ 	 	
 	
  
3(9 :< 	 	
 	

s+   AC# +7C# #E/<1D22E/>'E**E/c           	         | j                   d   }| j                   d   }| j                   d   }| j                   d   dn| j                   d   }|dk(  r| j                   d   nd }| j                   d   }|d	   }|d
   }i }	d|d   dd}
|r1|s/t        |       }|"| j                  dj                  |             dj                  |      }||d}|r||d<   t	        ||      }	 t        |d|
t        j                  |      || j                   d         }di i}	d|	|j                         fS # t        t        j                  f$ r}t        |      }t        j                  |j                         j                               }|j                   dk(  r-d|v s|j#                  dd      dk(  rd d |j                   fcY d }~S | j                  d!|d"|||
|j                   |j                         j                         #       Y d }~y d }~wt$        $ r.}| j                  d$|d%t        |      ||
d&'       Y d }~y d }~ww xY w)(Nr   r   vault_idmember_typeVaultdomaindomain_namer   r   r    r$   r%   r&   r'   z]Unable to find a user group named {pgroupname}, please create that before adding a user to itr   rv   z0/PasswordVault/api/UserGroups/{pvaultid}/Members)pvaultid)memberId
memberType
domainNamerG   r*   ra   r.   Ti  	ITATS262E	ErrorCode 	PASWS213EFz\Error while performing user_add_to_group.Please validate parameters provided.
*** end_point=r0   )r2   rd   r-   r3   rB   z@Unknown error while performing user_add_to_group.
*** end_point=r4   r5   rc   )r6   r   r>   r   r   r   r7   rk   r:   r   r;   r<   r   r8   r9   decoder=   rh   r?   )r@   r   r   r   r   r   r   r   r    r.   r-   r   rd   rA   rB   rC   rz   exception_bodyrD   s                      r   user_add_to_groupr   m  s    }}Z(H|,J}}Z(H =='/ 	]]=) 
 3>2I&--.tK}}%78#N3L%&67N F*)'2<G (+F3  "A  "H  "H  T^  "H  "_  `CKKU]K^I $;?G +
i
0C0
 G$)MM),
 Bfh..011w,,-  0N$7$7$9$@$@$BC#%;.+HNL^L^_jlnLos~L~4!4!455
 N,
  *//',,.557     
  124  	 		
 		

s3   &AD. .I A2H9I ?AHI $H;;I c                     t        t        d5i dt        dd      dt        ddddg      d	t        dd
g d      dt        dd      dt        dd      dt        dd      dt        dd      dt        d      dt        d      dt        d      dt        dd      dt        d      dt        d      dt        dd      dt        d      dt        d      d t        d!      d"t        d      d#t        d      d$t        d%d&      d't        d(ddd)d*g+      ,      } | j                  d	   1t        j                  | j                  d   | j                  d	   -       t        j
                  d.       | j                  d   }| j                  d   }| j                  d    }|dk(  rYt        |       \  }}}|d/k(  rt        | d0|d1         \  }}}n|d2k(  rt        | d3d       \  }}}||*t        |       \  }}}	|xs |}n|dk(  rt        |       \  }}}| j                  4       y )6Nr   strT)typerequiredstatepresentabsent)r   defaultchoiceslogging_levelNOTSET)r   DEBUGINFOlogging_filez/tmp/ansible_cyberark.log)r   r   r   dictrI   )r   no_logrL   rN   )r   rP   rR   rT   boolFrV   rX   r[   r]   r   r   intr   r   r*   float
   r_   rf   AddSafes
AuditUsers)r   elementsr   r   )argument_spec)filenamelevelzStarting Modulere   rK   r.   r/   rG   )changedcyberark_userr3    )r   r   r6   ri   basicConfigrl   rE   rr   r   r   	exit_json)
r@   r   r   r   r   r.   r3   group_change	no_resultno_status_codes
             r   mainr     s    
ut4
E9x>ST
 H6Q
 52MN
 "v=
 "uT:
 56
 E"
 '
 &
 /3.N
 %(
  U+
  vu5!
" u%#
$ '%
& u%'
( %()
* %(+
, gr2-
. FUUU_amTno/
F8 }}_%1]]>2&--:X	
 LL"#MM'"E|,J}}Z(H	)5f)=&&+# .@vh/.*Wfk C-?PT-U*Wfk !X%98I&8Q5\9n-G	(	)4V)<&&+
WFTr   __main__)"
__future__r   r   r   r   __metaclass__ANSIBLE_METADATADOCUMENTATIONEXAMPLESRETURNr7   ansible.module_utils.basicr   ansible.module_utils._textr   ansible.module_utils.six.movesr   r;   +ansible.module_utils.six.moves.urllib.errorr   ansible.module_utils.urlsr   +ansible.module_utils.six.moves.urllib.parser   ri   r   rE   rr   r{   r   r   r   r   __name__r   r   r   <module>r      s    C B  k FP<
*  4 . A A . = k;
|\+~5
pD
N2
j[
|?UD zF r   