Debian Codegraph @

ansible_collections/community/general/plugins/module_utils/_lxc.py

raw
1 # Copyright (c) 2014, Kevin Carter <[email protected]>
2 # Copyright (c) 2025, Alexei Znamensky <[email protected]>
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
6 # Note that this module util is **PRIVATE** to the collection. It can have breaking changes at any time.
7 # Do not use this from other collections or standalone plugins/modules!
8
9 from __future__ import annotations
10
11 import os
12 import subprocess
13 import tempfile
14
15 from ansible.module_utils.basic import AnsibleModule
16 from ansible.module_utils.common.text.converters import to_bytes
17
18 # This is used to attach to a running container and execute commands from
19 # within the container on the host. This will provide local access to a
20 # container without using SSH. The template will attempt to work within the
21 # home directory of the user that was attached to the container and source
22 # that users environment variables by default.
23 ATTACH_TEMPLATE = """#!/usr/bin/env bash
24 pushd "$(getent passwd $(whoami)|cut -f6 -d':')"
25 if [[ -f ".bashrc" ]];then
26 source .bashrc
27 unset HOSTNAME
28 fi
29 popd
30
31 # User defined command
32 {}
33 """
34
35
36 def create_script(command: str, module: AnsibleModule) -> None:
37 """Write out a script onto a target.
38
39 This method should be backward compatible with Python when executing
40 from within the container.
41
42 :param command: command to run, this can be a script and can use spacing
43 with newlines as separation.
44 :param module: AnsibleModule to run commands with.
45 """
46
47 script_file = ""
48 try:
49 f = tempfile.NamedTemporaryFile(prefix="lxc-attach-script", delete=False, mode="wb")
50 f.write(to_bytes(ATTACH_TEMPLATE.format(command), errors="surrogate_or_strict"))
51 script_file = f.name
52 f.flush()
53 f.close()
54
55 os.chmod(script_file, 0o0700)
56
57 with tempfile.NamedTemporaryFile(prefix="lxc-attach-script-log", delete=False, mode="ab") as stdout_file:
58 with tempfile.NamedTemporaryFile(prefix="lxc-attach-script-err", delete=False, mode="ab") as stderr_file:
59 subprocess.Popen([script_file], stdout=stdout_file, stderr=stderr_file).communicate()
60
61 finally:
62 if script_file:
63 os.remove(script_file)