
    Vh0                        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mZ  G d de      Z G d d      Z G d de      Z G d de      Z G d de      Zd Zedk(  r e        yy# e$ r Y lw xY w)aU  
---
module: iam_policy
version_added: 5.0.0
short_description: Manage inline IAM policies for users, groups, and roles
description:
  - Allows uploading or removing inline IAM policies for IAM users, groups or roles.
  - To administer managed policies please see M(community.aws.iam_user), M(community.aws.iam_role),
    M(amazon.aws.iam_group) and M(community.aws.iam_managed_policy).
  - This module was originally added to C(community.aws) in release 1.0.0.
options:
  iam_type:
    description:
      - Type of IAM resource.
    required: true
    choices: [ "user", "group", "role"]
    type: str
  iam_name:
    description:
      - Name of IAM resource you wish to target for policy actions. In other words, the user name, group name or role name.
    required: true
    type: str
  policy_name:
    description:
      - The name label for the policy to create or remove.
    required: true
    type: str
  policy_json:
    description:
      - A properly json formatted policy as string.
    type: json
  state:
    description:
      - Whether to create or delete the IAM policy.
    choices: [ "present", "absent"]
    default: present
    type: str
  skip_duplicates:
    description:
      - When O(skip_duplicates=true) the module looks for any policies that match the document you pass in.
        If there is a match it will not make a new policy object with the same rules.
    default: false
    type: bool

author:
  - "Jonathan I. Davila (@defionscode)"
  - "Dennis Podkovyrin (@sbj-ss)"
extends_documentation_fragment:
  - amazon.aws.common.modules
  - amazon.aws.region.modules
  - amazon.aws.boto3
a  
# Advanced example, create two new groups and add a READ-ONLY policy to both
# groups.
- name: Create Two Groups, Mario and Luigi
  amazon.aws.iam_group:
    name: "{{ item }}"
    state: present
  loop:
    - Mario
    - Luigi
  register: new_groups

- name: Apply READ-ONLY policy to new groups that have been recently created
  amazon.aws.iam_policy:
    iam_type: group
    iam_name: "{{ item.iam_group.group.group_name }}"
    policy_name: "READ-ONLY"
    policy_json: "{{ lookup('template', 'readonly.json.j2') }}"
    state: present
  loop: "{{ new_groups.results }}"

# Create a new S3 policy with prefix per user
- name: Create S3 policy from template
  amazon.aws.iam_policy:
    iam_type: user
    iam_name: "{{ item.user }}"
    policy_name: "s3_limited_access_{{ item.prefix }}"
    state: present
    policy_json: "{{ lookup('template', 's3_policy.json.j2') }}"
    loop:
      - user: s3_user
        prefix: s3_user_prefix
a  
user_name:
    description: Name of IAM user.
    returned: When I(iam_type=user)
    type: str
    sample: "ExampleUser001"
group_name:
    description: Name of IAM group.
    returned: When I(iam_type=group)
    type: str
    sample: "ExampleGroup001"
role_name:
    description: Name of IAM role.
    returned: When I(iam_type=role)
    type: str
    sample: "ExampleRole001"
policy_names:
    description: A list of names of the inline policies embedded in the specified IAM resource (user, group, or role).
    returned: always
    type: list
    elements: str
    sample: ["READ-ONLY"]
diff:
    description: A dict representing difference between policies applied on IAM resource (user, group, or role).
    returned: always
    type: dict
    contains:
        before:
            description: The policy that exists on IAM resource before new policy is applied.
            returned: always
            type: dict
            sample: {
                        "READ-ONLY": {
                            "Statement": [
                                {
                                    "Action": "ec2:DescribeAccountAttributes",
                                    "Effect": "Deny",
                                    "Resource": "*",
                                    "Sid": "VisualEditor0"
                                }
                            ],
                            "Version": "2012-10-17"
                        }
                    }
        after:
            description: The current policy on IAM resource after new policy is applied.
            returned: always
            type: dict
            sample: {
                        "READ-ONLY": {
                            "Statement": [
                                {
                                    "Action": "ec2:DescribeAccountAttributes",
                                    "Effect": "Allow",
                                    "Resource": "*",
                                    "Sid": "VisualEditor0"
                                }
                            ],
                            "Version": "2012-10-17"
                        }
                    }
    N)BotoCoreError)ClientError)string_types)is_boto3_error_code)AnsibleAWSModule)compare_policies)AWSRetryc                       e Zd Zy)PolicyErrorN)__name__
__module____qualname__     i/home/dcms/DCMS/lib/python3.12/site-packages/ansible_collections/amazon/aws/plugins/modules/iam_policy.pyr   r      s    r   r   c                   p    e Zd Zd Zed        Zd Zd Zd Zd Z	d Z
d Zd	 Zd
 Zd Zd Zd Zd Zd Zy)Policyc                     || _         || _        || _        || _        || _        || _        || _        d| _        | j                         j                         | _
        i | _        y )NF)clientnamepolicy_namepolicy_jsonskip_duplicatesstate
check_modechangedget_all_policiescopyoriginal_policiesupdated_policies)selfr   r   r   r   r   r   r   s           r   __init__zPolicy.__init__   s_    	&&.
$!%!6!6!8!=!=!? "r   c                       y)N r   r   r   r   	_iam_typezPolicy._iam_type   s    r   c                     i S Nr   r!   r   s     r   _listzPolicy._list   s    	r   c                     	 | j                  | j                        j                  dg       S # t        d      $ r g cY S w xY w)NPolicyNamesAccessDenied)r)   r   getr   r!   s    r   listzPolicy.list   s@    	::dii(,,]B??">2 	I	s   *- A A c                      y)Nz{}r   r!   r   r   s      r   _getzPolicy._get   s    r   c                 n    	 | j                  | j                  |      d   S # t        d      $ r i cY S w xY w)NPolicyDocumentr,   )r2   r   r   )r!   r   s     r   r-   z
Policy.get   s;    	99TYY45EFF">2 	I	s   ! 44c                      y r'   r   r!   r   r   
policy_docs       r   _putzPolicy._put       r   c                     d| _         | j                  ry | j                  | j                  | j                  t        j                  |d             y )NT)	sort_keys)r   r   r8   r   r   jsondumps)r!   r7   s     r   putz
Policy.put   s9    ??		$))T--tzz*PT/UVr   c                      y r'   r   r1   s      r   _deletezPolicy._delete   r9   r   c                 J   | j                   j                         | _        | j                  | j	                         vrd| _        y d| _        | j                  j                  | j                  d        | j                  ry | j                  | j                  | j                         y NFT)
r   r   r    r   r/   r   popr   r@   r   r.   s    r   deletezPolicy.delete   s|     $ 6 6 ; ; =499;. DL!!$"2"2D9??TYY 0 01r   c                     	 | j                   | j                         S 	 y # t        j                  $ r}t	        dt        |             d }~ww xY w)Nz+Failed to decode the policy as valid JSON: )r   get_policy_from_jsonr<   JSONDecodeErrorr   str)r!   es     r   get_policy_textzPolicy.get_policy_text   s_    	V+0022 ,  ## 	V KCPQF8TUU	Vs     AA

Ac                     t        | j                  t              r!t        j                  | j                        }|S | j                  }|S r'   )
isinstancer   r   r<   loads)r!   pdocs     r   rF   zPolicy.get_policy_from_json   s?    d&&5::d../D  ##Dr   c                 \    i }| j                         D ]  }| j                  |      ||<    |S r'   )r/   r-   )r!   policiespols      r   r   zPolicy.get_all_policies  s2    99; 	*C HHSMHSM	*r   c                 ~   g }| j                         }d}| j                         D ]/  }t        | j                  |   |      r|j	                  |       d}1 | j                  j                         | _        | j                  |v ry | j                  r|ry | j                  |       || j                  | j                  <   y rB   )
rJ   r/   r   r   appendr   r    r   r   r>   )r!   matching_policiesr7   policy_matchrQ   s        r   createzPolicy.create  s    ))+
99; 	$C#D$:$:3$?L!((-#	$
 !% 6 6 ; ; =00L2<d../r   c                 8   | j                   dk(  r| j                          n| j                   dk(  r| j                          d| j                  | j	                         dz   | j
                  d| j                         dt        | j                  | j                        iS )Npresentabsentr   _namepolicy_namesdiff)beforeafter)
r   rV   rD   r   r%   r   r/   dictr   r    r.   s    r   runz
Policy.run  s{    ::"KKMZZ8#KKMt||NNw&		DIIKD--++	
 	
r   N)r   r   r   r"   staticmethodr%   r)   r/   r2   r-   r8   r>   r@   rD   rJ   rF   r   rV   r`   r   r   r   r   r      s]    #  W2=&
r   r   c                   4    e Zd Zed        Zd Zd Zd Zd Zy)
UserPolicyc                       y)Nuserr   r   r   r   r%   zUserPolicy._iam_type+      r   c                 <    | j                   j                  d|      S )NT)	aws_retryUserName)r   list_user_policiesr(   s     r   r)   zUserPolicy._list/      {{--t-LLr   c                 >    | j                   j                  d||      S NT)rh   ri   
PolicyName)r   get_user_policyr1   s      r   r2   zUserPolicy._get2      {{**TDU`*aar   c                 @    | j                   j                  d|||      S )NT)rh   ri   rn   r4   )r   put_user_policyr6   s       r   r8   zUserPolicy._put5  (    {{**TkR\ + 
 	
r   c                 >    | j                   j                  d||      S rm   )r   delete_user_policyr1   s      r   r@   zUserPolicy._delete:      {{--tXc-ddr   N	r   r   r   ra   r%   r)   r2   r8   r@   r   r   r   rc   rc   *  +     Mb

er   rc   c                   4    e Zd Zed        Zd Zd Zd Zd Zy)
RolePolicyc                       y)Nroler   r   r   r   r%   zRolePolicy._iam_type?  rf   r   c                 <    | j                   j                  d|      S )NT)rh   RoleName)r   list_role_policiesr(   s     r   r)   zRolePolicy._listC  rk   r   c                 >    | j                   j                  d||      S NT)rh   r~   rn   )r   get_role_policyr1   s      r   r2   zRolePolicy._getF  rp   r   c                 @    | j                   j                  d|||      S )NT)rh   r~   rn   r4   )r   put_role_policyr6   s       r   r8   zRolePolicy._putI  rs   r   c                 >    | j                   j                  d||      S r   )r   delete_role_policyr1   s      r   r@   zRolePolicy._deleteN  rv   r   Nrw   r   r   r   rz   rz   >  rx   r   rz   c                   4    e Zd Zed        Zd Zd Zd Zd Zy)GroupPolicyc                       y)Ngroupr   r   r   r   r%   zGroupPolicy._iam_typeS  s    r   c                 <    | j                   j                  d|      S )NT)rh   	GroupName)r   list_group_policiesr(   s     r   r)   zGroupPolicy._listW  s    {{...NNr   c                 >    | j                   j                  d||      S NT)rh   r   rn   )r   get_group_policyr1   s      r   r2   zGroupPolicy._getZ  s    {{++ddWb+ccr   c                 @    | j                   j                  d|||      S )NT)rh   r   rn   r4   )r   put_group_policyr6   s       r   r8   zGroupPolicy._put]  s(    {{++d{S] , 
 	
r   c                 >    | j                   j                  d||      S r   )r   delete_group_policyr1   s      r   r@   zGroupPolicy._deleteb  s    {{..Ze.ffr   Nrw   r   r   r   r   r   R  s+     Od

gr   r   c                     t        t        dg d      t        dddg      t        d      t        d      t        dd d	
      t        dd	d	
            } dg}t        | |d      }t        |j                  dt        j                               |j
                  j                  d      |j
                  j                  d      |j
                  j                  d      |j
                  j                  d      |j
                  j                  d      |j                        }|j
                  j                  d      }	 |dk(  rt        di |}n!|dk(  rt        di |}n|dk(  rt        di |} |j                  di j                          y # t        t        f$ r}|j                  |       Y d }~y d }~wt         $ r%}|j#                  t%        |             Y d }~y d }~ww xY w)NT)re   r   r|   )requiredchoicesrX   rY   )defaultr   )r   r<   F)typer   r   bool)iam_typer   iam_namer   r   r   )r   rX   )r   T)argument_specrequired_ifsupports_check_modeiam)retry_decoratorr   r   r   r   r   )r   r   r   r   r   r   r   r   re   r|   r   )msgr   )r_   r   r   r	   jittered_backoffparamsr-   r   rc   rz   r   	exit_jsonr`   r   r   fail_json_awsr   	fail_jsonrH   )r   r   moduleargsr   policyrI   s          r   mainr   f  s   t-FG9y(.CDt$$'fdUC&%%HM 	5K M{hlmF}}UH4M4M4O}P]]z*MM%%m4MM%%m4))*;<mm($$D }}  ,H%v'$'F'$'F  (4(F*FJJL*;'  Q %SV$$%s%   AF G*#F99G*G%%G*__main__)DOCUMENTATIONEXAMPLESRETURNr<   botocore.exceptionsr   r   ImportErroransible.module_utils.sixr   <ansible_collections.amazon.aws.plugins.module_utils.botocorer   ;ansible_collections.amazon.aws.plugins.module_utils.modulesr   :ansible_collections.amazon.aws.plugins.module_utils.policyr   ;ansible_collections.amazon.aws.plugins.module_utils.retriesr	   	Exceptionr   r   rc   rz   r   r   r   r   r   r   <module>r      s   3j D=
~ 	1/ 2 \ X W P	) 	v
 v
re e(e e(g& g(&%R zF [  		s   A= =BB