| 1 |
# Copyright (c) 2016, Yanis Guenane <[email protected]> |
| 2 |
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 3 |
# SPDX-License-Identifier: GPL-3.0-or-later |
| 4 |
|
| 5 |
# Note that this module util is **PRIVATE** to the collection. It can have breaking changes at any time. |
| 6 |
# Do not use this from other collections or standalone plugins/modules! |
| 7 |
|
| 8 |
from __future__ import annotations |
| 9 |
|
| 10 |
import errno |
| 11 |
import os |
| 12 |
import tempfile |
| 13 |
import typing as t |
| 14 |
|
| 15 |
if t.TYPE_CHECKING: |
| 16 |
from ansible.module_utils.basic import AnsibleModule # pragma: no cover |
| 17 |
|
| 18 |
|
| 19 |
def load_file(*, path: str | os.PathLike, module: AnsibleModule | None = None) -> bytes: |
| 20 |
""" |
| 21 |
Load the file as a bytes string. |
| 22 |
""" |
| 23 |
try: |
| 24 |
with open(path, "rb") as f: |
| 25 |
return f.read() |
| 26 |
except Exception as exc: |
| 27 |
if module is None: |
| 28 |
raise |
| 29 |
module.fail_json(f"Error while loading {path} - {exc}") |
| 30 |
|
| 31 |
|
| 32 |
def load_file_if_exists( |
| 33 |
*, |
| 34 |
path: str | os.PathLike, |
| 35 |
module: AnsibleModule | None = None, |
| 36 |
ignore_errors: bool = False, |
| 37 |
) -> bytes | None: |
| 38 |
""" |
| 39 |
Load the file as a bytes string. If the file does not exist, ``None`` is returned. |
| 40 |
|
| 41 |
If ``ignore_errors`` is ``True``, will ignore errors. Otherwise, errors are |
| 42 |
raised as exceptions if ``module`` is not specified, and result in ``module.fail_json`` |
| 43 |
being called when ``module`` is specified. |
| 44 |
""" |
| 45 |
try: |
| 46 |
with open(path, "rb") as f: |
| 47 |
return f.read() |
| 48 |
except EnvironmentError as exc: |
| 49 |
if exc.errno == errno.ENOENT: |
| 50 |
return None |
| 51 |
if ignore_errors: |
| 52 |
return None |
| 53 |
if module is None: |
| 54 |
raise |
| 55 |
module.fail_json(f"Error while loading {path} - {exc}") |
| 56 |
except Exception as exc: |
| 57 |
if ignore_errors: |
| 58 |
return None |
| 59 |
if module is None: |
| 60 |
raise |
| 61 |
module.fail_json(f"Error while loading {path} - {exc}") |
| 62 |
|
| 63 |
|
| 64 |
def write_file( |
| 65 |
*, |
| 66 |
module: AnsibleModule, |
| 67 |
content: bytes, |
| 68 |
default_mode: str | int | None = None, |
| 69 |
path: str | os.PathLike | None = None, |
| 70 |
) -> None: |
| 71 |
""" |
| 72 |
Writes content into destination file as securely as possible. |
| 73 |
Uses file arguments from module. |
| 74 |
""" |
| 75 |
# Find out parameters for file |
| 76 |
try: |
| 77 |
file_args = module.load_file_common_arguments(module.params, path=path) |
| 78 |
except TypeError: |
| 79 |
# The path argument is only supported in Ansible 2.10+. Fall back to |
| 80 |
# pre-2.10 behavior of module_utils/crypto.py for older Ansible versions. |
| 81 |
file_args = module.load_file_common_arguments(module.params) |
| 82 |
if path is not None: |
| 83 |
file_args["path"] = path |
| 84 |
if file_args["mode"] is None: |
| 85 |
file_args["mode"] = default_mode |
| 86 |
# Create tempfile name |
| 87 |
tmp_fd, tmp_name = tempfile.mkstemp(prefix=b".ansible_tmp") |
| 88 |
try: |
| 89 |
os.close(tmp_fd) |
| 90 |
except Exception: |
| 91 |
pass |
| 92 |
module.add_cleanup_file(tmp_name) # if we fail, let Ansible try to remove the file |
| 93 |
try: |
| 94 |
try: |
| 95 |
# Create tempfile |
| 96 |
file = os.open(tmp_name, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) |
| 97 |
os.write(file, content) |
| 98 |
os.close(file) |
| 99 |
except Exception as e: |
| 100 |
try: |
| 101 |
os.remove(tmp_name) |
| 102 |
except Exception: |
| 103 |
pass |
| 104 |
module.fail_json(msg=f"Error while writing result into temporary file: {e}") |
| 105 |
# Update destination to wanted permissions |
| 106 |
if os.path.exists(file_args["path"]): |
| 107 |
module.set_fs_attributes_if_different(file_args, False) |
| 108 |
# Move tempfile to final destination |
| 109 |
module.atomic_move( |
| 110 |
os.path.abspath(tmp_name), os.path.abspath(file_args["path"]) |
| 111 |
) |
| 112 |
# Try to update permissions again |
| 113 |
if not module.check_file_absent_if_check_mode(file_args["path"]): |
| 114 |
module.set_fs_attributes_if_different(file_args, False) |
| 115 |
except Exception as e: |
| 116 |
try: |
| 117 |
os.remove(tmp_name) |
| 118 |
except Exception: |
| 119 |
pass |
| 120 |
module.fail_json(msg=f"Error while writing result: {e}") |
| 121 |
|
| 122 |
|
| 123 |
__all__ = ("load_file", "load_file_if_exists", "write_file") |