| 1 |
# Copyright: (c) 2016, Allen Sanabria <[email protected]> |
| 2 |
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 3 |
|
| 4 |
from __future__ import annotations |
| 5 |
|
| 6 |
from os import path, walk |
| 7 |
import re |
| 8 |
import pathlib |
| 9 |
|
| 10 |
import ansible.constants as C |
| 11 |
from ansible.errors import AnsibleError |
| 12 |
from ansible._internal._datatag._tags import SourceWasEncrypted |
| 13 |
from ansible.module_utils.common.text.converters import to_native |
| 14 |
from ansible.plugins.action import ActionBase, VariableLayer |
| 15 |
from ansible.utils.vars import combine_vars |
| 16 |
|
| 17 |
|
| 18 |
class ActionModule(ActionBase): |
| 19 |
|
| 20 |
TRANSFERS_FILES = False |
| 21 |
|
| 22 |
VALID_FILE_EXTENSIONS = ['yaml', 'yml', 'json'] |
| 23 |
VALID_DIR_ARGUMENTS = ['dir', 'depth', 'files_matching', 'ignore_files', 'extensions', 'ignore_unknown_extensions'] |
| 24 |
VALID_FILE_ARGUMENTS = ['file', '_raw_params'] |
| 25 |
VALID_ALL = ['name', 'hash_behaviour'] |
| 26 |
_requires_connection = False |
| 27 |
|
| 28 |
def _set_dir_defaults(self): |
| 29 |
if not self.depth: |
| 30 |
self.depth = 0 |
| 31 |
|
| 32 |
if self.files_matching: |
| 33 |
self.matcher = re.compile(r'{0}'.format(self.files_matching)) |
| 34 |
else: |
| 35 |
self.matcher = None |
| 36 |
|
| 37 |
if not self.ignore_files: |
| 38 |
self.ignore_files = list() |
| 39 |
|
| 40 |
if isinstance(self.ignore_files, str): |
| 41 |
self._display.deprecated( |
| 42 |
msg="Specifying 'ignore_files' as a string is deprecated.", |
| 43 |
version="2.24", |
| 44 |
help_text="Use a list of strings instead.", |
| 45 |
obj=self.ignore_files, |
| 46 |
) |
| 47 |
self.ignore_files = self.ignore_files.split() |
| 48 |
|
| 49 |
if not isinstance(self.ignore_files, list): |
| 50 |
raise AnsibleError("The 'ignore_files' option must be a list.", obj=self.ignore_files) |
| 51 |
|
| 52 |
def _set_args(self): |
| 53 |
""" Set instance variables based on the arguments that were passed """ |
| 54 |
|
| 55 |
self.hash_behaviour = self._task.args.get('hash_behaviour', None) |
| 56 |
self.return_results_as_name = self._task.args.get('name', None) |
| 57 |
self.source_dir = self._task.args.get('dir', None) |
| 58 |
self.source_file = self._task.args.get('file', None) |
| 59 |
if not self.source_dir and not self.source_file: |
| 60 |
self.source_file = self._task.args.get('_raw_params') |
| 61 |
if self.source_file: |
| 62 |
self.source_file = self.source_file.rstrip('\n') |
| 63 |
|
| 64 |
self.depth = self._task.args.get('depth', None) |
| 65 |
self.files_matching = self._task.args.get('files_matching', None) |
| 66 |
self.ignore_unknown_extensions = self._task.args.get('ignore_unknown_extensions', False) |
| 67 |
self.ignore_files = self._task.args.get('ignore_files', None) |
| 68 |
self.valid_extensions = self._task.args.get('extensions', self.VALID_FILE_EXTENSIONS) |
| 69 |
|
| 70 |
if not isinstance(self.valid_extensions, list): |
| 71 |
raise AnsibleError("The 'extensions' option must be a list.", obj=self.valid_extensions) |
| 72 |
|
| 73 |
def run(self, tmp=None, task_vars=None): |
| 74 |
""" Load yml files recursively from a directory. |
| 75 |
""" |
| 76 |
del tmp # tmp no longer has any effect |
| 77 |
|
| 78 |
if task_vars is None: |
| 79 |
task_vars = dict() |
| 80 |
|
| 81 |
self.show_content = True |
| 82 |
self.included_files = [] |
| 83 |
|
| 84 |
# Validate arguments |
| 85 |
dirs = 0 |
| 86 |
files = 0 |
| 87 |
for arg in self._task.args: |
| 88 |
if arg in self.VALID_DIR_ARGUMENTS: |
| 89 |
dirs += 1 |
| 90 |
elif arg in self.VALID_FILE_ARGUMENTS: |
| 91 |
files += 1 |
| 92 |
elif arg in self.VALID_ALL: |
| 93 |
pass |
| 94 |
else: |
| 95 |
raise AnsibleError(f'{arg} is not a valid option in include_vars', obj=arg) |
| 96 |
|
| 97 |
if dirs and files: |
| 98 |
raise AnsibleError("You are mixing file only and dir only arguments, these are incompatible", obj=self._task.args) |
| 99 |
|
| 100 |
# set internal vars from args |
| 101 |
self._set_args() |
| 102 |
|
| 103 |
results = dict() |
| 104 |
failed = False |
| 105 |
if self.source_dir: |
| 106 |
self._set_dir_defaults() |
| 107 |
self._set_root_dir() |
| 108 |
if not path.exists(self.source_dir): |
| 109 |
failed = True |
| 110 |
err_msg = f"{self.source_dir} directory does not exist" |
| 111 |
elif not path.isdir(self.source_dir): |
| 112 |
failed = True |
| 113 |
err_msg = f"{self.source_dir} is not a directory" |
| 114 |
else: |
| 115 |
for root_dir, filenames in self._traverse_dir_depth(): |
| 116 |
failed, err_msg, updated_results = self._load_files_in_dir(root_dir, filenames) |
| 117 |
if failed: |
| 118 |
break |
| 119 |
results.update(updated_results) |
| 120 |
else: |
| 121 |
try: |
| 122 |
self.source_file = self._find_needle('vars', self.source_file) |
| 123 |
failed, err_msg, updated_results = ( |
| 124 |
self._load_files(self.source_file) |
| 125 |
) |
| 126 |
if not failed: |
| 127 |
results.update(updated_results) |
| 128 |
|
| 129 |
except AnsibleError as e: |
| 130 |
failed = True |
| 131 |
err_msg = to_native(e) |
| 132 |
|
| 133 |
if self.return_results_as_name: |
| 134 |
scope = dict() |
| 135 |
scope[self.return_results_as_name] = results |
| 136 |
results = scope |
| 137 |
|
| 138 |
result = super(ActionModule, self).run(task_vars=task_vars) |
| 139 |
|
| 140 |
if failed: |
| 141 |
result['failed'] = failed |
| 142 |
result['message'] = err_msg |
| 143 |
elif self.hash_behaviour is not None and self.hash_behaviour != C.DEFAULT_HASH_BEHAVIOUR: |
| 144 |
merge_hashes = self.hash_behaviour == 'merge' |
| 145 |
existing_variables = {k: v for k, v in task_vars.items() if k in results} |
| 146 |
results = combine_vars(existing_variables, results, merge=merge_hashes) |
| 147 |
|
| 148 |
result['ansible_included_var_files'] = self.included_files |
| 149 |
self.register_host_variables(results, VariableLayer.INCLUDE_VARS) |
| 150 |
# until INJECT_FACTS_AS_VARS is removed, this prevent ansible_facts in the action result from getting added to the vars cache |
| 151 |
self.register_host_variables({}, VariableLayer.CACHEABLE_FACT) |
| 152 |
result['ansible_facts'] = results |
| 153 |
result['_ansible_no_log'] = not self.show_content |
| 154 |
|
| 155 |
return result |
| 156 |
|
| 157 |
def _set_root_dir(self): |
| 158 |
if self._task._role: |
| 159 |
if self.source_dir.split('/')[0] == 'vars': |
| 160 |
path_to_use = ( |
| 161 |
path.join(self._task._role._role_path, self.source_dir) |
| 162 |
) |
| 163 |
if path.exists(path_to_use): |
| 164 |
self.source_dir = path_to_use |
| 165 |
else: |
| 166 |
path_to_use = ( |
| 167 |
path.join( |
| 168 |
self._task._role._role_path, 'vars', self.source_dir |
| 169 |
) |
| 170 |
) |
| 171 |
self.source_dir = path_to_use |
| 172 |
else: |
| 173 |
if (origin := self._task._origin) and origin.path: # origin.path is not present for ad-hoc tasks |
| 174 |
current_dir = ( |
| 175 |
"/".join(origin.path.split('/')[:-1]) |
| 176 |
) |
| 177 |
self.source_dir = path.join(current_dir, self.source_dir) |
| 178 |
|
| 179 |
def _log_walk(self, error): |
| 180 |
self._display.vvv(f"Issue with walking through {error.filename}: {error}") |
| 181 |
|
| 182 |
def _traverse_dir_depth(self): |
| 183 |
""" Recursively iterate over a directory and sort the files in |
| 184 |
alphabetical order. Do not iterate pass the set depth. |
| 185 |
The default depth is unlimited. |
| 186 |
""" |
| 187 |
sorted_walk = list(walk(self.source_dir, onerror=self._log_walk, followlinks=True)) |
| 188 |
sorted_walk.sort(key=lambda x: x[0]) |
| 189 |
for current_root, current_dir, current_files in sorted_walk: |
| 190 |
# Depth 1 is the root, relative_to omits the root |
| 191 |
current_depth = len(pathlib.Path(current_root).relative_to(self.source_dir).parts) + 1 |
| 192 |
if self.depth != 0 and current_depth > self.depth: |
| 193 |
continue |
| 194 |
current_files.sort() |
| 195 |
yield (current_root, current_files) |
| 196 |
|
| 197 |
def _ignore_file(self, filename): |
| 198 |
""" Return True if a file matches the list of ignore_files. |
| 199 |
Args: |
| 200 |
filename (str): The filename that is being matched against. |
| 201 |
|
| 202 |
Returns: |
| 203 |
Boolean |
| 204 |
""" |
| 205 |
for file_type in self.ignore_files: |
| 206 |
try: |
| 207 |
if re.search(r'{0}$'.format(file_type), filename): |
| 208 |
return True |
| 209 |
except Exception as ex: |
| 210 |
raise AnsibleError(f'Invalid regular expression: {file_type!r}', obj=file_type) from ex |
| 211 |
return False |
| 212 |
|
| 213 |
def _is_valid_file_ext(self, source_file): |
| 214 |
""" Verify if source file has a valid extension |
| 215 |
Args: |
| 216 |
source_file (str): The full path of source file or source file. |
| 217 |
Returns: |
| 218 |
Bool |
| 219 |
""" |
| 220 |
file_ext = path.splitext(source_file) |
| 221 |
return bool(len(file_ext) > 1 and file_ext[-1][1:] in self.valid_extensions) |
| 222 |
|
| 223 |
def _load_files(self, filename, validate_extensions=False): |
| 224 |
""" Loads a file and converts the output into a valid Python dict. |
| 225 |
Args: |
| 226 |
filename (str): The source file. |
| 227 |
|
| 228 |
Returns: |
| 229 |
Tuple (bool, str, dict) |
| 230 |
""" |
| 231 |
results = dict() |
| 232 |
failed = False |
| 233 |
err_msg = '' |
| 234 |
if validate_extensions and not self._is_valid_file_ext(filename): |
| 235 |
failed = True |
| 236 |
err_msg = f"{filename!r} does not have a valid extension: {', '.join(self.valid_extensions)}" |
| 237 |
else: |
| 238 |
data = self._loader.load_from_file(filename, cache='none', trusted_as_template=True) |
| 239 |
|
| 240 |
self.show_content &= not SourceWasEncrypted.is_tagged_on(data) |
| 241 |
|
| 242 |
if data is None: # support empty files, but not falsey values |
| 243 |
data = dict() |
| 244 |
|
| 245 |
if not isinstance(data, dict): |
| 246 |
failed = True |
| 247 |
err_msg = f"{filename!r} must be stored as a dictionary/hash" |
| 248 |
else: |
| 249 |
self.included_files.append(filename) |
| 250 |
results.update(data) |
| 251 |
|
| 252 |
return failed, err_msg, results |
| 253 |
|
| 254 |
def _load_files_in_dir(self, root_dir, var_files): |
| 255 |
""" Load the found yml files and update/overwrite the dictionary. |
| 256 |
Args: |
| 257 |
root_dir (str): The base directory of the list of files that is being passed. |
| 258 |
var_files: (list): List of files to iterate over and load into a dictionary. |
| 259 |
|
| 260 |
Returns: |
| 261 |
Tuple (bool, str, dict) |
| 262 |
""" |
| 263 |
results = dict() |
| 264 |
failed = False |
| 265 |
err_msg = '' |
| 266 |
for filename in var_files: |
| 267 |
stop_iter = False |
| 268 |
# Never include main.yml from a role, as that is the default included by the role |
| 269 |
if self._task._role: |
| 270 |
if path.join(self._task._role._role_path, filename) == path.join(root_dir, 'vars', 'main.yml'): |
| 271 |
stop_iter = True |
| 272 |
continue |
| 273 |
|
| 274 |
filepath = path.join(root_dir, filename) |
| 275 |
if self.files_matching: |
| 276 |
if not self.matcher.search(filename): |
| 277 |
stop_iter = True |
| 278 |
|
| 279 |
if not stop_iter and not failed: |
| 280 |
if self.ignore_unknown_extensions: |
| 281 |
if path.exists(filepath) and not self._ignore_file(filename) and self._is_valid_file_ext(filename): |
| 282 |
failed, err_msg, loaded_data = self._load_files(filepath, validate_extensions=True) |
| 283 |
if not failed: |
| 284 |
results.update(loaded_data) |
| 285 |
else: |
| 286 |
if path.exists(filepath) and not self._ignore_file(filename): |
| 287 |
failed, err_msg, loaded_data = self._load_files(filepath, validate_extensions=True) |
| 288 |
if not failed: |
| 289 |
results.update(loaded_data) |
| 290 |
|
| 291 |
return failed, err_msg, results |