1
0
Fork 0
mirror of https://github.com/ansible-collections/community.general.git synced 2026-06-11 02:25:36 +00:00
community.general/plugins/module_utils/_lxc.py
patchback[bot] cd057ddcdb
[PR #12106/50046965 backport][stable-12] lxc_container: Fix create_script in plugins/module_utils/_lxc.py (#12110)
lxc_container: Fix create_script in plugins/module_utils/_lxc.py (#12106)

* Fix create_script in plugins/module_utils/_lxc.py

* Added changelog fragment

* Apply suggestions from code review - updated typing



* Apply suggestion from code review - fixed docstring argument name



* Apply suggestion from code review



* Update plugins/module_utils/_lxc.py



---------



(cherry picked from commit 50046965c9)

Co-authored-by: usbpc <3638901+usbpc@users.noreply.github.com>
Co-authored-by: Kevin Holm <kevin@holm.dev>
Co-authored-by: Felix Fontein <felix@fontein.de>
2026-05-27 12:48:57 +02:00

63 lines
2.2 KiB
Python

# Copyright (c) 2014, Kevin Carter <kevin.carter@rackspace.com>
# Copyright (c) 2025, Alexei Znamensky <russoz@gmail.com>
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
# SPDX-License-Identifier: GPL-3.0-or-later
from __future__ import annotations
import os
import subprocess
import tempfile
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.common.text.converters import to_bytes
# This is used to attach to a running container and execute commands from
# within the container on the host. This will provide local access to a
# container without using SSH. The template will attempt to work within the
# home directory of the user that was attached to the container and source
# that users environment variables by default.
ATTACH_TEMPLATE = """#!/usr/bin/env bash
pushd "$(getent passwd $(whoami)|cut -f6 -d':')"
if [[ -f ".bashrc" ]];then
source .bashrc
unset HOSTNAME
fi
popd
# User defined command
{}
"""
def create_script(arg_tuple: tuple[str, AnsibleModule]) -> None:
"""Write out a script onto a target.
This method should be backward compatible with Python when executing
from within the container.
:param arg_tuple: a tuple of (command, module) where command is the command
to run (this can be a script and can use spacing with
newlines as separation) and module is the AnsibleModule
to run commands with.
"""
command, module = arg_tuple
script_file = ""
try:
f = tempfile.NamedTemporaryFile(prefix="lxc-attach-script", delete=False, mode="wb")
f.write(to_bytes(ATTACH_TEMPLATE.format(command), errors="surrogate_or_strict"))
script_file = f.name
f.flush()
f.close()
os.chmod(script_file, 0o0700)
with tempfile.NamedTemporaryFile(prefix="lxc-attach-script-log", delete=False, mode="ab") as stdout_file:
with tempfile.NamedTemporaryFile(prefix="lxc-attach-script-err", delete=False, mode="ab") as stderr_file:
subprocess.Popen([script_file], stdout=stdout_file, stderr=stderr_file).communicate()
finally:
if script_file:
os.remove(script_file)