| 1 |
# Copyright (c) 2016 Dag Wieers <[email protected]> |
| 2 |
# Copyright (c) 2017 Ansible Project |
| 3 |
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 4 |
# SPDX-License-Identifier: GPL-3.0-or-later |
| 5 |
from __future__ import annotations |
| 6 |
|
| 7 |
DOCUMENTATION = r""" |
| 8 |
name: filetree |
| 9 |
author: Dag Wieers (@dagwieers) <[email protected]> |
| 10 |
short_description: Recursively match all files in a directory tree |
| 11 |
description: |
| 12 |
- This lookup enables you to template a complete tree of files on a target system while retaining permissions and ownership. |
| 13 |
- Supports directories, files and symlinks, including SELinux and other file properties. |
| 14 |
- If you provide more than one path, it implements a first_found logic, and does not process entries it already processed |
| 15 |
in previous paths. This enables merging different trees in order of importance, or add role_vars to specific paths to |
| 16 |
influence different instances of the same role. |
| 17 |
options: |
| 18 |
_terms: |
| 19 |
description: Path(s) of files to read. |
| 20 |
required: true |
| 21 |
type: list |
| 22 |
elements: string |
| 23 |
exclude: |
| 24 |
description: |
| 25 |
- A regular expression string to exclude files. Applies to the base name of the file or directory. |
| 26 |
type: str |
| 27 |
version_added: 12.0.0 |
| 28 |
""" |
| 29 |
|
| 30 |
EXAMPLES = r""" |
| 31 |
- name: Create directories |
| 32 |
ansible.builtin.file: |
| 33 |
path: /web/{{ item.path }} |
| 34 |
state: directory |
| 35 |
mode: '{{ item.mode }}' |
| 36 |
with_community.general.filetree: web/ |
| 37 |
when: item.state == 'directory' |
| 38 |
|
| 39 |
- name: Template files (explicitly skip directories in order to use the 'src' attribute) |
| 40 |
ansible.builtin.template: |
| 41 |
src: '{{ item.src }}' |
| 42 |
# Your template files should be stored with a .j2 file extension, |
| 43 |
# but should not be deployed with it. splitext|first removes it. |
| 44 |
dest: /web/{{ item.path | splitext | first }} |
| 45 |
mode: '{{ item.mode }}' |
| 46 |
with_community.general.filetree: web/ |
| 47 |
when: item.state == 'file' |
| 48 |
|
| 49 |
- name: Recreate symlinks |
| 50 |
ansible.builtin.file: |
| 51 |
src: '{{ item.src }}' |
| 52 |
dest: /web/{{ item.path }} |
| 53 |
state: link |
| 54 |
follow: false # avoid corrupting target files if the link already exists |
| 55 |
force: true |
| 56 |
mode: '{{ item.mode }}' |
| 57 |
with_community.general.filetree: web/ |
| 58 |
when: item.state == 'link' |
| 59 |
|
| 60 |
- name: list all files under web/ |
| 61 |
ansible.builtin.debug: |
| 62 |
msg: "{{ lookup('community.general.filetree', 'web/') }}" |
| 63 |
|
| 64 |
- name: list all files under web/; exclude .git and .node_modules |
| 65 |
ansible.builtin.debug: |
| 66 |
msg: >- |
| 67 |
{{ lookup('community.general.filetree', 'web/', exclude='^(\.git|\.node_modules)$') }} |
| 68 |
""" |
| 69 |
|
| 70 |
RETURN = r""" |
| 71 |
_raw: |
| 72 |
description: List of dictionaries with file information. |
| 73 |
type: list |
| 74 |
elements: dict |
| 75 |
contains: |
| 76 |
src: |
| 77 |
description: |
| 78 |
- Full path to file. |
| 79 |
- Not returned when RV(_raw[].state) is set to V(directory). |
| 80 |
type: path |
| 81 |
root: |
| 82 |
description: Allows filtering by original location. |
| 83 |
type: path |
| 84 |
path: |
| 85 |
description: Contains the relative path to root. |
| 86 |
type: path |
| 87 |
mode: |
| 88 |
description: The permissions the resulting file or directory. |
| 89 |
type: str |
| 90 |
state: |
| 91 |
description: |
| 92 |
- Type of the resulting file or directory. |
| 93 |
- V(directory) for a directory, V(file) for a regular file, V(link) for a symbolic link. |
| 94 |
- Other file types are skipped and not returned. |
| 95 |
type: str |
| 96 |
choices: [directory, file, link] |
| 97 |
owner: |
| 98 |
description: Name of the user that owns the file/directory. |
| 99 |
type: raw |
| 100 |
group: |
| 101 |
description: Name of the group that owns the file/directory. |
| 102 |
type: raw |
| 103 |
seuser: |
| 104 |
description: The user part of the SELinux file context. |
| 105 |
type: raw |
| 106 |
serole: |
| 107 |
description: The role part of the SELinux file context. |
| 108 |
type: raw |
| 109 |
setype: |
| 110 |
description: The type part of the SELinux file context. |
| 111 |
type: raw |
| 112 |
selevel: |
| 113 |
description: The level part of the SELinux file context. |
| 114 |
type: raw |
| 115 |
uid: |
| 116 |
description: Owner ID of the file/directory. |
| 117 |
type: int |
| 118 |
gid: |
| 119 |
description: Group ID of the file/directory. |
| 120 |
type: int |
| 121 |
size: |
| 122 |
description: Size of the target. |
| 123 |
type: int |
| 124 |
mtime: |
| 125 |
description: Time of last modification. |
| 126 |
type: float |
| 127 |
ctime: |
| 128 |
description: Time of last metadata update or creation (depends on OS). |
| 129 |
type: float |
| 130 |
""" |
| 131 |
|
| 132 |
import grp |
| 133 |
import os |
| 134 |
import pwd |
| 135 |
import re |
| 136 |
import stat |
| 137 |
|
| 138 |
HAVE_SELINUX = False |
| 139 |
try: |
| 140 |
import selinux |
| 141 |
|
| 142 |
HAVE_SELINUX = True |
| 143 |
except ImportError: |
| 144 |
pass |
| 145 |
|
| 146 |
from ansible.module_utils.common.text.converters import to_native, to_text |
| 147 |
from ansible.plugins.lookup import LookupBase |
| 148 |
from ansible.utils.display import Display |
| 149 |
|
| 150 |
from ansible_collections.community.general.plugins.plugin_utils._lookup import check_for_wrong_terms |
| 151 |
|
| 152 |
display = Display() |
| 153 |
|
| 154 |
|
| 155 |
# If selinux fails to find a default, return an array of None |
| 156 |
def selinux_context(path): |
| 157 |
context = [None, None, None, None] |
| 158 |
if HAVE_SELINUX and selinux.is_selinux_enabled(): |
| 159 |
try: |
| 160 |
# note: the selinux module uses byte strings on python2 and text |
| 161 |
# strings on python3 |
| 162 |
ret = selinux.lgetfilecon_raw(to_native(path)) |
| 163 |
except OSError: |
| 164 |
return context |
| 165 |
if ret[0] != -1: |
| 166 |
# Limit split to 4 because the selevel, the last in the list, |
| 167 |
# may contain ':' characters |
| 168 |
context = ret[1].split(":", 3) |
| 169 |
return context |
| 170 |
|
| 171 |
|
| 172 |
def file_props(root, path): |
| 173 |
"""Returns dictionary with file properties, or return None on failure""" |
| 174 |
abspath = os.path.join(root, path) |
| 175 |
|
| 176 |
try: |
| 177 |
st = os.lstat(abspath) |
| 178 |
except OSError as e: |
| 179 |
display.warning(f"filetree: Error using stat() on path {abspath} ({e})") |
| 180 |
return None |
| 181 |
|
| 182 |
ret = dict(root=root, path=path) |
| 183 |
|
| 184 |
if stat.S_ISLNK(st.st_mode): |
| 185 |
ret["state"] = "link" |
| 186 |
ret["src"] = os.readlink(abspath) |
| 187 |
elif stat.S_ISDIR(st.st_mode): |
| 188 |
ret["state"] = "directory" |
| 189 |
elif stat.S_ISREG(st.st_mode): |
| 190 |
ret["state"] = "file" |
| 191 |
ret["src"] = abspath |
| 192 |
else: |
| 193 |
display.warning(f"filetree: Error file type of {abspath} is not supported") |
| 194 |
return None |
| 195 |
|
| 196 |
ret["uid"] = st.st_uid |
| 197 |
ret["gid"] = st.st_gid |
| 198 |
try: |
| 199 |
ret["owner"] = pwd.getpwuid(st.st_uid).pw_name |
| 200 |
except KeyError: |
| 201 |
ret["owner"] = st.st_uid |
| 202 |
try: |
| 203 |
ret["group"] = to_text(grp.getgrgid(st.st_gid).gr_name) |
| 204 |
except KeyError: |
| 205 |
ret["group"] = st.st_gid |
| 206 |
ret["mode"] = f"0{stat.S_IMODE(st.st_mode):03o}" |
| 207 |
ret["size"] = st.st_size |
| 208 |
ret["mtime"] = st.st_mtime |
| 209 |
ret["ctime"] = st.st_ctime |
| 210 |
|
| 211 |
if HAVE_SELINUX and selinux.is_selinux_enabled() == 1: |
| 212 |
context = selinux_context(abspath) |
| 213 |
ret["seuser"] = context[0] |
| 214 |
ret["serole"] = context[1] |
| 215 |
ret["setype"] = context[2] |
| 216 |
ret["selevel"] = context[3] |
| 217 |
|
| 218 |
return ret |
| 219 |
|
| 220 |
|
| 221 |
class LookupModule(LookupBase): |
| 222 |
def run(self, terms, variables=None, **kwargs): |
| 223 |
self.set_options(var_options=variables, direct=kwargs) |
| 224 |
check_for_wrong_terms(self, direct=kwargs) |
| 225 |
|
| 226 |
basedir = self.get_basedir(variables) |
| 227 |
|
| 228 |
# Regular expression for exclude |
| 229 |
exclude = self.get_option("exclude") |
| 230 |
exclude_pattern = re.compile(exclude) if exclude else None |
| 231 |
|
| 232 |
ret = [] |
| 233 |
for term in terms: |
| 234 |
term_file = os.path.basename(term) |
| 235 |
dwimmed_path = self._loader.path_dwim_relative(basedir, "files", os.path.dirname(term)) |
| 236 |
path = os.path.join(dwimmed_path, term_file) |
| 237 |
display.debug(f"Walking '{path}'") |
| 238 |
for root, dirs, files in os.walk(path, topdown=True): |
| 239 |
# Filter files and directories using a regular expression |
| 240 |
if exclude_pattern is not None: |
| 241 |
dirs[:] = [d for d in dirs if not exclude_pattern.match(d)] |
| 242 |
files[:] = [f for f in files if not exclude_pattern.match(f)] |
| 243 |
|
| 244 |
for entry in dirs + files: |
| 245 |
relpath = os.path.relpath(os.path.join(root, entry), path) |
| 246 |
|
| 247 |
# Skip if relpath was already processed (from another root) |
| 248 |
if relpath not in [entry["path"] for entry in ret]: |
| 249 |
props = file_props(path, relpath) |
| 250 |
if props is not None: |
| 251 |
display.debug(f" found '{os.path.join(path, relpath)}'") |
| 252 |
ret.append(props) |
| 253 |
|
| 254 |
return ret |