Debian Codegraph @

lib/ansible/plugins/lookup/fileglob.py

raw
1 # (c) 2012, Michael DeHaan <[email protected]>
2 # (c) 2017 Ansible Project
3 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
4 from __future__ import annotations
5
6 DOCUMENTATION = """
7 name: fileglob
8 author: Michael DeHaan
9 version_added: "1.4"
10 short_description: list files matching a pattern
11 description:
12 - Matches all files in a single directory, non-recursively, that match a pattern.
13 It calls Python's "glob" library.
14 positional: _terms
15 options:
16 _terms:
17 description: path(s) of files to read
18 required: True
19 notes:
20 - Patterns are only supported on files, not directory/paths.
21 - See R(Ansible task paths,playbook_task_paths) to understand how file lookup occurs with paths.
22 - Matching is against local system files on the Ansible controller.
23 To iterate a list of files on a remote node, use the M(ansible.builtin.find) module.
24 - Returns a string list of paths joined by commas, or an empty list if no files match. For a 'true list' pass O(ignore:wantlist=True) to the lookup.
25 seealso:
26 - ref: playbook_task_paths
27 description: Search paths used for relative files.
28 """
29
30 EXAMPLES = """
31 - name: Display paths of all .txt files in dir
32 ansible.builtin.debug: msg={{ lookup('ansible.builtin.fileglob', '/my/path/*.txt') }}
33
34 - name: Copy each file over that matches the given pattern
35 ansible.builtin.copy:
36 src: "{{ item }}"
37 dest: "/etc/fooapp/"
38 owner: "root"
39 mode: 0600
40 with_fileglob:
41 - "/playbooks/files/fooapp/*"
42 """
43
44 RETURN = """
45 _list:
46 description:
47 - list of files
48 type: list
49 elements: path
50 """
51
52 import os
53 import glob
54
55 from ansible.plugins.lookup import LookupBase
56 from ansible.module_utils.common.text.converters import to_bytes, to_text
57
58
59 class LookupModule(LookupBase):
60
61 def run(self, terms, variables=None, **kwargs):
62
63 ret = []
64 for term in terms:
65 term_file = os.path.basename(term)
66 found_paths = []
67 if term_file != term:
68 found_paths.append(self.find_file_in_search_path(variables, 'files', os.path.dirname(term)))
69 else:
70 # no dir, just file, so use paths and 'files' paths instead
71 if 'ansible_search_path' in variables:
72 paths = variables['ansible_search_path']
73 else:
74 paths = [self.get_basedir(variables)]
75 for p in paths:
76 found_paths.append(os.path.join(p, 'files'))
77 found_paths.append(p)
78
79 for dwimmed_path in found_paths:
80 if dwimmed_path:
81 globbed = glob.glob(to_bytes(os.path.join(dwimmed_path, term_file), errors='surrogate_or_strict'))
82 term_results = [to_text(g, errors='surrogate_or_strict') for g in globbed if os.path.isfile(g)]
83 if term_results:
84 ret.extend(term_results)
85 break
86 return ret