
    Vh3                         d dl mZmZmZ dZdZdZd dlmZ d dl	Z	e
Zd dlmZmZ d dlmZmZmZmZmZ d	 Zed
k(  r e        yy)    )absolute_importdivisionprint_functiona  
---
module: mongodb_shell
author: Rhys Campbell (@rhysmeister)
version_added: "1.1.0"
short_description: Run commands via the MongoDB shell.
requirements:
  - mongosh
description:
    - Run commands via the MongoDB shell.
    - Commands provided with the eval parameter or included in a Javascript file.
    - Attempts to parse returned data into a format that Ansible can use.
    - Module uses the mongosh shell by default.
    - Support for mongo is depreciated.

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

options:
  mongo_cmd:
    description:
      - The MongoDB shell command.
      - auto - Automatically detect which MongoDB shell command used. Use "mongosh" if available, else use "mongo" command.
      - mongo - This should still work for most cases but you might have problems with json parsinf. Use transform_type of 'raw' is you encounter problems.
    type: str
    default: "mongosh"
  db:
    description:
      - The database to run commands against
    type: str
    required: false
    default: "test"
  file:
    description:
      - Path to a file containing MongoDB commands.
    type: str
  eval:
    description:
      - A MongoDB command to run.
    type: str
  nodb:
    description:
      - Specify a non-default encoding for output.
    type: bool
    default: false
  norc:
    description:
      - Prevents the shell from sourcing and evaluating ~/.mongorc.js on start up.
    type: bool
    default: false
  quiet:
    description:
      - Silences output from the shell during the connection process..
    type: bool
    default: true
  debug:
    description:
      - show additional debug info.
    type: bool
    default: false
  transform:
    description:
      - Transform the output returned to the user.
      - auto - Attempt to automatically decide the best tranformation.
      - split - Split output on a character.
      - json - parse as json.
      - raw - Return the raw output.
    type: str
    choices:
      - "auto"
      - "split"
      - "json"
      - "raw"
    default: "auto"
  split_char:
    description:
      - Used by the split action in the transform stage.
    type: str
    default: " "
  stringify:
    description:
      - Wraps the command in eval in JSON.stringify(<js cmd>) (mongo) or EJSON.stringify(<js cmd>) (mongosh).
      - Useful for escaping documents that are returned in Extended JSON format.
      - Automatically set to false when using mongo.
      - Automatically set to true when using mongosh.
      - Set explicitly to override automatic selection.
    type: bool
    default: null
  additional_args:
    description:
      - Additional arguments to supply to the mongo command.
      - Supply as key-value pairs.
      - If the parameter is a valueless flag supply an empty string as the value.
    type: raw
  idempotent:
    description:
      - Provides a form of pseudo-idempotency to the module.
      - We perform a hash calculation on the contents of the eval key or the file name provided in the file key.
      - When the command is first execute a filed called <hash>.success will be created.
      - The module will not rerun the command if this file exists and idempotent is set to true.
    type: bool
    default: false
  omit:
    description:
      - Parameter to omit from the command line.
      - This should match the parameter name that the MongoDB shell accepts not the module name.
    type: list
    elements: str
    default: []
a  
- name: Run the listDatabases command
  community.mongodb.mongodb_shell:
    login_user: user
    login_password: secret
    eval: "db.adminCommand('listDatabases')"

- name: List collections and stringify the output
  community.mongodb.mongodb_shell:
    login_user: user
    login_password: secret
    eval: "db.adminCommand('listCollections')"
    stringify: yes

- name: Run the showBuiltinRoles command
  community.mongodb.mongodb_shell:
    login_user: user
    login_password: secret
    eval: "db.getRoles({showBuiltinRoles: true})"

- name: Run a js file containing MongoDB commands with pseudo-idempotency
  community.mongodb.mongodb_shell:
    login_user: user
    login_password: secret
    file: "/path/to/mongo/file.js"
    idempotent: yes

- name: Provide a couple of additional cmd args
  community.mongodb.mongodb_shell:
    login_user: user
    login_password: secret
    eval: "db.adminCommand('listDatabases')"
    additional_args:
      verbose: True
      networkMessageCompressors: "snappy"
a  
file:
  description: JS file that was executed successfully.
  returned: When a js file is used.
  type: str
msg:
  description: A message indicating what has happened.
  returned: always
  type: str
transformed_output:
  description: Output from the mongo command. We attempt to parse this into a list or json where possible.
  returned: on success
  type: list
changed:
  description: Change status.
  returned: always
  type: bool
failed:
  description: Something went wrong.
  returned: on failure
  type: bool
out:
  description: Raw stdout from mongo.
  returned: when debug is set to true
  type: str
err:
  description: Raw stderr from mongo.
  returned: when debug is set to true
  type: str
rc:
  description: Return code from mongo.
  returned: when debug is set to true
  type: int
)AnsibleModuleN)load_mongocnfmongodb_common_argument_spec)add_arg_to_cmdtransform_outputget_hash_valuetouchdetect_if_cmd_existc                     t        d      } | j                  t        dd      t        dd      t        dd      t        ddd	      t        d
dd	      t        d
dd	      t        d
dd	      t        d
dd	      t        dg dd      t        dd      t        d
d       t        d      t        d
d      t        ddg              t        | dddggddgg      }|j                  d   dk(  rt               rdnd|j                  d<   |j                  d   dk(  r|j                  d   d|j                  d<   n0|j                  d   dk(  r|j                  d   d|j                  d<   |j                  d   |j                  d   g}t        |      }|j                  d   rPt        j                  j                  dj                  |            r"|j                  ddj                  |              |j                  d   s|j                  d   j                  d!      rd"}|j                  |#       |j                  d   ri|j                  d   dk7  r,d$j                  |j                  d         |j                  d<   n+d%j                  |j                  d         |j                  d<   |j                  d&   }|j                  d   }|j                  d   }t               }|r|s|d'   }|s|d(   }d)}	|j                  d*   rd+}	|j                  d*   D ]  }
t        |
t              r.|
j!                         D ]  \  }}|	d,j                  ||      z  }	 At        |
t"              rd-|
v r|	d.j                  |
      z  }	jt%        d/j                  t#        |
                   |d0   }|	d d1 }	d2j                  |j                  d3   |j                  d4   ||	      |d0<   n8t'        |d5|j                  d3   |6      }t'        |d7|j                  d4   |6      }t'        |d8||6      }t'        |d9||6      }t'        |d:|j                  d;   |6      }t'        |d<|j                  d=   |6      }t'        |d>|j                  d   |6      }t'        |d?d |j                  d@   |6      }t'        |dAd |j                  dB   |6      }t'        |dCd |j                  dD   |6      }t'        |dEd |j                  dF   |6      }t'        |dGd |j                  dH   dIv |6      }t'        |dJ|j                  dK   |6      }t'        |dL|j                  dM   |6      }t'        |dN|j                  dO   |6      }t'        |dP|j                  dQ   |6      }|j                  dR   }||j!                         D ]x  \  }}t        |t(              r!|j+                  dSj                  |             7t        |t"              st        |t,              sX|j+                  dTj                  ||             z |j                  d   r|j+                  |j                  d          d }d)}d)}i }dj/                  dU |D              }|j1                  |dV      \  }}}|j                  dW   r||dX<   ||dY<   ||dZ<   ||d[<   |d\k7  r,||d)k(  r|} |j                  ddd]|j3                         i| nd|d^<   |j                  d   rt5        dj                  |             	 t7        ||j                  d_   |j                  d`         }||da<   dbj                  |j                  d_         |d]<   |j                  d   |j                  d   |d<    |j                  ddi | y # t8        $ r,}dcj                  t#        |            |d]<   d |da<   Y d }~Cd }~ww xY w)eNT)ssl_optionsstrmongosh)typedefaultF)r   requiredtest)r   r   r   bool)autosplitjsonrawr   )r   choicesr    r   )r   list)r   elementsr   )	mongo_cmdfileevaldbnodbnorcquietdebug	transform
split_char	stringifyadditional_args
idempotentomit
login_userlogin_passwordr!   r    )argument_specsupports_check_moderequired_togethermutually_exclusiver   mongor)   r"   r+   z{0}.successzkThe file {0}.success was found meaning this command has already successfully executed on this MongoDB host.)changedmsgzshow zYou cannot use any shell helper (e.g. use <dbname>, show dbs, etc.) inside the eval parameter because they are not valid JavaScript.)r5   zJSON.stringify({0})zEJSON.stringify({0})r,   userpassword connection_options?z{0}={1}&=z{0}&z3Invalid value supplied in connection_options: {0} .   zmongodb://{0}:{1}/{2}{3}
login_host
login_portz--host)r,   z--portz
--usernamez
--passwordz--authenticationDatabaselogin_databasez--authenticationMechanismauth_mechanismz--evalz--nodbr#   z--norcr$   z--quietr%   z--tlssslz--tlsAllowInvalidCertificatesssl_cert_reqs)	CERT_NONECERT_OPTIONALz--tlsCAFilessl_ca_certsz--tlsCRLFilessl_crlfilez--tlsCertificateKeyFilessl_keyfilez--tlsCertificateKeyFilePasswordssl_pem_passphraser*   z --{0}z
 --{0} {1}c              3   2   K   | ]  }t        |        y w)N)r   ).0items     s/home/dcms/DCMS/lib/python3.12/site-packages/ansible_collections/community/mongodb/plugins/modules/mongodb_shell.py	<genexpr>zmain.<locals>.<genexpr>N  s     .3t9.s   )check_rcr&   outerrrccmdr   r5   r4   r'   r(   transformed_outputztransform type was {0}zError tranforming output: {0} )r   updatedictr   paramsr   r   ospathisfileformat	exit_json
startswith	fail_jsonr   
isinstanceitemsr   
ValueErrorr	   r   appendintjoinrun_commandstripr   r
   	Exception)r/   moduleargs
hash_valuer5   r,   usernamer7   credentialstmp_con_optionsrL   keyvaluetmp_dbr*   rR   rP   rQ   resultrS   outputexceps                         rM   mainru      s   0TBME95uu-uu-UUF;vu=vu==>E+KU[\UC0FD1%(VU3vr:    #!(*:;<#V,-	F }}[!V+2E2GYWk"}}[!W,{1K1S%*k"	{	#y	0V]];5O5W%)k" 	k"dD
  'J}}\"77>>-..z:;U"55;VJ5G  I
 == == ++G4VC%==%}}[)Y6(=(D(DV]]SYEZ([f%(>(E(EfmmTZF[(\f%== D}}\*H}}-.H/K"6*H":.HO}})*MM"67 	jD$%"&**, EJC#z'8'8e'DDOED#&3$;6==#66 !V!]!]^abf^g!hii	j a)#2.,33FMM,4O4:MM,4O4:4CEQ
 dHfmmL.IPTUdHfmmL.IPTU$hTBD$hTBD$ :FMMJZ<[bfgD$ ;V]]K[=\cghD$&--*?dKD$$f0EDQD$$f0EDQD$	4w1GdSD$v}}U/C$OD$ ?v}}UdGe  jH  HH  OS  TD$v}}^/LSWXD$m0LSWXD$ 96==;W^bcD$ A6==QeCfmqrDmm$56O")//1 	=JC%&HOOC01E3':eS+AL//U;<		=
 }}VFMM&)*	B
C
CF
((..
.C''e'<NRc}}Wuutu	Qw;#)C3SYY[3F3 y==&-&&z23
	0%c&,mmK&@&,mmL&ACF ,2F'(4;;FMM+<VWF5M}}V$0!'v!6v
 Fv	  	0;BB3u:NF5M+/F'(	0s   A.^ 	_"____main__)
__future__r   r   r   DOCUMENTATIONEXAMPLESRETURNansible.module_utils.basicr   rY   r   __metaclass__Iansible_collections.community.mongodb.plugins.module_utils.mongodb_commonr   r   Hansible_collections.community.mongodb.plugins.module_utils.mongodb_shellr	   r
   r   r   r   ru   __name__rU       rM   <module>r      s^    A @n`#J!
F 5 	 Yx zF r   