
    Vhm                     *   d Z dZd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mZ ddlmZ ddlmZ ddlmZ ddlmZ  ej&                  d      d        Zd Z ej&                  d      d        Z ej&                  d      d        Z ej0                  d      d        Zd Zd Z ej0                  d      d        Z ej:                  d      d        Zd Z ej0                  d      d         Z  ej&                  d!      d"        Z! ej&                  d#      d$        Z"d% Z# ej&                  d&      d'        Z$ ej:                  d(      d)        Z% ej&                  d*      d+        Z&d, Z' ej&                  d-      d.        Z(d/ Z) ej:                  d0      d1        Z* ej0                  d2      d3        Z+ ej:                  d4      d5        Z, ej0                  d6      d7        Z- ej:                  d8      d9        Z. ej0                  d:      d;        Z/ ej:                  d<      d=        Z0 ej0                  d>      d?        Z1 ej:                  d@      dA        Z2 ej0                  dB      dC        Z3dD Z4 ej:                  dE      dF        Z5 ej0                  dG      dH        Z6 ej:                  dI      dJ        Z7 ej0                  dK      dL        Z8 ej:                  dM      dN        Z9dO Z:dP Z;e<dQk(  r e;        yRyR)SaD  
---
module: iam_user
version_added: 5.0.0
short_description: Manage AWS IAM users
description:
  - A module to manage AWS IAM users.
  - The module does not manage groups that users belong to, groups memberships can be managed using M(amazon.aws.iam_group).
  - This module was originally added to C(community.aws) in release 1.0.0.
author:
  - Josh Souza (@joshsouza)
options:
  name:
    description:
      - The name of the user.
      - >-
        Note: user names are unique within an account.  Paths (O(path)) do B(not) affect
        the uniqueness requirements of O(name).  For example it is not permitted to have both
        C(/Path1/MyUser) and C(/Path2/MyUser) in the same account.
      - O(user_name) was added as an alias in release 7.2.0.
    required: true
    type: str
    aliases: ['user_name']
  path:
    description:
      - The path for the user.
      - For more information about IAM paths, see the AWS IAM identifiers documentation
        U(https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_identifiers.html).
    aliases: ['prefix', 'path_prefix']
    required: false
    type: str
    version_added: 7.2.0
  boundary:
    description:
      - The ARN of an IAM managed policy to apply as a boundary policy for this user.
      - Boundary policies can be used to restrict the permissions a user can excercise, but does not
        grant any policies in and of itself.
      - For more information on boundaries, see
        U(https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_boundaries.html).
      - Set to the empty string V("") to remove the boundary policy.
    aliases: ["boundary_policy_arn", "permissions_boundary"]
    required: false
    type: str
    version_added: 7.2.0
  password:
    description:
      - The password to apply to the user.
    required: false
    type: str
    version_added: 2.2.0
    version_added_collection: community.aws
  password_reset_required:
    description:
      - Defines if the user is required to set a new password when they log in.
      - Ignored unless a new password is set.
    required: false
    type: bool
    default: false
    version_added: 3.1.0
    version_added_collection: community.aws
  update_password:
    default: always
    choices: ['always', 'on_create']
    description:
      - When to update user passwords.
      - O(update_password=always) will ensure the password is set to O(password).
      - O(update_password=on_create) will only set the password for newly created users.
    type: str
    version_added: 2.2.0
    version_added_collection: community.aws
  remove_password:
    description:
      - Option to delete user login passwords.
      - This field is mutually exclusive to O(password).
    type: 'bool'
    version_added: 2.2.0
    version_added_collection: community.aws
  managed_policies:
    description:
      - A list of managed policy ARNs or friendly names to attach to the user.
      - To embed an inline policy, use M(community.aws.iam_policy).
    required: false
    type: list
    default: []
    elements: str
    aliases: ['managed_policy']
  state:
    description:
      - Create or remove the IAM user.
    required: true
    choices: [ 'present', 'absent' ]
    type: str
  purge_policies:
    description:
      - When O(purge_policies=true) any managed policies not listed in O(managed_policies) will be detached.
    required: false
    default: false
    type: bool
    aliases: ['purge_policy', 'purge_managed_policies']
  wait:
    description:
      - When O(wait=True) the module will wait for up to O(wait_timeout) seconds
        for IAM user creation before returning.
    default: True
    type: bool
    version_added: 2.2.0
    version_added_collection: community.aws
  wait_timeout:
    description:
      - How long (in seconds) to wait for creation / updates to complete.
    default: 120
    type: int
    version_added: 2.2.0
    version_added_collection: community.aws
notes:
  - Support for O(tags) and O(purge_tags) was added in release 2.1.0.
extends_documentation_fragment:
  - amazon.aws.common.modules
  - amazon.aws.region.modules
  - amazon.aws.tags
  - amazon.aws.boto3
a2  
# Note: These examples do not set authentication details, see the AWS Guide for details.
# Note: This module does not allow management of groups that users belong to.
#       Groups should manage their membership directly using amazon.aws.iam_group,
#       as users belong to them.

- name: Create a user
  amazon.aws.iam_user:
    name: testuser1
    state: present

- name: Create a user with a password
  amazon.aws.iam_user:
    name: testuser1
    password: SomeSecurePassword
    state: present

- name: Create a user and attach a managed policy using its ARN
  amazon.aws.iam_user:
    name: testuser1
    managed_policies:
      - arn:aws:iam::aws:policy/AmazonSNSFullAccess
    state: present

- name: Remove all managed policies from an existing user with an empty list
  amazon.aws.iam_user:
    name: testuser1
    state: present
    purge_policies: true

- name: Create user with tags
  amazon.aws.iam_user:
    name: testuser1
    state: present
    tags:
      Env: Prod

- name: Delete the user
  amazon.aws.iam_user:
    name: testuser1
    state: absent
aE  
user:
    description: Dictionary containing all the user information.
    returned: success
    type: complex
    contains:
        arn:
            description: The Amazon Resource Name (ARN) specifying the user.
            type: str
            returned: always
            sample: "arn:aws:iam::123456789012:user/testuser1"
        create_date:
            description: The date and time, in ISO 8601 date-time format, when the user was created.
            type: str
            returned: always
            sample: "2017-02-08T04:36:28+00:00"
        user_id:
            description: The stable and unique string identifying the user.
            type: str
            returned: always
            sample: "AGPA12345EXAMPLE54321"
        user_name:
            description: The friendly name that identifies the user.
            type: str
            returned: always
            sample: "testuser1"
        path:
            description: The path to the user.
            type: str
            returned: always
            sample: "/"
        tags:
            description: User tags.
            type: dict
            returned: always
            sample: {"Env": "Prod"}
        attached_policies:
            version_added: 7.2.0
            description:
                - List containing basic information about managed policies attached to the group.
            returned: always
            type: list
            elements: dict
            sample: [
                        {
                            "policy_arn": "arn:aws:iam::123456789012:policy/test_policy",
                            "policy_name": "test_policy"
                        }
                    ]
            contains:
                policy_arn:
                    description: The Amazon Resource Name (ARN) specifying the managed policy.
                    type: str
                    sample: "arn:aws:iam::123456789012:policy/test_policy"
                policy_name:
                    description: The friendly name that identifies the policy.
                    type: str
                    sample: test_policy
    )camel_dict_to_snake_dict)AnsibleIAMError)IAMErrorHandler)$convert_managed_policy_names_to_arns)get_iam_user)normalize_iam_user)validate_iam_identifiers)AnsibleAWSModule)AWSRetry)ansible_dict_to_boto3_tag_list)compare_aws_tagszwait for IAM user creationc                 J    | j                  d      } |j                  di | y )Nuser_exists )
get_waiterwait)
connectionparamswaiters      g/home/dcms/DCMS/lib/python3.12/site-packages/ansible_collections/amazon/aws/plugins/modules/iam_user.py_wait_user_existsr      s#    ""=1FFKK&    c                     |j                   j                  d      sy |j                   j                  d      }|j                   j                  d      }t        |d      }||z  }||d}t        | ||       y )Nr   namewait_timeout   )DelayMaxAttempts)WaiterConfigUserName)r   getminr   )r   module	user_namer   delaymax_attemptswaiter_configs          r   wait_iam_existsr(      sk    ==V$!!&)I==$$^4La E5(L#LAMj}yQr   zcreate userc                     d|i}|r||d<   |r||d<   |rt        |      |d<   |j                  r|j                  d|        | j                  d	ddi|d   }t	        |      S )
Nr    PathPermissionsBoundaryTagsT)changedcreate_params	aws_retryUserr   )r   
check_mode	exit_jsoncreate_userr   )r   r#   r$   pathboundarytagsr   users           r   r3   r3     s}    )$Fv(0$%7=vV<!:!!;D;F;FCDd##r   zcreate user login profilec                 *     | j                   dddi|S Nr/   Tr   )create_login_profiler   r   s     r   _create_login_profiler<         *:**DTDVDDr   zupdate user login profilec                 *     | j                   dddi|S r9   )update_login_profiler;   s     r   _update_login_profiler@   $  r=   r   c                 F    |||d}t        | fi |}|r|S t        | fi |S )N)r    PasswordPasswordResetRequired)r@   r<   )r   r   passwordresetuser_paramsretvals         r   _create_or_update_login_profilerH   )  s=     !&K #:==F ;{;;r   c                 >    |y|dk(  r|sy|rydt        | |||      fS )N)FN	on_create)TNT)rH   )r   r1   r$   rD   updaterE   new_users          r   ensure_login_profilerM   7  s6    X0YRWXXXr   zget login profilec                 F    | j                  d|      j                  d      S )NTr/   r    LoginProfile)get_login_profiler!   r   r   s     r   _get_login_profilerS   C  s#    ''$'FJJ>ZZr   zdelete login profilec                 *    | j                  d|       y NTrO   )delete_login_profilerR   s     r   _delete_login_profilerW   H  s    ##dT#Br   c                 L    |ry|syt        | |      }|sy|ryt        | |       y)NFT)rS   rW   )r   r1   r$   remove_passwordrL   login_profiles         r   remove_login_profiler[   M  s5     'z9=M*i0r   zget policies for userc                 .    | j                  d|      d   S )NTrO   AttachedPolicies)list_attached_user_policies)r   r$   s     r   _list_attached_policiesr_   _  s    11D91UVhiir   zattach policy to userc                 D    |sy|ry|D ]  }| j                  ||        y NFT)r    	PolicyArn)attach_user_policyr   r1   r$   policies
policy_arns        r   attach_policiesrg   d  2     P
%%yJ%OPr   zdetach policy from userc                 D    |sy|ry|D ]  }| j                  ||        y ra   )detach_user_policyrd   s        r   detach_policiesrk   n  rh   r   c                 8   |yt        | |      }t        | |      }|D cg c]  }|d   	 }}t        t        |      t        |      z
        }g }	|r t        t        |      t        |      z
        }	|s|	sy|ryt	        | |||	       t        | |||       yc c}w )NFrb   T)r   r_   listsetrk   rg   )
r   r1   r$   managed_policiespurge_policiesattached_policies_descpolicycurrent_attached_policiespolicies_to_addpolicies_to_removes
             r   ensure_managed_policiesrv   x  s    ;JHXY 5ZKCY Z!4 Z Z3/037P3QQRO!#&?"@3GWCX"XY#5J
I7IJJ
IG! ![s   Bzset tags for userc                     |y|d   }t        |||      \  }}|s|sy|ry|r| j                  ||       |r| j                  |t        |             y)NFr6   )
purge_tagsT)r    TagKeys)r    r,   )r   
untag_usertag_userr   )	r   r1   r7   r$   new_tagsrx   existing_tagstags_to_addtags_to_removes	            r   ensure_user_tagsr     sl    LM"2=(Wa"bK+y.IY5ST_5`ar   z$remove permissions boundary for userc                 0    |ry| j                  d|       y rU   ) delete_user_permissions_boundaryr   r1   r$   s      r   !_delete_user_permissions_boundaryr     s    //$/Sr   z!set permissions boundary for userc                 2    |ry| j                  d||       y )NT)r/   r    r+   )put_user_permissions_boundary)r   r1   r$   r5   s       r   _put_user_permissions_boundaryr     s    ,,tiem,nr   c                     |y|r|j                  dd      nd }|r|j                  d      }||k(  ry|ry|dk(  rt        | ||       yt        | |||       y)NFpermissions_boundary permissions_boundary_arnT)r!   r   r   )r   r1   r7   r$   r5   current_boundarys         r   ensure_permissions_boundaryr     ss    ?Ctxx 6;+//0JK##2~)*j)L  	'z:y(Sr   zset path for userc                 p    |y|r|j                  dd      nd }||k(  ry|ry| j                  d||       y)NFr4   r   T)r/   r    NewPath)r!   update_user)r   r1   r7   r$   r4   current_paths         r   ensure_pathr     sG    |+/488FB'TL|TItLr   c                 N   |j                   j                  d      }d}d}t        | |      }|j                   j                  d      }|r)t        | |j                   j                  d      g      d   }|Rt	        | |||j                   j                  d      ||j                   j                  d            }d}t        | |       d}t        | |j                  ||j                   j                  d      |j                   j                  d	      |j                   j                  d
      |      \  }}||z  }|t        | |j                  ||j                   j                  d      |      z  }|t        | |j                  |||      z  }|t        | |j                  |||j                   j                  d            z  }|t        | |j                  ||j                   j                  d      |j                   j                  d            z  }|t        | |j                  |||j                   j                  d      |j                   j                  d            z  }|j                  r|j                  |       t        | |      }|r'|r%|j                  di       j                  dd      |d
<   	 dt        | |      i}	|j                  t!        |	             |j                  |d|i|       y # t"        $ r1}
|j%                  dt'        |
j(                                Y d }
~
Ld }
~
ww xY w)Nr   Fr5   r   r4   r6   TrD   update_passwordpassword_reset_requiredrY   ro   rp   rx   r-   rP   rC   attached_policiesz#Failed to list attached policies - r7   )r-   iam_userr7   )r   r!   r   r   r3   r(   rM   r1   r[   r   r   rv   r   r2   r_   rK   r   r   warnstr	exception)r   r#   r$   r-   rL   r7   r5   profile_changedrZ   re   es              r   create_or_update_userr     s   !!&)IGH
I.D}}  ,H7
V]]EVEVWaEbDcdefg|MMf%MMf%
 
F+%9*%+,34&"O] G#+, G * G {&! G &,-*+ G &!,' G ) 
I.D=*7*;*;NB*O*S*STkmr*s&'')@Y)WX,X67 W~DI  1#akk2B1CD	
 		s   +(K* *	L$3'LL$zdelete access keyc                 2    |ry| j                  d||       y)NT)r/   r    AccessKeyId)delete_access_keyr   r1   r$   key_ids       r   r   r   E  s!      4)QW Xr   zlist access keysc                 f    | j                  d|      d   }|sy|D ]  }t        | |||d           y)NTrO   AccessKeyMetadataFr   )list_access_keysr   )r   r1   r$   access_keys
access_keys        r   delete_access_keysr   M  sJ    --y-QRefK! X
*j)Z=VWXr   zdelete SSH keyc                 2    |ry| j                  d||       yNT)r/   r    SSHPublicKeyIddelete_ssh_public_keyr   s       r   delete_ssh_keyr   W  s!    $$tiX^$_r   zlist SSH keysc                 f    | j                  d|      d   }|sy|D ]  }t        | |||d           y)NTrO   SSHPublicKeysFr   )list_ssh_public_keysr   )r   r1   r$   public_keys
public_keys        r   delete_ssh_public_keysr   _  sK    11D91UVefK! X
z:y*EU:VWXr   zdelete service credentialc                 2    |ry| j                  d||       yr   r   )r   r1   r$   cred_ids       r   delete_service_credentialr   i  s!    $$tiX_$`r   zlist service credentialsc                 f    | j                  d|      d   }|sy|D ]  }t        | |||d           y)NTrO   ServiceSpecificCredentialsFServiceSpecificCredentialId)!list_service_specific_credentialsr   )r   r1   r$   credentials
credentials        r   delete_service_credentialsr   q  sP    >>Xa>b$K ! p
!*j)ZPmEnopr   zdelete signing certificatec                 2    |ry| j                  d||       y)NT)r/   r    CertificateId)delete_signing_certificate)r   r1   r$   cert_ids       r   r   r   }  s!    ))D9\c)dr   zlist signing certificatesc                 f    | j                  d|      d   }|sy|D ]  }t        | |||d           y)NTrO   CertificatesFr   )list_signing_certificatesr   )r   r1   r$   certificatescertificates        r   delete_signing_certificatesr     sL    77$QZ7[\jkL# d":z9kRaFbcdr   zdelete MFA devicec                 2    |ry| j                  d||       y)NT)r/   r    SerialNumber)deactivate_mfa_device)r   r1   r$   	device_ids       r   delete_mfa_devicer     s!    $$tiV_$`r   zlist MFA devicesc                 f    | j                  d|      d   }|sy|D ]  }t        | |||d           y)NTrO   
MFADevicesFr   )list_mfa_devicesr   )r   r1   r$   devicesdevices        r   delete_mfa_devicesr     sI    ))D9)Ml[G U*j)VN=STUr   c                 f    t        | |      }|D cg c]  }|d   	 }}t        | |||       y c c}w )Nrb   )r_   rk   )r   r1   r$   rq   rr   rs   s         r   detach_all_policiesr     s=    4ZKCY Z!4 Z ZJ
I7PQ ![s   .zdelete inline policyc                 2    |ry| j                  d||       y)NT)r/   r    
PolicyName)delete_user_policy)r   r1   r$   rr   s       r   delete_inline_policyr     s!    !!D9QW!Xr   zlist inline policiesc                 `    | j                  d|      d   }|sy|D ]  }t        | |||        y)NTrO   PolicyNamesF)list_user_policiesr   )r   r1   r$   inline_policiespolicy_names        r   delete_inline_policiesr     sE     33dY3WXefO& MZYLMr   zremove user from groupc                 2    |ry| j                  d||       y)NT)r/   r    	GroupName)remove_user_from_group)r   r1   r$   
group_names       r   remove_from_groupr     s!    %%yT^%_r   zlist groups containing userc                 f    | j                  d|      d   }|sy|D ]  }t        | |||d           y)NTrO   GroupsFr   )list_groups_for_userr   )r   r1   r$   user_groupsgroups        r   remove_from_all_groupsr     sJ    11D91UV^_K Q*j)U;=OPQr   zdelete userc                 0    |ry| j                  d|       yrU   )delete_userr   s      r   r   r     s    TI>r   c                    |j                   j                  d      }t        | |      }|s|j                  d       |j                  r|j                  d       t        | |j                  |dd       t        | |j                  |       t        | |j                  |       t        | |j                  |       t        | |j                  |       t        | |j                  |       t        | |j                  |       t        | |j                  |       t        | |j                  |       t        | |j                  |      }|j                  |       y )Nr   Fr   T)r   r!   r   r2   r1   r[   r   r   r   r   r   r   r   r   r   )r   r#   r$   r7   r-   s        r   destroy_userr     s   !!&)I
I.D' &$ V%6%6	4Oz6#4#4i@:v'8'8)Dz6+<+<iH
F,=,=yIz6#4#4i@
F$5$5yA:v'8'8)D:v'8'8)D*f&7&7CG
W%r   c                     t        t        dddg      t        dddg      t        ddd	g      t        dd
      t        ddd      t        dddgd      t        dd
      t        g ddgd      t        ddgd      t        ddddg      t        ddg      t        dd      t        dd      t        dd             } t        | dd!d"gg#      }|j                  d$d%d&'       t        d(|j                  j                  d)      |j                  j                  d*      +      }|r|j                  |,       t        j                  d-g.      }|j                  d/|0      }|j                  j                  d1      }	 |dk(  rt        ||       y t        ||       y # t        $ r}|j                  |       Y d }~y d }~ww xY w)2NTr   r$   )requiredtypealiasesprefixpath_prefix)r   r   boundary_policy_arnr   )r   no_logboolF)r   defaultr   alwaysrJ   )r   choicesr   rm   managed_policy)r   r   r   elementspresentabsent)r   r   purge_policypurge_managed_policies)r   r   r   dictresource_tags)r   r   x   int)r   r   )r   r4   r5   rD   r   r   rY   ro   staterp   r6   rx   r   r   rD   rY   )argument_specsupports_check_modemutually_exclusiveziThe 'iam_user' return key is deprecated and will be replaced by 'user'. Both values are returned for now.z
2024-05-01z
amazon.aws)datecollection_namer7   r   r4   )r   r4   )msgEntityTemporarilyUnmodifiable)catch_extra_error_codesiam)retry_decoratorr  )r  r
   	deprecater	   r   r!   	fail_jsonr   jittered_backoffclientr   r   r   fail_json_aws_error)r  r#   identifier_problemr  r   r  r   s          r   mainr    s   4ek]Cux&?@5+@BX*YZ5. $&% NX+7NW\]&7bv@P?Q\abIx04@EQi@jkv'89VT2vt,#E2M" # '):;<F s$   2V]]&&v.V]]5F5Fv5N /0//IhHijOuoFJMMg&E&I!*f5V, &""1%%&s   F% F% %	G	.GG	__main__N)=DOCUMENTATIONEXAMPLESRETURN0ansible.module_utils.common.dict_transformationsr   7ansible_collections.amazon.aws.plugins.module_utils.iamr   r   r   r   r   r	   ;ansible_collections.amazon.aws.plugins.module_utils.modulesr
   ;ansible_collections.amazon.aws.plugins.module_utils.retriesr   ;ansible_collections.amazon.aws.plugins.module_utils.taggingr   r   common_error_handlerr   r(   r3   r<   list_error_handlerr@   rH   rM   rS   deletion_error_handlerrW   r[   r_   rg   rk   rv   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  __name__r   r   r   <module>r%     se  yv)V:
x V S S h P V \ X P f X &%%&BC D
R &%%m4$ 5$" &%%&ABE CE $##$?@E AE<	Y $##$78[ 9[ (''(>?C @C$ $##$;<j =j &%%&=>P ?P &%%&?@P AP6 &%%&9: ;, (''(NOT PT &%%&IJo Ko. &%%&9: ;"aJH (''(;< = $##$67 8 (''(89 : $##O4 5 (''(CD E $##$>? @ (''(DE F $##$?@ A (''(;< = $##$67 8R (''(>? @ $##$:; < (''(@A B $##$AB C (''6 7&&R/&d zF r   