
    Vh00                         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mZ d dlmZ d dlmZmZmZmZmZmZ d	 Zd
 Zd Zd Zd Zedk(  r e        yy)    )absolute_importdivisionprint_functionat	  
---
module: mongodb_role
short_description: Adds or removes a role from a MongoDB database
description:
    - Adds or removes a role from a MongoDB database.
    - For further information on the required format for       the privileges, authenticationRestriction or roles       parameters, see the MongoDB Documentation https://www.mongodb.com/docs/manual/reference/command/createRole/
version_added: "1.5.0"

extends_documentation_fragment:
  - community.mongodb.login_options
  - community.mongodb.ssl_options

options:
  replica_set:
    description:
      - Replica set to connect to (automatically connects to primary for writes).
    type: str
  database:
    description:
      - The name of the database to add/remove the role from.
    required: true
    type: str
    aliases: [db]
  name:
    description:
      - The name of the role to add or remove.
    required: true
    aliases: [user]
    type: str
  privileges:
    type: list
    elements: raw
    description:
      - >
        The privileges to grant the role. A privilege consists of a resource
        and permitted actions.
    default: []
  authenticationRestrictions:
    type: list
    elements: raw
    description:
      - >
          The authentication restrictions the server enforces on the role.
          Specifies a list of IP addresses and CIDR ranges users granted
          this role are allowed to connect to and/or which they can connect from.
          Provide a list of dictionaries with the following
          fields: clientSource (list), serverAddress (list).
          Provide an empty list if you don't want to use the field.
    default: []
  roles:
    type: list
    elements: raw
    description:
      - >
          The database user roles should be provided as a dictionary with the db and role keys.
    default: []
  state:
    description:
      - The database user state.
    default: present
    choices: [absent, present]
    type: str
  debug:
    description:
      - Enable extra debugging output.
    default: false
    type: bool
notes:
    - Requires the pymongo Python package on the remote host, version 4+. This
      can be installed using pip or the OS package manager. Newer mongo server versions require newer
      pymongo versions. @see https://www.mongodb.com/docs/languages/python/pymongo-driver/current/compatibility/
requirements:
  - "pymongo"
author:
    - "Rhys Campbell (@rhysmeister)"
a  
- name: Create sales role
  community.mongodb.mongodb_role:
    name: sales
    database: salesdb
    privileges:
      - resource:
          db: salesdb
          collection: ""
        actions:
          - find
    state: present

- name: Create ClusterAdmin Role
  community.mongodb.mongodb_role:
    name: myClusterwideAdmin
    database: admin
    privileges:
      - resource:
          cluster: true
        actions:
          - addShard
      - resource:
          db: config
          collection: ""
        actions:
          - find
          - update
          - insert
          - remove
      - resource:
          db: "users"
          collection: "usersCollection"
        actions:
          - update
          - insert
          - remove
      - resource:
          db: ""
          collection: ""
        actions:
          - find
    roles:
      - role: "read"
        db: "admin"
    state: present

- name: Create ClusterAdmin Role with a login only from 127.0.0.1 restriction
  community.mongodb.mongodb_role:
    name: myClusterwideAdmin
    database: admin
    privileges:
      - resource:
          cluster: true
        actions:
          - addShard
      - resource:
          db: config
          collection: ""
        actions:
          - find
          - update
          - insert
      - resource:
          db: "users"
          collection: "usersCollection"
        actions:
          - update
          - insert
          - remove
      - resource:
          db: ""
          collection: ""
        actions:
          - find
    roles:
      - role: "read"
        db: "admin"
      - role: "read"
        db: "mynewdb"
    authenticationRestrictions:
      - clientSource:
          - "127.0.0.1"
        serverAddress: []
    state: present

- name: Delete sales role
  community.mongodb.mongodb_role:
    name: sales
    database: "salesdb"
    state: absent

- name: Delete myClusterwideAdmin role
  community.mongodb.mongodb_role:
    name: myClusterwideAdmin
    database: admin
    state: absent
zc
user:
    description: The name of the role to add or remove.
    returned: success
    type: str
N)AnsibleModulemissing_required_lib)	to_native)r   mongodb_common_argument_spec
mongo_authPYMONGO_IMP_ERRpymongo_foundget_mongodb_clientc                     	 d}dddd}| |   j                  |      d   D ]   }|d   |k(  sd|vr|c S |d   |dfv s|c S  	 y# t        $ r'}t        |d	      r|j                  d
k(  rn Y d}~yd}~ww xY w)zCheck if the role exists.

    Args:
        client (cursor): Mongodb cursor on admin database.
        user (str): Role to check.
        db_name (str): Role's database.

    Returns:
        dict: when role exists, False otherwise.
    N   T)	rolesInfoshowAuthenticationRestrictionsshowPrivilegesrolesroledbadmincode   F)command	Exceptionhasattrr   )clientr   db_name
mongo_rolerolesDocexceps         r/home/dcms/DCMS/lib/python3.12/site-packages/ansible_collections/community/mongodb/plugins/modules/mongodb_role.py	role_findr"      s    
.2"

 !/11(;GD 	&J&!T)z)%% d#'99%%	&   5&!ejjB&6  s,   *A A 	A A A 	A6A11A6c                     | |   }	 t        | ||      }|rd}	nd}	i }
||
d<   ||
d<   ||
d<    |j                  |	|fi |
 y # t        $ r)}t        |d      r|j                  dk(  rd}n Y d }~Zd }~ww xY w)	Nr      F
updateRole
createRole
privilegesr   authenticationRestrictions)r"   r   r   r   r   )r   r   r   r'   r   r(   r   existsr    role_add_db_command	role_dicts              r!   role_addr,      s    	B641 **I(IlIg.HI*+BJJ"D6I6+  	 5&!ejjB&6F 	s   A 	A3
A..A3c                     t        |||      }|r7| j                  r| j                  d|       ||   }|j                  d|       y | j                  d|       y )NTchangedr   dropRoleF)r"   
check_mode	exit_jsonr   )moduler   r   r   r)   r   s         r!   role_remover4     sY    vtW-FT5G_


:t$T2    c           	         t        | ||      }d}|rg }d|v r|d   D ]  }	|j                  |	d           d|v rH|d   D 
cg c]  }
|
d   t        |
d         d c}
|D 
cg c]  }
|
d   t        |
d         d c}
k7  s	d|vr	|g k7  rd}|S d	|v r t        |d	   d
       t        |d       k7  s	d	|vr	|g k7  rd}|S d|v rt        |d       t        |d       k7  s	d|vr|g k7  rd}|S t        d      c c}
w c c}
w )NFr(   r   r'   resourceactions)r7   r8   Tr   c                     | d   | d   fS Nr   r    xs    r!   <lambda>z'check_if_role_changed.<locals>.<lambda>-  s    !D'1V99M r5   )keyc                     | d   | d   fS r:   r;   r<   s    r!   r>   z'check_if_role_changed.<locals>.<lambda>.  s    QtWai,@ r5   c                 J    | j                  dd      | j                  dd      fS NclientSource serverAddressgetr<   s    r!   r>   z'check_if_role_changed.<locals>.<lambda>2  s0    155Q_acKdfgfkfkl{}  gA  KB r5   c                 J    | j                  dd      | j                  dd      fS rB   rF   r<   s    r!   r>   z'check_if_role_changed.<locals>.<lambda>3  s'    !%%XZB[]^]b]bcrtv]wAx r5   zRole not found)r"   appendsortedr   )r   r   r   r'   r(   r   r+   r/   #reformat_authenticationRestrictionsitemds              r!   check_if_role_changedrN     sh   &$0IG.0+'94!">? D3::47CDI%W`amWnoRSa
mq|8LMoWabRSa
mq|8LMbcI-*2BG N "y)/MNu"@ABy(Ub[G N +i7:  AB  C17xyz,I=B\`bBbG N ()) pbs   C9"C>c                  <   t               } | j                  t        d       t        ddg      t        ddg      t        g dd      t        g dd      t        g dd      t        d	d
d	g      t        dd             t        | d      }t        s |j                  t        d      t               	 d}|j                  d   d}t        ||      }t        |||      }d }|j                  d   x}}|j                  d   }|j                  d   }|j                  d   }	|j                  d   }
|j                  d   }|j                  d   }	 |d	k(  rdt        ||      du r!|j                  du rt        ||||	|
|       d}ngt!        ||||	||
      r!|j                  du rt        ||||	|
|       d}n6d}n3|d
k(  r.t        ||      r|j                  du rt#        ||||       d}nd}|j%                  ||       y # t        $ r)}|j                  dt        |      z         Y d }~Kd }~ww xY w# t        $ r[}|r/|j                  t'        |      t)        j*                                n |j                  t'        |             Y d }~y Y d }~y d }~ww xY w) N)defaultTr   )requiredaliasesuserlistraw)rP   typeelementspresentabsent)rP   choicesboolF)rV   rP   )replica_setdatabasenamer'   r(   r   statedebug)argument_specsupports_check_modepymongo)msg	exceptionr\   )directConnectionz!Unable to connect to database: %s)rd   r^   r_   r]   r'   r   r(   r`   r.   )rd   	traceback)r	   updatedictr   r   	fail_jsonr   r   paramsr   r
   r   r   r"   r1   r,   rN   r4   r2   strrg   
format_exc)ra   r3   rf   r   er/   r   r_   r   r'   r   r(   r`   s                r!   mainro   ?  s   02M&tdV44&2%@#'%#P2FU;9x.CD.  	 # F
 1)<#2 	 	4Q =='/##F=MNFF=MN G==((D5MM'"EmmJ'G|,JMM'"E!'/K!LMM'"E)Iw/58$$-VWdJGab(w
Lfhmn((E1 $
EKef"G#Ghw/$$->t4A  Q@9Q<OPPQB  )Q93G3G3IJQ(( K)s2   6.H B/H7 	H4H//H47	J AJJ__main__)
__future__r   r   r   rV   __metaclass__DOCUMENTATIONEXAMPLESRETURNrg   ansible.module_utils.basicr   r   ansible.module_utils._textr   Iansible_collections.community.mongodb.plugins.module_utils.mongodb_commonr	   r
   r   r   r   r"   r,   r4   rN   ro   __name__r;   r5   r!   <module>rz      su    A @N`aF
  K 0  F7:3@@)F zF r5   