o nnhW@sddlmZdZdZdZddlZddlZddlZddlZddl Z ddl Z ddl Z ddl Z ddl mZmZddlmZddlmZGd d d Zdd d ZddZddZdddZddZddZddZedkrnedSdS)) annotationsaO --- module: find author: Brian Coca (@bcoca) version_added: "2.0" short_description: Return a list of files based on specific criteria description: - Return a list of files based on specific criteria. Multiple criteria are AND'd together. - For Windows targets, use the M(ansible.windows.win_find) module instead. - This module does not use the C(find) command, it is a much simpler and slower Python implementation. It is intended for small and simple uses. Those that need the extra power or speed and have expertise with the UNIX command, should use it directly. options: age: description: - Select files whose age is equal to or greater than the specified time. - Use a negative age to find files equal to or less than the specified time. - You can choose seconds, minutes, hours, days, or weeks by specifying the first letter of any of those words (e.g., "1w"). type: str patterns: default: [] description: - One or more (shell or regex) patterns, which type is controlled by O(use_regex) option. - The patterns restrict the list of files to be returned to those whose basenames match at least one of the patterns specified. Multiple patterns can be specified using a list. - The pattern is matched against the file base name, excluding the directory. - When using regexen, the pattern MUST match the ENTIRE file name, not just parts of it. So if you are looking to match all files ending in .default, you'd need to use C(.*\.default) as a regexp and not just C(\.default). - This parameter expects a list, which can be either comma separated or YAML. If any of the patterns contain a comma, make sure to put them in a list to avoid splitting the patterns in undesirable ways. - Defaults to V(*) when O(use_regex=False), or V(.*) when O(use_regex=True). type: list aliases: [ pattern ] elements: str excludes: description: - One or more (shell or regex) patterns, which type is controlled by O(use_regex) option. - Items whose basenames match an O(excludes) pattern are culled from O(patterns) matches. Multiple patterns can be specified using a list. type: list aliases: [ exclude ] version_added: "2.5" elements: str contains: description: - A regular expression or pattern which should be matched against the file content. - If O(read_whole_file) is V(false) it matches against the beginning of the line (uses V(re.match(\))). If O(read_whole_file) is V(true), it searches anywhere for that pattern (uses V(re.search(\))). - Works only when O(file_type) is V(file). type: str read_whole_file: description: - When doing a C(contains) search, determines whether the whole file should be read into memory or if the regex should be applied to the file line-by-line. - Setting this to C(true) can have performance and memory implications for large files. - This uses V(re.search(\)) instead of V(re.match(\)). type: bool default: false version_added: "2.11" paths: description: - List of paths of directories to search. All paths must be fully qualified. type: list required: true aliases: [ name, path ] elements: str file_type: description: - Type of file to select. - The 'link' and 'any' choices were added in Ansible 2.3. type: str choices: [ any, directory, file, link ] default: file recurse: description: - If target is a directory, recursively descend into the directory looking for files. type: bool default: no size: description: - Select files whose size is equal to or greater than the specified size. - Use a negative size to find files equal to or less than the specified size. - Unqualified values are in bytes but b, k, m, g, and t can be appended to specify bytes, kilobytes, megabytes, gigabytes, and terabytes, respectively. - Size is not evaluated for directories. type: str age_stamp: description: - Choose the file property against which we compare age. type: str choices: [ atime, ctime, mtime ] default: mtime hidden: description: - Set this to V(true) to include hidden files, otherwise they will be ignored. type: bool default: no mode: description: - Choose objects matching a specified permission. This value is restricted to modes that can be applied using the python C(os.chmod) function. - The mode can be provided as an octal such as V("0644") or as symbolic such as V(u=rw,g=r,o=r) type: raw version_added: '2.16' exact_mode: description: - Restrict mode matching to exact matches only, and not as a minimum set of permissions to match. type: bool default: true version_added: '2.16' follow: description: - Set this to V(true) to follow symlinks in path for systems with python 2.6+. type: bool default: no get_checksum: description: - Set this to V(true) to retrieve a file's SHA1 checksum. type: bool default: no use_regex: description: - If V(false), the patterns are file globs (shell). - If V(true), they are python regexes. type: bool default: no depth: description: - Set the maximum number of levels to descend into. - Setting recurse to V(false) will override this value, which is effectively depth 1. - Default is unlimited depth. type: int version_added: "2.6" encoding: description: - When doing a C(contains) search, determine the encoding of the files to be searched. type: str version_added: "2.17" extends_documentation_fragment: action_common_attributes attributes: check_mode: details: since this action does not modify the target it just executes normally during check mode support: full diff_mode: support: none platform: platforms: posix seealso: - module: ansible.windows.win_find a - name: Recursively find /tmp files older than 2 days ansible.builtin.find: paths: /tmp age: 2d recurse: yes - name: Recursively find /tmp files older than 4 weeks and equal or greater than 1 megabyte ansible.builtin.find: paths: /tmp age: 4w size: 1m recurse: yes - name: Recursively find /var/tmp files with last access time greater than 3600 seconds ansible.builtin.find: paths: /var/tmp age: 3600 age_stamp: atime recurse: yes - name: Find /var/log files equal or greater than 10 megabytes ending with .old or .log.gz ansible.builtin.find: paths: /var/log patterns: '*.old,*.log.gz' size: 10m # Note that YAML double quotes require escaping backslashes but yaml single quotes do not. - name: Find /var/log files equal or greater than 10 megabytes ending with .old or .log.gz via regex ansible.builtin.find: paths: /var/log patterns: "^.*?\\.(?:old|log\\.gz)$" size: 10m use_regex: yes - name: Find /var/log all directories, exclude nginx and mysql ansible.builtin.find: paths: /var/log recurse: no file_type: directory excludes: 'nginx,mysql' # When using patterns that contain a comma, make sure they are formatted as lists to avoid splitting the pattern - name: Use a single pattern that contains a comma formatted as a list ansible.builtin.find: paths: /var/log file_type: file use_regex: yes patterns: ['^_[0-9]{2,4}_.*.log$'] - name: Use multiple patterns that contain a comma formatted as a YAML list ansible.builtin.find: paths: /var/log file_type: file use_regex: yes patterns: - '^_[0-9]{2,4}_.*.log$' - '^[a-z]{1,5}_.*log$' a0 files: description: All matches found with the specified criteria (see stat module for full output of each dictionary) returned: success type: list sample: [ { path: "/var/tmp/test1", mode: "0644", "...": "...", checksum: 16fac7be61a6e4591a33ef4b729c5c3302307523 }, { path: "/var/tmp/test2", "...": "..." }, ] matched: description: Number of matches returned: success type: int sample: 14 examined: description: Number of filesystem objects looked at returned: success type: int sample: 34 skipped_paths: description: skipped paths and reasons they were skipped returned: success type: dict sample: {"/laskdfj": "'/laskdfj' is not a directory"} version_added: '2.12' N)to_text to_native) AnsibleModule) string_typesc@seZdZddZdS)_ObjectcKs"|D] \}}t|||qdSN)itemssetattr)selfkwargskvr?/usr/local/lib/python3.10/dist-packages/ansible/modules/find.py__init__sz_Object.__init__N)__name__ __module__ __qualname__rrrrrrs rFcCs|s|sdS|rK|r |s |D]}t|}||rdSqdS|rI|rI|D]"}t|}||rH|D]}t|}||rDdSq4dSq&dS|r_|s_|D] }t||r\dSqQdS|r|r|D]}t||r|D] }t||r{dSqodSqedS)zfilter using glob patternsTF)recompilematchfnmatch)fpatternsexcludes use_regexprerrrpfiltersL          r cCs\|durdS|dkr|t|d|t|krdS|dkr,|t|d|t|kr,dSdS)zfilter files older than ageNTrzst_%sF)getattrabs)stnowage timestamprrr agefilterDs""r'cCsD|durdS|dkr|jt|krdS|dkr |jt|kr dSdS)zfilter files greater than sizeNTrF)st_sizer")r#sizerrr sizefilterOsr*c Cs|durdSt|}zBt||d1}|r&t||WdWS|D]}||r9WdWdSq(WdWdS1sFwYWdSty[}z|d}~wtyy}z|durhd}d|d|}t ||d}~wt yYdSw)a Filter files which contain the given expression :arg fsname: Filename to scan for lines matching a pattern :arg pattern: Pattern to look for inside of line :arg encoding: Encoding of the file to be scanned :arg read_whole_file: If true, the whole file is read into memory before the regex is applied against it. Otherwise, the regex is applied line-by-line. :rtype: bool :returns: True if one of the lines in fsname matches the pattern. Otherwise False NT)encodingz@None (default determined by the Python built-in function "open")zFailed to read the file z- due to an encoding error. current encoding: F) rropenboolsearchreadr LookupErrorUnicodeDecodeError Exception) fsnamepatternr+read_whole_fileprogrlinermsgrrr contentfilterZs>      r9cCsj|sdSt|j}zt|d}Wnty#|tdd|}Ynwt|}|r/||kSt||@S)NTr)st_mode)statS_IMODEr;int ValueError_symbolic_mode_to_octalrr-)r#modeexactmoduler;rrr mode_filters    rDcCsd}d}z t|jj}Wn tyYnwz t|jj}Wn ty)Ynwiddt |j dt |j dt |j dt |j dt |j dt |j d t |j d t |j d |jd |jd |jd|jd|jd|jd|jd|jd|j||t|j t j@t|j t j@t|j t j@t|j t j@t|j t j@t|j t j @t|j t j!@t|j t j"@t|j t j#@t|j t j$@t|j t j%@d S)NrAz%04oisdirischrisblkisregisfifoislnkissockuidgidr)inodedevnlinkatimemtimectime) gr_namepw_namewusrrusrxusrwgrprgrpxgrpwothrothxothisuidisgid)&pwdgetpwuidst_uidrVr2grpgetgrgidst_gidrUr<r=r;S_ISDIRS_ISCHRS_ISBLKS_ISREGS_ISFIFOS_ISLNKS_ISSOCKr(st_inost_devst_nlinkst_atimest_mtimest_ctimer-S_IWUSRS_IRUSRS_IXUSRS_IWGRPS_IRGRPS_IXGRPS_IWOTHS_IROTHS_IXOTHS_ISUIDS_ISGID)r#rVrUrrrstatinfosz              rc s$ttdNidtddddgdddtdgd gdd d tdd gdd dtdddtddddtddgdddtdddtddgdddtdddtddddtddddtdddd tdddd!tdddd"td#dd$td%dd&tdddd'tdddd(}|j}|d$rt|d$ts|jd)|d$jjd*|ds|d!rd+g|d<nd,g|d<g}ifd-d.}|ddurd}n.t d/|d }d0d1d2d3d4d5}|rt | d0| | d6d0}n |j|dd7d8|ddurd}n/t d9|d }d0d:d;d}|r.t | d0| | d6d0}n |j|dd?d@t} dA} dB} d} |dD]5} tjtj| } ztj| sctdCt| tj| ||ddDD]\}}}| t|t|} ||D]}tjtj||}|d"r| tjjtjj}t |tjjt |tjjd0}||d"kr|dd=qtj|dEr|dsҐqzt|}Wn)t t!fy}z|"dF|t#|ft#||<d} WYd}~qd}~wwd|i}|ddGkrgt$||d|d |d!ret%|| ||dret&||d$|d&|re|'t(|t)*|j+rL|d rL|,||dH<t)*|j+r`t-||r^|.|q|.|qt)/|j+r|ddIkrt$||d|d |d!rt%|| ||drt&||d$|d&|r|'t(||.|qt)*|j+r|ddkrt$||d|d |d!rt%|| ||drt-||rt0||d|d'|drt&||d$|d&|r|'t(||d r|,||dH<|.|qt)1|j+rE|ddJkrEt$||d|d |d!rEt%|| ||drEt&||d$|d&|rE|'t(||.|q|dsNnqmWqEty{}zt#|| <|"dKt#| | fd} WYd}~qEd}~ww| rdL} t|}|j2|d| || dMdS)ONpathslistTnamepathstr)typerequiredaliaseselementsrr4)rdefaultrrrexclude)rrrcontains)rr5r-F)rr file_typefile)any directoryrlink)rrchoicesr% age_stamprS)rRrTrSr)recursehiddenfollow get_checksumrdepthr>rAraw exact_moder+) argument_specsupports_check_modezRargument 'mode' is not a string and conversion is not allowed, value is of type %s)r8z.**cs(|jtjtjfvrt||j<dS|r)errnoEPERMEACCESrfilename)rskippedrrhandle_walk_errorssz main..handle_walk_errorsz^(-?\d+)(s|m|h|d|w)?$<iiQi: )smhdwzfailed to process age)r%r8z^(-?\d+)(b|k|m|g|t)?$iii@l)br rgtzfailed to process size)r)r8zAll paths examinedrz'%s' is not a directory)onerror followlinks.z0Skipped entry '%s' due to this access issue: %s rchecksumrrz/Skipped '%s' path due to this access issue: %s z2Not all paths examined, check warnings for details)fileschangedr8matchedexamined skipped_pathsr)3rdictparams isinstancer fail_json __class__rrrlowerr>groupgettimeosr expanduser expandvarsrFr2rwalklennormpathjoinrstripsepcountbasename startswithlstatIOErrorOSErrorwarnrr r'rDupdaterr<rkr;sha1r*appendrhr9rm exit_json)rCrfilelistrr%rseconds_per_unitr)bytes_per_unitr$r8looked has_warningsnpathrootdirsrfsobjr3wpathrr#rrrrrrmains>                 ""  (           r__main__)NNF)F) __future__r DOCUMENTATIONEXAMPLESRETURNrrrerrbrr<r+ansible.module_utils.common.text.convertersrransible.module_utils.basicransible.module_utils.sixrrr r'r*r9rDrrrrrrrs8  =!   ' %0#