fix(vpn-node-config): resolve ansible-lint violations
OpenVPN Ansible / Deploy VPN Networking and OpenVPN (push) Canceled after 0s
OpenVPN Ansible / Generate SBOM (push) Canceled after 0s
OpenVPN Ansible / Scan SBOM with Trivy (push) Canceled after 0s
OpenVPN Ansible / Ansible Syntax Check (push) Canceled after 38s
OpenVPN Ansible / Ansible Lint (push) Canceled after 40s

This commit is contained in:
2026-11-11 12:13:20 +01:00
parent acb5c4ba82
commit 72fb458dab
3659 changed files with 471307 additions and 12 deletions
@@ -0,0 +1,233 @@
# Based on local.py (c) 2012, Michael DeHaan <michael.dehaan@gmail.com>
#
# (c) 2013, Maykel Moya <mmoya@speedyrails.com>
# (c) 2015, Toshio Kuratomi <tkuratomi@ansible.com>
# Copyright (c) 2017 Ansible Project
# 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
DOCUMENTATION = r"""
author: Maykel Moya (!UNKNOWN) <mmoya@speedyrails.com>
name: chroot
short_description: Interact with local chroot
description:
- Run commands or put/fetch files to an existing chroot on the Ansible controller.
options:
remote_addr:
description:
- The path of the chroot you want to access.
type: string
default: inventory_hostname
vars:
- name: inventory_hostname
- name: ansible_host
executable:
description:
- User specified executable shell.
type: string
ini:
- section: defaults
key: executable
env:
- name: ANSIBLE_EXECUTABLE
vars:
- name: ansible_executable
default: /bin/sh
chroot_exe:
description:
- User specified chroot binary.
type: string
ini:
- section: chroot_connection
key: exe
env:
- name: ANSIBLE_CHROOT_EXE
vars:
- name: ansible_chroot_exe
default: chroot
disable_root_check:
description:
- Do not check that the user is not root.
ini:
- section: chroot_connection
key: disable_root_check
env:
- name: ANSIBLE_CHROOT_DISABLE_ROOT_CHECK
vars:
- name: ansible_chroot_disable_root_check
default: false
type: bool
version_added: 7.3.0
"""
EXAMPLES = r"""
- hosts: chroots
connection: community.general.chroot
tasks:
- ansible.builtin.debug:
msg: "This is coming from chroot environment"
"""
import os
import os.path
import subprocess
import traceback
from shlex import quote as shlex_quote
from ansible.errors import AnsibleError
from ansible.module_utils.basic import is_executable
from ansible.module_utils.common.process import get_bin_path
from ansible.module_utils.common.text.converters import to_bytes
from ansible.plugins.connection import BUFSIZE, ConnectionBase
from ansible.utils.display import Display
display = Display()
class Connection(ConnectionBase):
"""Local chroot based connections"""
transport = "community.general.chroot"
has_pipelining = True
# su currently has an undiagnosed issue with calculating the file
# checksums (so copy, for instance, doesn't work right)
# Have to look into that before re-enabling this
has_tty = False
default_user = "root"
def __init__(self, play_context, new_stdin, *args, **kwargs):
super().__init__(play_context, new_stdin, *args, **kwargs)
self.chroot = self._play_context.remote_addr
# do some trivial checks for ensuring 'host' is actually a chroot'able dir
if not os.path.isdir(self.chroot):
raise AnsibleError(f"{self.chroot} is not a directory")
chrootsh = os.path.join(self.chroot, "bin/sh")
# Want to check for a usable bourne shell inside the chroot.
# is_executable() == True is sufficient. For symlinks it
# gets really complicated really fast. So we punt on finding that
# out. As long as it is a symlink we assume that it will work
if not (is_executable(chrootsh) or (os.path.lexists(chrootsh) and os.path.islink(chrootsh))):
raise AnsibleError(f"{self.chroot} does not look like a chrootable dir (/bin/sh missing)")
def _connect(self):
"""connect to the chroot"""
if not self.get_option("disable_root_check") and os.geteuid() != 0:
raise AnsibleError(
"chroot connection requires running as root. "
"You can override this check with the `disable_root_check` option."
)
if os.path.isabs(self.get_option("chroot_exe")):
self.chroot_cmd = self.get_option("chroot_exe")
else:
try:
self.chroot_cmd = get_bin_path(self.get_option("chroot_exe"))
except ValueError as e:
raise AnsibleError(str(e)) from e
super()._connect()
if not self._connected:
display.vvv("THIS IS A LOCAL CHROOT DIR", host=self.chroot)
self._connected = True
def _buffered_exec_command(self, cmd, stdin=subprocess.PIPE):
"""run a command on the chroot. This is only needed for implementing
put_file() get_file() so that we don't have to read the whole file
into memory.
compared to exec_command() it looses some niceties like being able to
return the process's exit code immediately.
"""
executable = self.get_option("executable")
local_cmd = [self.chroot_cmd, self.chroot, executable, "-c", cmd]
display.vvv(f"EXEC {local_cmd}", host=self.chroot)
local_cmd = [to_bytes(i, errors="surrogate_or_strict") for i in local_cmd]
p = subprocess.Popen(local_cmd, shell=False, stdin=stdin, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
return p
def exec_command(self, cmd, in_data=None, sudoable=False):
"""run a command on the chroot"""
super().exec_command(cmd, in_data=in_data, sudoable=sudoable)
p = self._buffered_exec_command(cmd)
stdout, stderr = p.communicate(in_data)
return p.returncode, stdout, stderr
@staticmethod
def _prefix_login_path(remote_path):
"""Make sure that we put files into a standard path
If a path is relative, then we need to choose where to put it.
ssh chooses $HOME but we aren't guaranteed that a home dir will
exist in any given chroot. So for now we're choosing "/" instead.
This also happens to be the former default.
Can revisit using $HOME instead if it is a problem
"""
if not remote_path.startswith(os.path.sep):
remote_path = os.path.join(os.path.sep, remote_path)
return os.path.normpath(remote_path)
def put_file(self, in_path, out_path):
"""transfer a file from local to chroot"""
super().put_file(in_path, out_path)
display.vvv(f"PUT {in_path} TO {out_path}", host=self.chroot)
out_path = shlex_quote(self._prefix_login_path(out_path))
try:
with open(to_bytes(in_path, errors="surrogate_or_strict"), "rb") as in_file:
if not os.fstat(in_file.fileno()).st_size:
count = " count=0"
else:
count = ""
try:
p = self._buffered_exec_command(f"dd of={out_path} bs={BUFSIZE}{count}", stdin=in_file)
except OSError as e:
raise AnsibleError("chroot connection requires dd command in the chroot") from e
try:
stdout, stderr = p.communicate()
except Exception as e:
traceback.print_exc()
raise AnsibleError(f"failed to transfer file {in_path} to {out_path}") from e
if p.returncode != 0:
raise AnsibleError(f"failed to transfer file {in_path} to {out_path}:\n{stdout}\n{stderr}")
except OSError as e:
raise AnsibleError(f"file or module does not exist at: {in_path}") from e
def fetch_file(self, in_path, out_path):
"""fetch a file from chroot to local"""
super().fetch_file(in_path, out_path)
display.vvv(f"FETCH {in_path} TO {out_path}", host=self.chroot)
in_path = shlex_quote(self._prefix_login_path(in_path))
try:
p = self._buffered_exec_command(f"dd if={in_path} bs={BUFSIZE}")
except OSError as e:
raise AnsibleError("chroot connection requires dd command in the chroot") from e
with open(to_bytes(out_path, errors="surrogate_or_strict"), "wb+") as out_file:
try:
chunk = p.stdout.read(BUFSIZE)
while chunk:
out_file.write(chunk)
chunk = p.stdout.read(BUFSIZE)
except Exception as e:
traceback.print_exc()
raise AnsibleError(f"failed to transfer file {in_path} to {out_path}") from e
stdout, stderr = p.communicate()
if p.returncode != 0:
raise AnsibleError(f"failed to transfer file {in_path} to {out_path}:\n{stdout}\n{stderr}")
def close(self):
"""terminate the connection; nothing to do here"""
super().close()
self._connected = False
@@ -0,0 +1,107 @@
# Based on local.py (c) 2012, Michael DeHaan <michael.dehaan@gmail.com>
# Based on chroot.py (c) 2013, Maykel Moya <mmoya@speedyrails.com>
# Copyright (c) 2013, Michael Scherer <misc@zarb.org>
# Copyright (c) 2017 Ansible Project
# 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
DOCUMENTATION = r"""
author: Michael Scherer (@mscherer) <misc@zarb.org>
name: funcd
short_description: Use funcd to connect to target
description:
- This transport permits you to use Ansible over Func.
- For people who have already setup func and that wish to play with ansible, this permit to move gradually to ansible without
having to redo completely the setup of the network.
options:
remote_addr:
description:
- The path of the chroot you want to access.
type: string
default: inventory_hostname
vars:
- name: ansible_host
- name: ansible_func_host
"""
HAVE_FUNC = False
try:
import func.overlord.client as fc
HAVE_FUNC = True
except ImportError:
pass
import os
import shutil
import tempfile
from ansible.errors import AnsibleError
from ansible.plugins.connection import ConnectionBase
from ansible.utils.display import Display
display = Display()
class Connection(ConnectionBase):
"""Func-based connections"""
has_pipelining = False
def __init__(self, runner, host, port, *args, **kwargs):
self.runner = runner
self.host = host
# port is unused, this go on func
self.port = port
self.client = None
def connect(self, port=None):
if not HAVE_FUNC:
raise AnsibleError("func is not installed")
self.client = fc.Client(self.host)
return self
def exec_command(self, cmd, in_data=None, sudoable=True):
"""run a command on the remote minion"""
if in_data:
raise AnsibleError("Internal Error: this module does not support optimized module pipelining")
# totally ignores privilege escalation
display.vvv(f"EXEC {cmd}", host=self.host)
p = self.client.command.run(cmd)[self.host]
return p[0], p[1], p[2]
@staticmethod
def _normalize_path(path, prefix):
if not path.startswith(os.path.sep):
path = os.path.join(os.path.sep, path)
normpath = os.path.normpath(path)
return os.path.join(prefix, normpath[1:])
def put_file(self, in_path, out_path):
"""transfer a file from local to remote"""
out_path = self._normalize_path(out_path, "/")
display.vvv(f"PUT {in_path} TO {out_path}", host=self.host)
self.client.local.copyfile.send(in_path, out_path)
def fetch_file(self, in_path, out_path):
"""fetch a file from remote to local"""
in_path = self._normalize_path(in_path, "/")
display.vvv(f"FETCH {in_path} TO {out_path}", host=self.host)
# need to use a tmp dir due to difference of semantic for getfile
# ( who take a # directory as destination) and fetch_file, who
# take a file directly
tmpdir = tempfile.mkdtemp(prefix="func_ansible")
self.client.local.getfile.get(in_path, tmpdir)
shutil.move(os.path.join(tmpdir, self.host, os.path.basename(in_path)), out_path)
shutil.rmtree(tmpdir)
def close(self):
"""terminate the connection; nothing to do here"""
pass
@@ -0,0 +1,358 @@
# Based on lxd.py (c) 2016, Matt Clay <matt@mystile.com>
# (c) 2023, Stephane Graber <stgraber@stgraber.org>
# Copyright (c) 2023 Ansible Project
# 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
DOCUMENTATION = r"""
author: Stéphane Graber (@stgraber)
name: incus
short_description: Run tasks in Incus instances using the Incus CLI
description:
- Run commands or put/fetch files to an existing Incus instance using Incus CLI.
version_added: "8.2.0"
notes:
- When using this collection for Windows virtual machines, set C(ansible_shell_type) to C(powershell) or C(cmd) as a variable to the host in
the inventory.
options:
remote_addr:
description:
- The instance identifier.
type: string
default: inventory_hostname
vars:
- name: inventory_hostname
- name: ansible_host
- name: ansible_incus_host
executable:
description:
- The shell to use for execution inside the instance.
type: string
default: /bin/sh
vars:
- name: ansible_executable
- name: ansible_incus_executable
incus_become_method:
description:
- Become command used to switch to a non-root user.
- Is only used when O(remote_user) is not V(root).
type: str
default: /bin/su
vars:
- name: incus_become_method
version_added: 10.4.0
remote:
description:
- The name of the Incus remote to use (per C(incus remote list)).
- Remotes are used to access multiple servers from a single client.
type: string
default: local
vars:
- name: ansible_incus_remote
remote_user:
description:
- User to login/authenticate as.
- Can be set from the CLI with the C(--user) or C(-u) options.
type: string
default: root
vars:
- name: ansible_user
env:
- name: ANSIBLE_REMOTE_USER
ini:
- section: defaults
key: remote_user
keyword:
- name: remote_user
version_added: 10.4.0
remote_user_id_command:
description:
- Command used to retrieve the remote UID and GID of O(remote_user).
- Is used to set the ownership of files copied with C(put_file) when O(remote_user) is not V(root).
- The command is run inside the instance twice, once with the argument C(-u) to retrieve the UID and once with C(-g) to retrieve
the GID.
- In both cases the command must write the numeric ID, and nothing else, to standard output.
type: str
default: /bin/id
vars:
- name: ansible_incus_user_id_command
version_added: 13.4.0
project:
description:
- The name of the Incus project to use (per C(incus project list)).
- Projects are used to divide the instances running on a server.
type: string
default: default
vars:
- name: ansible_incus_project
"""
import os
import re
import shlex
from subprocess import PIPE, Popen
from ansible.errors import AnsibleConnectionFailure, AnsibleError, AnsibleFileNotFound
from ansible.module_utils.common.process import get_bin_path
from ansible.module_utils.common.text.converters import to_bytes, to_text
from ansible.plugins.connection import ConnectionBase
class Connection(ConnectionBase):
"""Incus based connections"""
transport = "incus"
has_pipelining = True
def __init__(self, play_context, new_stdin, *args, **kwargs):
super().__init__(play_context, new_stdin, *args, **kwargs)
self._incus_cmd = get_bin_path("incus")
if not self._incus_cmd:
raise AnsibleError("incus command not found in PATH")
if getattr(self._shell, "_IS_WINDOWS", False):
# Initializing regular expression patterns to match on a PowerShell or cmd command line.
self.powershell_regex_pattern = re.compile(
r'^"?(?P<executable>(?:[a-z]:\\)?[a-z0-9 ()\\.]*powershell(?:\.exe)?)"?\s+(?P<args>.*)(?P<command>-c(?:ommand)?)\s+(?P<post_args>.*(\n.*)*)',
re.IGNORECASE,
)
self.cmd_regex_pattern = re.compile(
r'^"?(?P<executable>(?:[a-z]:\\)?[a-z0-9 ()\\.]*cmd(?:\.exe)?)"?\s+(?P<args>.*)(?P<command>/c)\s+(?P<post_args>.*)',
re.IGNORECASE,
)
# Basic setup for a Windows host.
self.has_native_async = True
self.always_pipeline_modules = True
self.module_implementation_preferences = (".ps1", ".exe", "")
self.allow_executable = False
def _connect(self):
"""connect to Incus (nothing to do here)"""
super()._connect()
if not self._connected:
self._display.vvv(
f"ESTABLISH Incus CONNECTION FOR USER: {self.get_option('remote_user')}", host=self._instance()
)
self._connected = True
def _build_command(self, cmd) -> list[str]:
"""build the command to execute on the incus host"""
# Force pseudo-terminal allocation if the active become plugin
# requires one (e.g. community.general.machinectl), otherwise the
# become helper runs without a controlling tty and silently fails.
require_tty = self.become is not None and getattr(self.become, "require_tty", False)
exec_cmd: list[str] = [
self._incus_cmd,
"--project",
self.get_option("project"),
"exec",
*(["-T"] if getattr(self._shell, "_IS_WINDOWS", False) else []),
*(["-t"] if require_tty and not getattr(self._shell, "_IS_WINDOWS", False) else []),
f"{self.get_option('remote')}:{self._instance()}",
"--",
]
if getattr(self._shell, "_IS_WINDOWS", False):
if regex_match := self.powershell_regex_pattern.match(cmd):
regex_pattern = self.powershell_regex_pattern
elif regex_match := self.cmd_regex_pattern.match(cmd):
regex_pattern = self.cmd_regex_pattern
if regex_match:
self._display.vvvvvv(
f'Found keyword: "{regex_match.group("command")}" based on regex: {regex_pattern.pattern}',
host=self._instance(),
)
# To avoid splitting on a space contained in the path, set the executable as the first argument.
exec_cmd.append(regex_match.group("executable"))
if args := regex_match.group("args"):
exec_cmd.extend(args.strip().split(" "))
# Set the command argument depending on cmd or powershell and the rest of it
exec_cmd.append(regex_match.group("command"))
if post_args := regex_match.group("post_args"):
post_args = post_args.strip()
# Keep quotes from becoming literal PowerShell argument content.
if len(post_args) >= 2 and post_args[0] == post_args[-1] and post_args[0] in ("'", '"'):
self._display.v(
"WARNING: PowerShell -Command argument is wrapped in outer quotes; "
"this connection plugin strips those quotes and behavior may differ "
"from a direct shell run. Prefer passing -Command without extra "
"outer quoting.",
host=self._instance(),
)
post_args = post_args[1:-1]
exec_cmd.append(post_args)
else:
# Keep quotes from becoming literal PowerShell argument content.
# shlex is not a full PowerShell/Windows command-line parser,
# but with posix=False it reliably keeps quoted segments (for
# example, paths with spaces) as single argv items, which is
# what we need before passing arguments to incus exec.
parts = shlex.split(cmd, posix=False)
for i, part in enumerate(parts[:-1]):
if part.lower() in {"-enc", "-encodedcommand", "-file", "-f"}:
parts[i + 1] = parts[i + 1].strip("'\"")
break
exec_cmd.extend(parts)
else:
if self.get_option("remote_user") != "root":
self._display.vvv(
f"INFO: Running as non-root user: {self.get_option('remote_user')}, \
trying to run 'incus exec' with become method: {self.get_option('incus_become_method')}",
host=self._instance(),
)
exec_cmd.extend([self.get_option("incus_become_method"), self.get_option("remote_user"), "-c"])
exec_cmd.extend([self.get_option("executable"), "-c", cmd])
return exec_cmd
def _instance(self):
# Return only the leading part of the FQDN as the instance name
# as Incus instance names cannot be a FQDN.
return self.get_option("remote_addr").split(".")[0]
def exec_command(self, cmd, in_data=None, sudoable=True):
"""execute a command on the Incus host"""
super().exec_command(cmd, in_data=in_data, sudoable=sudoable)
self._display.vvv(f"EXEC {cmd}", host=self._instance())
local_cmd = self._build_command(cmd)
self._display.vvvvv(f"EXEC {local_cmd}", host=self._instance())
local_cmd = [to_bytes(i, errors="surrogate_or_strict") for i in local_cmd]
in_data = to_bytes(in_data, errors="surrogate_or_strict", nonstring="passthru")
process = Popen(local_cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE)
stdout, stderr = process.communicate(in_data)
if stderr.startswith(b"Error: ") and stderr.rstrip().endswith(b": Instance is not running"):
raise AnsibleConnectionFailure(
f"instance not running: {self._instance()} (remote={self.get_option('remote')}, project={self.get_option('project')})"
)
if stderr.startswith(b"Error: ") and stderr.rstrip().endswith(b": Instance not found"):
raise AnsibleConnectionFailure(
f"instance not found: {self._instance()} (remote={self.get_option('remote')}, project={self.get_option('project')})"
)
if stderr.startswith(b"Error: ") and b": User does not have permission " in stderr:
raise AnsibleConnectionFailure(
f"instance access denied: {self._instance()} (remote={self.get_option('remote')}, project={self.get_option('project')})"
)
if stderr.startswith(b"Error: ") and b": User does not have entitlement " in stderr:
raise AnsibleConnectionFailure(
f"instance access denied: {self._instance()} (remote={self.get_option('remote')}, project={self.get_option('project')})"
)
return process.returncode, stdout, stderr
def _get_remote_uid_gid(self) -> tuple[int, int]:
"""Get the user and group ID of 'remote_user' from the instance."""
id_cmd = self.get_option("remote_user_id_command")
rc, uid_out, err = self.exec_command(f"{id_cmd} -u")
if rc != 0:
raise AnsibleError(f"Failed to get remote uid for user {self.get_option('remote_user')}: {err}")
uid = uid_out.strip()
rc, gid_out, err = self.exec_command(f"{id_cmd} -g")
if rc != 0:
raise AnsibleError(f"Failed to get remote gid for user {self.get_option('remote_user')}: {err}")
gid = gid_out.strip()
return int(uid), int(gid)
def put_file(self, in_path, out_path):
"""put a file from local to Incus"""
super().put_file(in_path, out_path)
self._display.vvv(f"PUT {in_path} TO {out_path}", host=self._instance())
if not os.path.isfile(to_bytes(in_path, errors="surrogate_or_strict")):
raise AnsibleFileNotFound(f"input path is not a file: {in_path}")
if not getattr(self._shell, "_IS_WINDOWS", False) and self.get_option("remote_user") != "root":
uid, gid = self._get_remote_uid_gid()
local_cmd = [
self._incus_cmd,
"--project",
self.get_option("project"),
"file",
"push",
"--uid",
str(uid),
"--gid",
str(gid),
"--quiet",
in_path,
f"{self.get_option('remote')}:{self._instance()}/{out_path}",
]
else:
local_cmd = [
self._incus_cmd,
"--project",
self.get_option("project"),
"file",
"push",
"--quiet",
in_path,
f"{self.get_option('remote')}:{self._instance()}/{out_path}",
]
self._display.vvvvv(f"PUT {local_cmd}", host=self._instance())
local_cmd = [to_bytes(i, errors="surrogate_or_strict") for i in local_cmd]
process = Popen(local_cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE)
_stdout, stderr = process.communicate()
if process.returncode != 0:
raise AnsibleError(f"failed to transfer file to instance {self._instance()}: {to_text(stderr).strip()}")
def fetch_file(self, in_path, out_path):
"""fetch a file from Incus to local"""
super().fetch_file(in_path, out_path)
self._display.vvv(f"FETCH {in_path} TO {out_path}", host=self._instance())
local_cmd = [
self._incus_cmd,
"--project",
self.get_option("project"),
"file",
"pull",
"--quiet",
f"{self.get_option('remote')}:{self._instance()}/{in_path}",
out_path,
]
local_cmd = [to_bytes(i, errors="surrogate_or_strict") for i in local_cmd]
process = Popen(local_cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE)
_stdout, stderr = process.communicate()
if process.returncode != 0:
raise AnsibleError(f"failed to transfer file from instance {self._instance()}: {to_text(stderr).strip()}")
def close(self):
"""close the connection (nothing to do here)"""
super().close()
self._connected = False
@@ -0,0 +1,88 @@
# Based on jail.py
# (c) 2013, Michael Scherer <misc@zarb.org>
# (c) 2015, Toshio Kuratomi <tkuratomi@ansible.com>
# (c) 2016, Stephan Lohse <dev-github@ploek.org>
# Copyright (c) 2017 Ansible Project
# 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
DOCUMENTATION = r"""
author: Stephan Lohse (!UNKNOWN) <dev-github@ploek.org>
name: iocage
short_description: Run tasks in iocage jails
description:
- Run commands or put/fetch files to an existing iocage jail.
options:
remote_addr:
description:
- Path to the jail.
type: string
vars:
- name: ansible_host
- name: ansible_iocage_host
remote_user:
description:
- User to execute as inside the jail.
type: string
vars:
- name: ansible_user
- name: ansible_iocage_user
"""
import subprocess
from ansible.errors import AnsibleError
from ansible.module_utils.common.text.converters import to_native
from ansible.utils.display import Display
from ansible_collections.community.general.plugins.connection.jail import Connection as Jail
display = Display()
class Connection(Jail):
"""Local iocage based connections"""
transport = "community.general.iocage"
def __init__(self, play_context, new_stdin, *args, **kwargs):
self.ioc_jail = play_context.remote_addr
self.iocage_cmd = Jail._search_executable("iocage")
jail_uuid = self.get_jail_uuid()
kwargs[Jail.modified_jailname_key] = f"ioc-{jail_uuid}"
display.vvv(
f"Jail {self.ioc_jail} has been translated to {kwargs[Jail.modified_jailname_key]}",
host=kwargs[Jail.modified_jailname_key],
)
super().__init__(play_context, new_stdin, *args, **kwargs)
def get_jail_uuid(self):
p = subprocess.Popen(
[self.iocage_cmd, "get", "host_hostuuid", self.ioc_jail],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
)
stdout, stderr = p.communicate()
if stdout is not None:
stdout = to_native(stdout)
if stderr is not None:
stderr = to_native(stderr)
# otherwise p.returncode would not be set
p.wait()
if p.returncode != 0:
raise AnsibleError(f"iocage returned an error: {stdout}")
return stdout.strip("\n")
@@ -0,0 +1,207 @@
# Based on local.py by Michael DeHaan <michael.dehaan@gmail.com>
# and chroot.py by Maykel Moya <mmoya@speedyrails.com>
# Copyright (c) 2013, Michael Scherer <misc@zarb.org>
# Copyright (c) 2015, Toshio Kuratomi <tkuratomi@ansible.com>
# Copyright (c) 2017 Ansible Project
# 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
DOCUMENTATION = r"""
author: Ansible Core Team
name: jail
short_description: Run tasks in jails
description:
- Run commands or put/fetch files to an existing jail.
options:
remote_addr:
description:
- Path to the jail.
type: string
default: inventory_hostname
vars:
- name: inventory_hostname
- name: ansible_host
- name: ansible_jail_host
remote_user:
description:
- User to execute as inside the jail.
type: string
vars:
- name: ansible_user
- name: ansible_jail_user
"""
import os
import os.path
import subprocess
import traceback
from shlex import quote as shlex_quote
from ansible.errors import AnsibleError
from ansible.module_utils.common.process import get_bin_path
from ansible.module_utils.common.text.converters import to_bytes, to_native, to_text
from ansible.plugins.connection import BUFSIZE, ConnectionBase
from ansible.utils.display import Display
display = Display()
class Connection(ConnectionBase):
"""Local BSD Jail based connections"""
modified_jailname_key = "conn_jail_name"
transport = "community.general.jail"
# Pipelining may work. Someone needs to test by setting this to True and
# having pipelining=True in their ansible.cfg
has_pipelining = True
has_tty = False
def __init__(self, play_context, new_stdin, *args, **kwargs):
super().__init__(play_context, new_stdin, *args, **kwargs)
self.jail = self._play_context.remote_addr
if self.modified_jailname_key in kwargs:
self.jail = kwargs[self.modified_jailname_key]
if os.geteuid() != 0:
raise AnsibleError("jail connection requires running as root")
self.jls_cmd = self._search_executable("jls")
self.jexec_cmd = self._search_executable("jexec")
if self.jail not in self.list_jails():
raise AnsibleError(f"incorrect jail name {self.jail}")
@staticmethod
def _search_executable(executable):
try:
return get_bin_path(executable)
except ValueError as e:
raise AnsibleError(f"{executable} command not found in PATH") from e
def list_jails(self):
p = subprocess.Popen(
[self.jls_cmd, "-q", "name"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE
)
stdout, stderr = p.communicate()
return to_text(stdout, errors="surrogate_or_strict").split()
def _connect(self):
"""connect to the jail; nothing to do here"""
super()._connect()
if not self._connected:
display.vvv(f"ESTABLISH JAIL CONNECTION FOR USER: {self._play_context.remote_user}", host=self.jail)
self._connected = True
def _buffered_exec_command(self, cmd, stdin=subprocess.PIPE):
"""run a command on the jail. This is only needed for implementing
put_file() get_file() so that we don't have to read the whole file
into memory.
compared to exec_command() it looses some niceties like being able to
return the process's exit code immediately.
"""
local_cmd = [self.jexec_cmd]
set_env = ""
if self._play_context.remote_user is not None:
local_cmd += ["-U", self._play_context.remote_user]
# update HOME since -U does not update the jail environment
set_env = f"HOME=~{self._play_context.remote_user} "
local_cmd += [self.jail, self._play_context.executable, "-c", set_env + cmd]
display.vvv(f"EXEC {local_cmd}", host=self.jail)
local_cmd = [to_bytes(i, errors="surrogate_or_strict") for i in local_cmd]
p = subprocess.Popen(local_cmd, shell=False, stdin=stdin, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
return p
def exec_command(self, cmd, in_data=None, sudoable=False):
"""run a command on the jail"""
super().exec_command(cmd, in_data=in_data, sudoable=sudoable)
p = self._buffered_exec_command(cmd)
stdout, stderr = p.communicate(in_data)
return p.returncode, stdout, stderr
@staticmethod
def _prefix_login_path(remote_path):
"""Make sure that we put files into a standard path
If a path is relative, then we need to choose where to put it.
ssh chooses $HOME but we aren't guaranteed that a home dir will
exist in any given chroot. So for now we're choosing "/" instead.
This also happens to be the former default.
Can revisit using $HOME instead if it is a problem
"""
if not remote_path.startswith(os.path.sep):
remote_path = os.path.join(os.path.sep, remote_path)
return os.path.normpath(remote_path)
def put_file(self, in_path, out_path):
"""transfer a file from local to jail"""
super().put_file(in_path, out_path)
display.vvv(f"PUT {in_path} TO {out_path}", host=self.jail)
out_path = shlex_quote(self._prefix_login_path(out_path))
try:
with open(to_bytes(in_path, errors="surrogate_or_strict"), "rb") as in_file:
if not os.fstat(in_file.fileno()).st_size:
count = " count=0"
else:
count = ""
try:
p = self._buffered_exec_command(f"dd of={out_path} bs={BUFSIZE}{count}", stdin=in_file)
except OSError as e:
raise AnsibleError("jail connection requires dd command in the jail") from e
try:
stdout, stderr = p.communicate()
except Exception as e:
traceback.print_exc()
raise AnsibleError(f"failed to transfer file {in_path} to {out_path}") from e
if p.returncode != 0:
raise AnsibleError(
f"failed to transfer file {in_path} to {out_path}:\n{to_native(stdout)}\n{to_native(stderr)}"
)
except OSError as e:
raise AnsibleError(f"file or module does not exist at: {in_path}") from e
def fetch_file(self, in_path, out_path):
"""fetch a file from jail to local"""
super().fetch_file(in_path, out_path)
display.vvv(f"FETCH {in_path} TO {out_path}", host=self.jail)
in_path = shlex_quote(self._prefix_login_path(in_path))
try:
p = self._buffered_exec_command(f"dd if={in_path} bs={BUFSIZE}")
except OSError as e:
raise AnsibleError("jail connection requires dd command in the jail") from e
with open(to_bytes(out_path, errors="surrogate_or_strict"), "wb+") as out_file:
try:
chunk = p.stdout.read(BUFSIZE)
while chunk:
out_file.write(chunk)
chunk = p.stdout.read(BUFSIZE)
except Exception as e:
traceback.print_exc()
raise AnsibleError(f"failed to transfer file {in_path} to {out_path}") from e
stdout, stderr = p.communicate()
if p.returncode != 0:
raise AnsibleError(
f"failed to transfer file {in_path} to {out_path}:\n{to_native(stdout)}\n{to_native(stderr)}"
)
def close(self):
"""terminate the connection; nothing to do here"""
super().close()
self._connected = False
@@ -0,0 +1,230 @@
# (c) 2015, Joerg Thalheim <joerg@higgsboson.tk>
# Copyright (c) 2017 Ansible Project
# 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
DOCUMENTATION = r"""
author: Joerg Thalheim (!UNKNOWN) <joerg@higgsboson.tk>
name: lxc
short_description: Run tasks in LXC containers using lxc python library
description:
- Run commands or put/fetch files to an existing LXC container using lxc python library.
options:
remote_addr:
description:
- Container identifier.
type: string
default: inventory_hostname
vars:
- name: inventory_hostname
- name: ansible_host
- name: ansible_lxc_host
executable:
default: /bin/sh
description:
- Shell executable.
type: string
vars:
- name: ansible_executable
- name: ansible_lxc_executable
"""
import errno
import fcntl
import os
import select
import shutil
import traceback
HAS_LIBLXC = False
try:
import lxc as _lxc
HAS_LIBLXC = True
except ImportError:
pass
from ansible import errors
from ansible.module_utils.common.text.converters import to_bytes, to_native
from ansible.plugins.connection import ConnectionBase
class Connection(ConnectionBase):
"""Local lxc based connections"""
transport = "community.general.lxc"
has_pipelining = True
default_user = "root"
def __init__(self, play_context, new_stdin, *args, **kwargs):
super().__init__(play_context, new_stdin, *args, **kwargs)
self.container_name = None
self.container = None
def _connect(self):
"""connect to the lxc; nothing to do here"""
super()._connect()
if not HAS_LIBLXC:
msg = "lxc python bindings are not installed"
raise errors.AnsibleError(msg)
container_name = self.get_option("remote_addr")
if self.container and self.container_name == container_name:
return
self.container_name = container_name
self._display.vvv("THIS IS A LOCAL LXC DIR", host=self.container_name)
self.container = _lxc.Container(self.container_name)
if self.container.state == "STOPPED":
raise errors.AnsibleError(f"{self.container_name} is not running")
@staticmethod
def _communicate(pid, in_data, stdin, stdout, stderr):
buf = {stdout: [], stderr: []}
read_fds = [stdout, stderr]
if in_data:
write_fds = [stdin]
else:
write_fds = []
while len(read_fds) > 0 or len(write_fds) > 0:
try:
ready_reads, ready_writes, dummy = select.select(read_fds, write_fds, [])
except OSError as e:
if e.args[0] == errno.EINTR:
continue
raise
for fd in ready_writes:
in_data = in_data[os.write(fd, in_data) :]
if len(in_data) == 0:
write_fds.remove(fd)
for fd in ready_reads:
data = os.read(fd, 32768)
if not data:
read_fds.remove(fd)
buf[fd].append(data)
(pid, returncode) = os.waitpid(pid, 0)
return returncode, b"".join(buf[stdout]), b"".join(buf[stderr])
def _set_nonblocking(self, fd):
flags = fcntl.fcntl(fd, fcntl.F_GETFL) | os.O_NONBLOCK
fcntl.fcntl(fd, fcntl.F_SETFL, flags)
return fd
def exec_command(self, cmd, in_data=None, sudoable=False):
"""run a command on the chroot"""
super().exec_command(cmd, in_data=in_data, sudoable=sudoable)
# python2-lxc needs bytes. python3-lxc needs text.
executable = to_native(self.get_option("executable"), errors="surrogate_or_strict")
local_cmd = [executable, "-c", to_native(cmd, errors="surrogate_or_strict")]
read_stdout, write_stdout = None, None
read_stderr, write_stderr = None, None
read_stdin, write_stdin = None, None
try:
read_stdout, write_stdout = os.pipe()
read_stderr, write_stderr = os.pipe()
kwargs = {
"stdout": self._set_nonblocking(write_stdout),
"stderr": self._set_nonblocking(write_stderr),
"env_policy": _lxc.LXC_ATTACH_CLEAR_ENV,
}
if in_data:
read_stdin, write_stdin = os.pipe()
kwargs["stdin"] = self._set_nonblocking(read_stdin)
self._display.vvv(f"EXEC {local_cmd}", host=self.container_name)
pid = self.container.attach(_lxc.attach_run_command, local_cmd, **kwargs)
if pid == -1:
msg = f"failed to attach to container {self.container_name}"
raise errors.AnsibleError(msg)
write_stdout = os.close(write_stdout)
write_stderr = os.close(write_stderr)
if read_stdin:
read_stdin = os.close(read_stdin)
return self._communicate(pid, in_data, write_stdin, read_stdout, read_stderr)
finally:
fds = [read_stdout, write_stdout, read_stderr, write_stderr, read_stdin, write_stdin]
for fd in fds:
if fd:
os.close(fd)
def put_file(self, in_path, out_path):
"""transfer a file from local to lxc"""
super().put_file(in_path, out_path)
self._display.vvv(f"PUT {in_path} TO {out_path}", host=self.container_name)
in_path = to_bytes(in_path, errors="surrogate_or_strict")
out_path = to_bytes(out_path, errors="surrogate_or_strict")
if not os.path.exists(in_path):
msg = f"file or module does not exist: {in_path}"
raise errors.AnsibleFileNotFound(msg)
try:
src_file = open(in_path, "rb")
except OSError as e:
traceback.print_exc()
raise errors.AnsibleError(f"failed to open input file to {in_path}") from e
try:
def write_file(args):
with open(out_path, "wb+") as dst_file:
shutil.copyfileobj(src_file, dst_file)
try:
self.container.attach_wait(write_file, None)
except OSError as e:
traceback.print_exc()
msg = f"failed to transfer file to {out_path}"
raise errors.AnsibleError(msg) from e
finally:
src_file.close()
def fetch_file(self, in_path, out_path):
"""fetch a file from lxc to local"""
super().fetch_file(in_path, out_path)
self._display.vvv(f"FETCH {in_path} TO {out_path}", host=self.container_name)
in_path = to_bytes(in_path, errors="surrogate_or_strict")
out_path = to_bytes(out_path, errors="surrogate_or_strict")
try:
dst_file = open(out_path, "wb")
except OSError as e:
traceback.print_exc()
msg = f"failed to open output file {out_path}"
raise errors.AnsibleError(msg) from e
try:
def write_file(args):
try:
with open(in_path, "rb") as src_file:
shutil.copyfileobj(src_file, dst_file)
finally:
# this is needed in the lxc child process
# to flush internal python buffers
dst_file.close()
try:
self.container.attach_wait(write_file, None)
except OSError as e:
traceback.print_exc()
msg = f"failed to transfer file from {in_path} to {out_path}"
raise errors.AnsibleError(msg) from e
finally:
dst_file.close()
def close(self):
"""terminate the connection; nothing to do here"""
super().close()
self._connected = False
@@ -0,0 +1,246 @@
# Copyright (c) 2016 Matt Clay <matt@mystile.com>
# Copyright (c) 2017 Ansible Project
# 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
DOCUMENTATION = r"""
author: Matt Clay (@mattclay) <matt@mystile.com>
name: lxd
short_description: Run tasks in LXD instances using C(lxc) CLI
description:
- Run commands or put/fetch files to an existing instance using C(lxc) CLI.
options:
remote_addr:
description:
- Instance (container/VM) identifier.
- Since community.general 8.0.0, a FQDN can be provided; in that case, the first component (the part before C(.)) is
used as the instance identifier.
type: string
default: inventory_hostname
vars:
- name: inventory_hostname
- name: ansible_host
- name: ansible_lxd_host
executable:
description:
- Shell to use for execution inside instance.
type: string
default: /bin/sh
vars:
- name: ansible_executable
- name: ansible_lxd_executable
lxd_become_method:
description:
- Become command used to switch to a non-root user.
- Is only used when O(remote_user) is not V(root).
type: str
default: /bin/su
vars:
- name: lxd_become_method
version_added: 10.4.0
remote:
description:
- Name of the LXD remote to use.
type: string
default: local
vars:
- name: ansible_lxd_remote
version_added: 2.0.0
remote_user:
description:
- User to login/authenticate as.
- Can be set from the CLI with the C(--user) or C(-u) options.
type: string
default: root
vars:
- name: ansible_user
env:
- name: ANSIBLE_REMOTE_USER
ini:
- section: defaults
key: remote_user
keyword:
- name: remote_user
version_added: 10.4.0
project:
description:
- Name of the LXD project to use.
type: string
vars:
- name: ansible_lxd_project
version_added: 2.0.0
"""
import os
from subprocess import PIPE, Popen
from ansible.errors import AnsibleConnectionFailure, AnsibleError, AnsibleFileNotFound
from ansible.module_utils.common.process import get_bin_path
from ansible.module_utils.common.text.converters import to_bytes, to_text
from ansible.plugins.connection import ConnectionBase
class Connection(ConnectionBase):
"""lxd based connections"""
transport = "community.general.lxd"
has_pipelining = True
def __init__(self, play_context, new_stdin, *args, **kwargs):
super().__init__(play_context, new_stdin, *args, **kwargs)
try:
self._lxc_cmd = get_bin_path("lxc")
except ValueError as e:
raise AnsibleError("lxc command not found in PATH") from e
def _host(self):
"""translate remote_addr to lxd (short) hostname"""
return self.get_option("remote_addr").split(".", 1)[0]
def _connect(self):
"""connect to lxd (nothing to do here)"""
super()._connect()
if not self._connected:
self._display.vvv(f"ESTABLISH LXD CONNECTION FOR USER: {self.get_option('remote_user')}", host=self._host())
self._connected = True
def _build_command(self, cmd) -> list[str]:
"""build the command to execute on the lxd host"""
exec_cmd: list[str] = [self._lxc_cmd]
if self.get_option("project"):
exec_cmd.extend(["--project", self.get_option("project")])
exec_cmd.extend(["exec", f"{self.get_option('remote')}:{self._host()}", "--"])
if self.get_option("remote_user") != "root":
self._display.vvv(
f"INFO: Running as non-root user: {self.get_option('remote_user')}, \
trying to run 'lxc exec' with become method: {self.get_option('lxd_become_method')}",
host=self._host(),
)
exec_cmd.extend([self.get_option("lxd_become_method"), self.get_option("remote_user"), "-c"])
exec_cmd.extend([self.get_option("executable"), "-c", cmd])
return exec_cmd
def exec_command(self, cmd, in_data=None, sudoable=True):
"""execute a command on the lxd host"""
super().exec_command(cmd, in_data=in_data, sudoable=sudoable)
self._display.vvv(f"EXEC {cmd}", host=self._host())
local_cmd = self._build_command(cmd)
self._display.vvvvv(f"EXEC {local_cmd}", host=self._host())
local_cmd = [to_bytes(i, errors="surrogate_or_strict") for i in local_cmd]
in_data = to_bytes(in_data, errors="surrogate_or_strict", nonstring="passthru")
process = Popen(local_cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE)
stdout, stderr = process.communicate(in_data)
stdout = to_text(stdout)
stderr = to_text(stderr)
self._display.vvvvv(f"EXEC lxc output: {stdout} {stderr}", host=self._host())
if "is not running" in stderr:
raise AnsibleConnectionFailure(f"instance not running: {self._host()}")
if stderr.strip() == "Error: Instance not found" or stderr.strip() == "error: not found":
raise AnsibleConnectionFailure(f"instance not found: {self._host()}")
return process.returncode, stdout, stderr
def _get_remote_uid_gid(self) -> tuple[int, int]:
"""Get the user and group ID of 'remote_user' from the instance."""
rc, uid_out, err = self.exec_command("/bin/id -u")
if rc != 0:
raise AnsibleError(f"Failed to get remote uid for user {self.get_option('remote_user')}: {err}")
uid = uid_out.strip()
rc, gid_out, err = self.exec_command("/bin/id -g")
if rc != 0:
raise AnsibleError(f"Failed to get remote gid for user {self.get_option('remote_user')}: {err}")
gid = gid_out.strip()
return int(uid), int(gid)
def put_file(self, in_path, out_path):
"""put a file from local to lxd"""
super().put_file(in_path, out_path)
self._display.vvv(f"PUT {in_path} TO {out_path}", host=self._host())
if not os.path.isfile(to_bytes(in_path, errors="surrogate_or_strict")):
raise AnsibleFileNotFound(f"input path is not a file: {in_path}")
local_cmd = [self._lxc_cmd]
if self.get_option("project"):
local_cmd.extend(["--project", self.get_option("project")])
if self.get_option("remote_user") != "root":
uid, gid = self._get_remote_uid_gid()
local_cmd.extend(
[
"file",
"push",
"--uid",
str(uid),
"--gid",
str(gid),
in_path,
f"{self.get_option('remote')}:{self._host()}/{out_path}",
]
)
else:
local_cmd.extend(
[
"file",
"push",
in_path,
f"{self.get_option('remote')}:{self._host()}/{out_path}",
]
)
self._display.vvvvv(f"PUT {local_cmd}", host=self._host())
local_cmd = [to_bytes(i, errors="surrogate_or_strict") for i in local_cmd]
process = Popen(local_cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE)
_stdout, stderr = process.communicate()
if process.returncode != 0:
raise AnsibleError(f"failed to transfer file to instance {self._host()}: {to_text(stderr).strip()}")
def fetch_file(self, in_path, out_path):
"""fetch a file from lxd to local"""
super().fetch_file(in_path, out_path)
self._display.vvv(f"FETCH {in_path} TO {out_path}", host=self._host())
local_cmd = [self._lxc_cmd]
if self.get_option("project"):
local_cmd.extend(["--project", self.get_option("project")])
local_cmd.extend(["file", "pull", f"{self.get_option('remote')}:{self._host()}/{in_path}", out_path])
local_cmd = [to_bytes(i, errors="surrogate_or_strict") for i in local_cmd]
process = Popen(local_cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE)
_stdout, stderr = process.communicate()
if process.returncode != 0:
raise AnsibleError(f"failed to transfer file from instance {self._host()}: {to_text(stderr).strip()}")
def close(self):
"""close the connection (nothing to do here)"""
super().close()
self._connected = False
@@ -0,0 +1,154 @@
# Based on the buildah connection plugin
# Copyright (c) 2017 Ansible Project
# 2018 Kushal Das
# 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
#
#
# Written by: Kushal Das (https://github.com/kushaldas)
from __future__ import annotations
DOCUMENTATION = r"""
name: qubes
short_description: Interact with an existing QubesOS AppVM
description:
- Run commands or put/fetch files to an existing Qubes AppVM using qubes tools.
author: Kushal Das (@kushaldas)
options:
remote_addr:
description:
- VM name.
type: string
default: inventory_hostname
vars:
- name: ansible_host
remote_user:
description:
- The user to execute as inside the VM.
type: string
default: The I(user) account as default in Qubes OS.
vars:
- name: ansible_user
# keyword:
# - name: hosts
"""
import subprocess
from ansible.errors import AnsibleConnectionFailure
from ansible.module_utils.common.text.converters import to_bytes
from ansible.plugins.connection import ConnectionBase, ensure_connect
from ansible.utils.display import Display
display = Display()
# this _has to be_ named Connection
class Connection(ConnectionBase):
"""This is a connection plugin for qubes: it uses qubes-run-vm binary to interact with the containers."""
# String used to identify this Connection class from other classes
transport = "community.general.qubes"
has_pipelining = True
def __init__(self, play_context, new_stdin, *args, **kwargs):
super().__init__(play_context, new_stdin, *args, **kwargs)
self._remote_vmname = self._play_context.remote_addr
self._connected = False
# Default username in Qubes
self.user = "user"
if self._play_context.remote_user:
self.user = self._play_context.remote_user
def _qubes(self, cmd=None, in_data=None, shell="qubes.VMShell"):
"""run qvm-run executable
:param cmd: cmd string for remote system
:param in_data: data passed to qvm-run-vm's stdin
:return: return code, stdout, stderr
"""
display.vvvv("CMD: ", cmd)
if not cmd.endswith("\n"):
cmd = f"{cmd}\n"
local_cmd = []
# For dom0
local_cmd.extend(["qvm-run", "--pass-io", "--service"])
if self.user != "user":
# Means we have a remote_user value
local_cmd.extend(["-u", self.user])
local_cmd.append(self._remote_vmname)
local_cmd.append(shell)
local_cmd = [to_bytes(i, errors="surrogate_or_strict") for i in local_cmd]
display.vvvv("Local cmd: ", local_cmd)
display.vvv(f"RUN {local_cmd}", host=self._remote_vmname)
p = subprocess.Popen(
local_cmd, shell=False, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE
)
# Here we are writing the actual command to the remote bash
p.stdin.write(to_bytes(cmd, errors="surrogate_or_strict"))
stdout, stderr = p.communicate(input=in_data)
return p.returncode, stdout, stderr
def _connect(self):
"""No persistent connection is being maintained."""
super()._connect()
self._connected = True
@ensure_connect # type: ignore # TODO: for some reason, the type infos for ensure_connect suck...
def exec_command(self, cmd, in_data=None, sudoable=False):
"""Run specified command in a running QubesVM"""
super().exec_command(cmd, in_data=in_data, sudoable=sudoable)
display.vvvv(f"CMD IS: {cmd}")
rc, stdout, stderr = self._qubes(cmd)
display.vvvvv(f"STDOUT {stdout!r} STDERR {stderr!r}")
return rc, stdout, stderr
def put_file(self, in_path, out_path):
"""Place a local file located in 'in_path' inside VM at 'out_path'"""
super().put_file(in_path, out_path)
display.vvv(f"PUT {in_path} TO {out_path}", host=self._remote_vmname)
with open(in_path, "rb") as fobj:
source_data = fobj.read()
retcode, dummy, dummy = self._qubes(f'cat > "{out_path}"\n', source_data, "qubes.VMRootShell")
# if qubes.VMRootShell service not supported, fallback to qubes.VMShell and
# hope it will have appropriate permissions
if retcode == 127:
retcode, dummy, dummy = self._qubes(f'cat > "{out_path}"\n', source_data)
if retcode != 0:
raise AnsibleConnectionFailure(f"Failed to put_file to {out_path}")
def fetch_file(self, in_path, out_path):
"""Obtain file specified via 'in_path' from the container and place it at 'out_path'"""
super().fetch_file(in_path, out_path)
display.vvv(f"FETCH {in_path} TO {out_path}", host=self._remote_vmname)
# We are running in dom0
cmd_args_list = ["qvm-run", "--pass-io", self._remote_vmname, f"cat {in_path}"]
with open(out_path, "wb") as fobj:
p = subprocess.Popen(cmd_args_list, shell=False, stdout=fobj)
p.communicate()
if p.returncode != 0:
raise AnsibleConnectionFailure(f"Failed to fetch file to {out_path}")
def close(self):
"""Closing the connection"""
super().close()
self._connected = False
@@ -0,0 +1,125 @@
# Based on local.py (c) 2012, Michael DeHaan <michael.dehaan@gmail.com>
# Based on chroot.py (c) 2013, Maykel Moya <mmoya@speedyrails.com>
# Based on func.py
# Copyright (c) 2014, Michael Scherer <misc@zarb.org>
# Copyright (c) 2017 Ansible Project
# 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
DOCUMENTATION = r"""
author: Michael Scherer (@mscherer) <misc@zarb.org>
name: saltstack
short_description: Allow ansible to piggyback on salt minions
description:
- Run commands or put/fetch files to Salt minions by using the local Salt master as transport.
- Ansible must run directly on the Salt master; this plugin uses C(salt.client.LocalClient)
and does not support connecting to a remote Salt master.
requirements:
- the C(salt) Python package must be installed on the Salt master (the Ansible controller)
options:
remote_addr:
description:
- The Salt minion ID to target.
type: string
default: inventory_hostname
vars:
- name: inventory_hostname
- name: ansible_host
notes:
- Ansible must be run from the Salt master host; the plugin cannot reach a remote Salt master.
- The inventory hostname (or O(remote_addr)) is treated as the Salt minion ID, not as a DNS
name or IP address.
- The Salt master and its minion keys must already be configured and accepted before using
this connection plugin.
- File transfer via P(community.general.saltstack#connection) uses C(hashutil.base64_decodefile)
(put) and C(cp.get_file_str) (fetch); these Salt execution modules must be available on
the targeted minions.
"""
import base64
import os
from ansible import errors
from ansible.plugins.connection import ConnectionBase
HAVE_SALTSTACK = False
try:
import salt.client as sc
HAVE_SALTSTACK = True
except ImportError:
pass
class Connection(ConnectionBase):
"""Salt-based connections"""
has_pipelining = False
# while the name of the product is salt, naming that module salt cause
# trouble with module import
transport = "community.general.saltstack"
def __init__(self, play_context, new_stdin, *args, **kwargs):
super().__init__(play_context, new_stdin, *args, **kwargs)
self.host = self._play_context.remote_addr
def _connect(self):
if not HAVE_SALTSTACK:
raise errors.AnsibleError("saltstack is not installed")
self.client = sc.LocalClient()
self._connected = True
return self
def exec_command(self, cmd, in_data=None, sudoable=False):
"""run a command on the remote minion"""
super().exec_command(cmd, in_data=in_data, sudoable=sudoable)
if in_data:
raise errors.AnsibleError("Internal Error: this module does not support optimized module pipelining")
self._display.vvv(f"EXEC {cmd}", host=self.host)
# need to add 'true;' to work around https://github.com/saltstack/salt/issues/28077
res = self.client.cmd(self.host, "cmd.exec_code_all", ["bash", f"true;{cmd}"])
if self.host not in res:
raise errors.AnsibleError(
f"Minion {self.host} didn't answer, check if salt-minion is running and the name is correct"
)
p = res[self.host]
return p["retcode"], p["stdout"], p["stderr"]
@staticmethod
def _normalize_path(path, prefix):
if not path.startswith(os.path.sep):
path = os.path.join(os.path.sep, path)
normpath = os.path.normpath(path)
return os.path.join(prefix, normpath[1:])
def put_file(self, in_path, out_path):
"""transfer a file from local to remote"""
super().put_file(in_path, out_path)
out_path = self._normalize_path(out_path, "/")
self._display.vvv(f"PUT {in_path} TO {out_path}", host=self.host)
with open(in_path, "rb") as in_fh:
content = in_fh.read()
self.client.cmd(self.host, "hashutil.base64_decodefile", [base64.b64encode(content), out_path])
# TODO test it
def fetch_file(self, in_path, out_path):
"""fetch a file from remote to local"""
super().fetch_file(in_path, out_path)
in_path = self._normalize_path(in_path, "/")
self._display.vvv(f"FETCH {in_path} TO {out_path}", host=self.host)
content = self.client.cmd(self.host, "cp.get_file_str", [in_path])[self.host]
open(out_path, "wb").write(content)
def close(self):
"""terminate the connection; nothing to do here"""
pass
@@ -0,0 +1,819 @@
# Derived from ansible/plugins/connection/proxmox_pct_remote.py (c) 2024 Nils Stein (@mietzen) <github.nstein@mailbox.org>
# Derived from ansible/plugins/connection/paramiko_ssh.py (c) 2012, Michael DeHaan <michael.dehaan@gmail.com>
# Copyright (c) 2025 Rui Lopes (@rgl) <ruilopes.com>
# Copyright (c) 2025 Ansible Project
# 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
DOCUMENTATION = r"""
author: Rui Lopes (@rgl) <ruilopes.com>
name: wsl
short_description: Run tasks in WSL distribution using wsl.exe CLI using SSH
requirements:
- paramiko
description:
- Run commands or put/fetch files to an existing WSL distribution using wsl.exe CLI using SSH.
- Uses the Python SSH implementation (Paramiko) to connect to the WSL host.
version_added: "10.6.0"
options:
remote_addr:
description:
- Address of the remote target.
default: inventory_hostname
type: string
vars:
- name: inventory_hostname
- name: ansible_host
- name: ansible_ssh_host
- name: ansible_paramiko_host
port:
description: Remote port to connect to.
type: int
default: 22
ini:
- section: defaults
key: remote_port
- section: paramiko_connection
key: remote_port
env:
- name: ANSIBLE_REMOTE_PORT
- name: ANSIBLE_REMOTE_PARAMIKO_PORT
vars:
- name: ansible_port
- name: ansible_ssh_port
- name: ansible_paramiko_port
keyword:
- name: port
remote_user:
description:
- User to login/authenticate as.
- Can be set from the CLI with the C(--user) or C(-u) options.
type: string
vars:
- name: ansible_user
- name: ansible_ssh_user
- name: ansible_paramiko_user
env:
- name: ANSIBLE_REMOTE_USER
- name: ANSIBLE_PARAMIKO_REMOTE_USER
ini:
- section: defaults
key: remote_user
- section: paramiko_connection
key: remote_user
keyword:
- name: remote_user
password:
description:
- Secret used to either login the SSH server or as a passphrase for SSH keys that require it.
- Can be set from the CLI with the C(--ask-pass) option.
type: string
vars:
- name: ansible_password
- name: ansible_ssh_pass
- name: ansible_ssh_password
- name: ansible_paramiko_pass
- name: ansible_paramiko_password
secret: true
use_rsa_sha2_algorithms:
description:
- Whether or not to enable RSA SHA2 algorithms for pubkeys and hostkeys.
- On paramiko versions older than 2.9, this only affects hostkeys.
- For behavior matching paramiko<2.9 set this to V(false).
vars:
- name: ansible_paramiko_use_rsa_sha2_algorithms
ini:
- {key: use_rsa_sha2_algorithms, section: paramiko_connection}
env:
- {name: ANSIBLE_PARAMIKO_USE_RSA_SHA2_ALGORITHMS}
default: true
type: boolean
host_key_auto_add:
description: "Automatically add host keys to C(~/.ssh/known_hosts)."
env:
- name: ANSIBLE_PARAMIKO_HOST_KEY_AUTO_ADD
ini:
- key: host_key_auto_add
section: paramiko_connection
type: boolean
look_for_keys:
default: true
description: "Set to V(false) to disable searching for private key files in C(~/.ssh/)."
env:
- name: ANSIBLE_PARAMIKO_LOOK_FOR_KEYS
ini:
- {key: look_for_keys, section: paramiko_connection}
type: boolean
proxy_command:
default: ""
description:
- Proxy information for running the connection through a jumphost.
- This option is supported by paramiko version 1.9.0 or newer.
type: string
env:
- name: ANSIBLE_PARAMIKO_PROXY_COMMAND
ini:
- {key: proxy_command, section: paramiko_connection}
vars:
- name: ansible_paramiko_proxy_command
record_host_keys:
default: true
description: "Save the host keys to a file."
env:
- name: ANSIBLE_PARAMIKO_RECORD_HOST_KEYS
ini:
- section: paramiko_connection
key: record_host_keys
type: boolean
host_key_checking:
description: "Set this to V(false) if you want to avoid host key checking by the underlying tools Ansible uses to connect
to the host."
type: boolean
default: true
env:
- name: ANSIBLE_HOST_KEY_CHECKING
- name: ANSIBLE_SSH_HOST_KEY_CHECKING
- name: ANSIBLE_PARAMIKO_HOST_KEY_CHECKING
ini:
- section: defaults
key: host_key_checking
- section: paramiko_connection
key: host_key_checking
vars:
- name: ansible_host_key_checking
- name: ansible_ssh_host_key_checking
- name: ansible_paramiko_host_key_checking
use_persistent_connections:
description: "Toggles the use of persistence for connections."
type: boolean
default: false
env:
- name: ANSIBLE_USE_PERSISTENT_CONNECTIONS
ini:
- section: defaults
key: use_persistent_connections
banner_timeout:
type: float
default: 30
description:
- Configures, in seconds, the amount of time to wait for the SSH banner to be presented.
- This option is supported by paramiko version 1.15.0 or newer.
ini:
- section: paramiko_connection
key: banner_timeout
env:
- name: ANSIBLE_PARAMIKO_BANNER_TIMEOUT
timeout:
type: int
default: 10
description:
- Number of seconds until the plugin gives up on failing to establish a TCP connection.
- This option is supported by paramiko version 2.2.0 or newer.
ini:
- section: defaults
key: timeout
- section: ssh_connection
key: timeout
- section: paramiko_connection
key: timeout
env:
- name: ANSIBLE_TIMEOUT
- name: ANSIBLE_SSH_TIMEOUT
- name: ANSIBLE_PARAMIKO_TIMEOUT
vars:
- name: ansible_ssh_timeout
- name: ansible_paramiko_timeout
cli:
- name: timeout
lock_file_timeout:
type: int
default: 60
description: Number of seconds until the plugin gives up on trying to write a lock file when writing SSH known host keys.
vars:
- name: ansible_lock_file_timeout
env:
- name: ANSIBLE_LOCK_FILE_TIMEOUT
private_key_file:
description:
- Path to private key file to use for authentication.
type: path
ini:
- section: defaults
key: private_key_file
- section: paramiko_connection
key: private_key_file
env:
- name: ANSIBLE_PRIVATE_KEY_FILE
- name: ANSIBLE_PARAMIKO_PRIVATE_KEY_FILE
vars:
- name: ansible_private_key_file
- name: ansible_ssh_private_key_file
- name: ansible_paramiko_private_key_file
cli:
- name: private_key_file
option: "--private-key"
user_known_hosts_file:
description:
- Path to the user known hosts file.
- Used to verify the ssh hosts keys.
type: path
default: ~/.ssh/known_hosts
ini:
- section: paramiko_connection
key: user_known_hosts_file
vars:
- name: ansible_paramiko_user_known_hosts_file
wsl_distribution:
description:
- WSL distribution name.
type: string
required: true
vars:
- name: wsl_distribution
wsl_remote_ssh_shell_type:
description:
- The shell type expected in the SSH session (not inside the WSL session).
- See also C(ansible_shell_type).
type: string
choices:
- cmd
- powershell
default: cmd
vars:
- name: wsl_remote_ssh_shell_type
version_added: 12.2.0
wsl_user:
description:
- WSL distribution user.
type: string
vars:
- name: wsl_user
become_user:
description:
- WSL distribution user.
type: string
default: root
vars:
- name: become_user
- name: ansible_become_user
become:
description:
- Whether to use the user defined by O(become_user).
type: bool
default: false
vars:
- name: become
- name: ansible_become
"""
EXAMPLES = r"""
# ------------------------
# Inventory: inventory.yml
# ------------------------
---
all:
children:
wsl:
hosts:
example-wsl-ubuntu:
ansible_host: 10.0.0.10
wsl_distribution: ubuntu
wsl_user: ubuntu
vars:
ansible_connection: community.general.wsl
ansible_user: vagrant
# ----------------------
# Playbook: playbook.yml
# ----------------------
---
- name: WSL Example
hosts: wsl
gather_facts: true
become: true
tasks:
- name: Ping
ansible.builtin.ping:
- name: Id (with become false)
become: false
changed_when: false
args:
executable: /bin/bash
ansible.builtin.shell: |
exec 2>&1
set -x
echo "$0"
pwd
id
- name: Id (with become true)
changed_when: false
args:
executable: /bin/bash
ansible.builtin.shell: |
exec 2>&1
set -x
echo "$0"
pwd
id
- name: Reboot
ansible.builtin.reboot:
boot_time_command: systemctl show -p ActiveEnterTimestamp init.scope
"""
import io
import os
import pathlib
import shlex
import tempfile
import traceback
import typing as t
from binascii import hexlify
from subprocess import list2cmdline
from ansible.errors import (
AnsibleAuthenticationFailure,
AnsibleConnectionFailure,
AnsibleError,
)
from ansible.module_utils.common.text.converters import to_bytes, to_native, to_text
from ansible.playbook.play_context import PlayContext
from ansible.plugins.connection import ConnectionBase
from ansible.utils.display import Display
from ansible.utils.path import makedirs_safe
from ansible_collections.community.general.plugins.module_utils._filelock import FileLock, LockTimeout
from ansible_collections.community.general.plugins.module_utils._version import LooseVersion
PARAMIKO_IMPORT_ERR: str | None
try:
import paramiko
from paramiko import MissingHostKeyPolicy
PARAMIKO_IMPORT_ERR = None
except ImportError:
PARAMIKO_IMPORT_ERR = traceback.format_exc()
MissingHostKeyPolicy = object # type: ignore
display = Display()
def authenticity_msg(hostname: str, ktype: str, fingerprint: bytes) -> str:
msg = f"""
paramiko: The authenticity of host '{hostname}' can't be established.
The {ktype} key fingerprint is {to_text(fingerprint)}.
Are you sure you want to continue connecting (yes/no)?
"""
return msg
class MyAddPolicy(MissingHostKeyPolicy):
"""
Based on AutoAddPolicy in paramiko so we can determine when keys are added
and also prompt for input.
Policy for automatically adding the hostname and new host key to the
local L{HostKeys} object, and saving it. This is used by L{SSHClient}.
"""
def __init__(self, connection: Connection) -> None:
self.connection = connection
self._options = connection._options
def missing_host_key(self, client: paramiko.SSHClient, hostname: str, key: paramiko.PKey) -> None:
if all((self.connection.get_option("host_key_checking"), not self.connection.get_option("host_key_auto_add"))):
fingerprint = hexlify(key.get_fingerprint())
ktype = key.get_name()
if self.connection.get_option("use_persistent_connections") or self.connection.force_persistence:
# don't print the prompt string since the user cannot respond
# to the question anyway
raise AnsibleError(authenticity_msg(hostname, ktype, fingerprint)[1:92])
inp = to_text(
display.prompt_until(authenticity_msg(hostname, ktype, fingerprint), private=False),
errors="surrogate_or_strict",
)
if inp.lower() not in ["yes", "y", ""]:
raise AnsibleError("host connection rejected by user")
key._added_by_ansible_this_time = True # type: ignore
# existing implementation below:
client._host_keys.add(hostname, key.get_name(), key) # type: ignore[attr-defined] # TODO: figure out what _host_keys is!
# host keys are actually saved in close() function below
# in order to control ordering.
class Connection(ConnectionBase):
"""SSH based connections (paramiko) to WSL"""
transport = "community.general.wsl"
_log_channel: str | None = None
def __init__(
self, play_context: PlayContext, new_stdin: io.TextIOWrapper | None = None, *args: t.Any, **kwargs: t.Any
):
super().__init__(play_context, new_stdin, *args, **kwargs)
def _set_log_channel(self, name: str) -> None:
"""Mimic paramiko.SSHClient.set_log_channel"""
self._log_channel = name
def _parse_proxy_command(self, port: int = 22) -> dict[str, t.Any]:
proxy_command = self.get_option("proxy_command") or None
sock_kwarg = {}
if proxy_command:
replacers: dict[str, str] = {
"%h": self.get_option("remote_addr"),
"%p": str(port),
"%r": self.get_option("remote_user"),
}
for find, replace in replacers.items():
proxy_command = proxy_command.replace(find, replace)
try:
sock_kwarg = {"sock": paramiko.ProxyCommand(proxy_command)}
display.vvv(
f"CONFIGURE PROXY COMMAND FOR CONNECTION: {proxy_command}", host=self.get_option("remote_addr")
)
except AttributeError:
display.warning(
"Paramiko ProxyCommand support unavailable. "
"Please upgrade to Paramiko 1.9.0 or newer. "
"Not using configured ProxyCommand"
)
return sock_kwarg
def _connect(self) -> Connection:
"""activates the connection object"""
if PARAMIKO_IMPORT_ERR is not None:
raise AnsibleError(f"paramiko is not installed: {to_native(PARAMIKO_IMPORT_ERR)}")
port = self.get_option("port")
display.vvv(
f"ESTABLISH PARAMIKO SSH CONNECTION FOR USER: {self.get_option('remote_user')} on PORT {to_text(port)} TO {self.get_option('remote_addr')}",
host=self.get_option("remote_addr"),
)
ssh = paramiko.SSHClient()
# Set pubkey and hostkey algorithms to disable, the only manipulation allowed currently
# is keeping or omitting rsa-sha2 algorithms
# default_keys: t.Tuple[str] = ()
paramiko_preferred_pubkeys = getattr(paramiko.Transport, "_preferred_pubkeys", ())
paramiko_preferred_hostkeys = getattr(paramiko.Transport, "_preferred_keys", ())
use_rsa_sha2_algorithms = self.get_option("use_rsa_sha2_algorithms")
disabled_algorithms: dict[str, t.Iterable[str]] = {}
if not use_rsa_sha2_algorithms:
if paramiko_preferred_pubkeys:
disabled_algorithms["pubkeys"] = tuple(a for a in paramiko_preferred_pubkeys if "rsa-sha2" in a)
if paramiko_preferred_hostkeys:
disabled_algorithms["keys"] = tuple(a for a in paramiko_preferred_hostkeys if "rsa-sha2" in a)
# override paramiko's default logger name
if self._log_channel is not None:
ssh.set_log_channel(self._log_channel)
self.keyfile = os.path.expanduser(self.get_option("user_known_hosts_file"))
if self.get_option("host_key_checking"):
for ssh_known_hosts in ("/etc/ssh/ssh_known_hosts", "/etc/openssh/ssh_known_hosts", self.keyfile):
try:
ssh.load_system_host_keys(ssh_known_hosts)
break
except OSError:
pass # file was not found, but not required to function
except paramiko.hostkeys.InvalidHostKey as e:
raise AnsibleConnectionFailure(f"Invalid host key: {to_text(e.line)}") from e
try:
ssh.load_system_host_keys()
except paramiko.hostkeys.InvalidHostKey as e:
raise AnsibleConnectionFailure(f"Invalid host key: {to_text(e.line)}") from e
ssh_connect_kwargs = self._parse_proxy_command(port)
ssh.set_missing_host_key_policy(MyAddPolicy(self))
conn_password = self.get_option("password")
allow_agent = True
if conn_password is not None:
allow_agent = False
try:
key_filename = None
if self.get_option("private_key_file"):
key_filename = os.path.expanduser(self.get_option("private_key_file"))
# paramiko 2.2 introduced auth_timeout parameter
if LooseVersion(paramiko.__version__) >= LooseVersion("2.2.0"):
ssh_connect_kwargs["auth_timeout"] = self.get_option("timeout")
# paramiko 1.15 introduced banner timeout parameter
if LooseVersion(paramiko.__version__) >= LooseVersion("1.15.0"):
ssh_connect_kwargs["banner_timeout"] = self.get_option("banner_timeout")
ssh.connect(
self.get_option("remote_addr").lower(),
username=self.get_option("remote_user"),
allow_agent=allow_agent,
look_for_keys=self.get_option("look_for_keys"),
key_filename=key_filename,
password=conn_password,
timeout=self.get_option("timeout"),
port=port,
disabled_algorithms=disabled_algorithms,
**ssh_connect_kwargs,
)
except paramiko.ssh_exception.BadHostKeyException as e:
raise AnsibleConnectionFailure(f"host key mismatch for {to_text(e.hostname)}") from e
except paramiko.ssh_exception.AuthenticationException as e:
msg = f"Failed to authenticate: {e}"
raise AnsibleAuthenticationFailure(msg) from e
except Exception as e:
msg = to_text(e)
if "PID check failed" in msg:
raise AnsibleError(
"paramiko version issue, please upgrade paramiko on the machine running ansible"
) from e
elif "Private key file is encrypted" in msg:
msg = (
f"ssh {self.get_option('remote_user')}@{self.get_options('remote_addr')}:{port} : "
f"{msg}\nTo connect as a different user, use -u <username>."
)
raise AnsibleConnectionFailure(msg) from e
else:
raise AnsibleConnectionFailure(msg) from e
self.ssh = ssh
self._connected = True
return self
def _any_keys_added(self) -> bool:
for host_keys in self.ssh._host_keys.values(): # type: ignore[attr-defined] # TODO: figure out what _host_keys is!
for key in host_keys.values():
added_this_time = getattr(key, "_added_by_ansible_this_time", False)
if added_this_time:
return True
return False
def _save_ssh_host_keys(self, filename: str) -> None:
"""
not using the paramiko save_ssh_host_keys function as we want to add new SSH keys at the bottom so folks
don't complain about it :)
"""
if not self._any_keys_added():
return
path = os.path.expanduser("~/.ssh")
makedirs_safe(path)
with open(filename, "w") as f:
for hostname, keys in self.ssh._host_keys.items(): # type: ignore[attr-defined] # TODO: figure out what _host_keys is!
for keytype, key in keys.items():
# was f.write
added_this_time = getattr(key, "_added_by_ansible_this_time", False)
if not added_this_time:
f.write(f"{hostname} {keytype} {key.get_base64()}\n")
for hostname, keys in self.ssh._host_keys.items(): # type: ignore[attr-defined] # TODO: figure out what _host_keys is!
for keytype, key in keys.items():
added_this_time = getattr(key, "_added_by_ansible_this_time", False)
if added_this_time:
f.write(f"{hostname} {keytype} {key.get_base64()}\n")
def _build_wsl_command(self, cmd: str) -> str:
wsl_distribution = self.get_option("wsl_distribution")
become = self.get_option("become")
become_user = self.get_option("become_user")
wsl_remote_ssh_shell_type = self.get_option("wsl_remote_ssh_shell_type")
is_integration_test = os.getenv("_ANSIBLE_TEST_WSL_CONNECTION_PLUGIN_WAERI5TEPHEESHA2FAE8")
if "%" in cmd:
if wsl_remote_ssh_shell_type == "powershell":
# there is no universal way to escape '%' here
# if this is raised, add a workaround to allow the specific situation (if possible)
raise AnsibleError("The command contains '%', cannot safely escape it for Powershell")
else:
cmd = cmd.replace("%", "^%")
if become and become_user:
wsl_user = become_user
else:
wsl_user = self.get_option("wsl_user")
args = ["wsl.exe"]
if wsl_remote_ssh_shell_type == "powershell" and not is_integration_test:
# Powershell stop-parsing token, treat the rest as arguments to the native command wsl.exe
args.append("--%")
args.extend(["--distribution", wsl_distribution])
if wsl_user:
args.extend(["--user", wsl_user])
args.extend(["--"])
args.extend(shlex.split(cmd))
if is_integration_test:
return shlex.join(args)
else:
return list2cmdline(args) # see https://github.com/python/cpython/blob/3.11/Lib/subprocess.py#L576
def exec_command(self, cmd: str, in_data: bytes | None = None, sudoable: bool = True) -> tuple[int, bytes, bytes]:
"""run a command on inside a WSL distribution"""
cmd = self._build_wsl_command(cmd)
super().exec_command(cmd, in_data=in_data, sudoable=sudoable) # type: ignore[safe-super]
bufsize = 4096
try:
transport = self.ssh.get_transport()
if transport is None:
raise ValueError("Transport not available")
transport.set_keepalive(5)
chan = transport.open_session()
except Exception as e:
text_e = to_text(e)
msg = "Failed to open session"
if text_e:
msg += f": {text_e}"
raise AnsibleConnectionFailure(to_native(msg)) from e
display.vvv(f"EXEC {cmd}", host=self.get_option("remote_addr"))
cmd_b = to_bytes(cmd, errors="surrogate_or_strict")
no_prompt_out = b""
no_prompt_err = b""
become_output = b""
try:
chan.exec_command(cmd_b)
if self.become and self.become.expect_prompt():
password_prompt = False
become_success = False
while not (become_success or password_prompt):
display.debug("Waiting for Privilege Escalation input")
chunk = chan.recv(bufsize)
display.debug(f"chunk is: {to_text(chunk)}")
if not chunk:
if b"unknown user" in become_output:
n_become_user = to_native(self.become.get_option("become_user"))
raise AnsibleError(f"user {n_become_user} does not exist")
else:
break
# raise AnsibleError('ssh connection closed waiting for password prompt')
become_output += chunk
# need to check every line because we might get lectured
# and we might get the middle of a line in a chunk
for line in become_output.splitlines(True):
if self.become.check_success(line):
become_success = True
break
elif self.become.check_password_prompt(line):
password_prompt = True
break
if password_prompt:
if self.become:
become_pass = self.become.get_option("become_pass")
chan.sendall(to_bytes(f"{become_pass}\n", errors="surrogate_or_strict"))
else:
raise AnsibleError("A password is required but none was supplied")
else:
no_prompt_out += become_output
no_prompt_err += become_output
if in_data:
for i in range(0, len(in_data), bufsize):
chan.send(in_data[i : i + bufsize])
chan.shutdown_write()
elif in_data == b"":
chan.shutdown_write()
except TimeoutError as e:
raise AnsibleError(f"ssh timed out waiting for privilege escalation.\n{to_text(become_output)}") from e
stdout = b"".join(chan.makefile("rb", bufsize))
stderr = b"".join(chan.makefile_stderr("rb", bufsize))
returncode = chan.recv_exit_status()
# NB the full english error message is:
# 'wsl.exe' is not recognized as an internal or external command,
# operable program or batch file.
if "'wsl.exe' is not recognized" in stderr.decode("utf-8"):
raise AnsibleError(f"wsl.exe not found in path of host: {to_text(self.get_option('remote_addr'))}")
return (returncode, no_prompt_out + stdout, no_prompt_out + stderr)
def put_file(self, in_path: str, out_path: str) -> None:
"""transfer a file from local to remote"""
display.vvv(f"PUT {in_path} TO {out_path}", host=self.get_option("remote_addr"))
try:
with open(in_path, "rb") as f:
data = f.read()
returncode, stdout, stderr = self.exec_command(
f"{self._shell.executable} -c {self._shell.quote(f'cat > {out_path}')}",
in_data=data,
sudoable=False,
)
if returncode != 0:
if "cat: not found" in stderr.decode("utf-8"):
raise AnsibleError(
f"cat not found in path of WSL distribution: {to_text(self.get_option('wsl_distribution'))}"
)
raise AnsibleError(f"{to_text(stdout)}\n{to_text(stderr)}")
except Exception as e:
raise AnsibleError(f"error occurred while putting file from {in_path} to {out_path}!\n{to_text(e)}") from e
def fetch_file(self, in_path: str, out_path: str) -> None:
"""save a remote file to the specified path"""
display.vvv(f"FETCH {in_path} TO {out_path}", host=self.get_option("remote_addr"))
try:
returncode, stdout, stderr = self.exec_command(
f"{self._shell.executable} -c {self._shell.quote(f'cat {in_path}')}", sudoable=False
)
if returncode != 0:
if "cat: not found" in stderr.decode("utf-8"):
raise AnsibleError(
f"cat not found in path of WSL distribution: {to_text(self.get_option('wsl_distribution'))}"
)
raise AnsibleError(f"{to_text(stdout)}\n{to_text(stderr)}")
with open(out_path, "wb") as f:
f.write(stdout)
except Exception as e:
raise AnsibleError(f"error occurred while fetching file from {in_path} to {out_path}!\n{to_text(e)}") from e
def reset(self) -> None:
"""reset the connection"""
if not self._connected:
return
self.close()
self._connect()
def close(self) -> None:
"""terminate the connection"""
if self.get_option("host_key_checking") and self.get_option("record_host_keys") and self._any_keys_added():
# add any new SSH host keys -- warning -- this could be slow
# (This doesn't acquire the connection lock because it needs
# to exclude only other known_hosts writers, not connections
# that are starting up.)
lockfile = os.path.basename(self.keyfile)
dirname = os.path.dirname(self.keyfile)
makedirs_safe(dirname)
tmp_keyfile_name = None
try:
with FileLock().lock_file(lockfile, dirname, self.get_option("lock_file_timeout")):
# just in case any were added recently
self.ssh.load_system_host_keys()
self.ssh._host_keys.update(self.ssh._system_host_keys) # type: ignore[attr-defined] # TODO this is a HACK!
# gather information about the current key file, so
# we can ensure the new file has the correct mode/owner
key_dir = os.path.dirname(self.keyfile)
if os.path.exists(self.keyfile):
key_stat = os.stat(self.keyfile)
mode = key_stat.st_mode & 0o777
uid = key_stat.st_uid
gid = key_stat.st_gid
else:
mode = 0o644
uid = os.getuid()
gid = os.getgid()
# Save the new keys to a temporary file and move it into place
# rather than rewriting the file. We set delete=False because
# the file will be moved into place rather than cleaned up.
with tempfile.NamedTemporaryFile(dir=key_dir, delete=False) as tmp_keyfile:
tmp_keyfile_name = tmp_keyfile.name
os.chmod(tmp_keyfile_name, mode)
os.chown(tmp_keyfile_name, uid, gid)
self._save_ssh_host_keys(tmp_keyfile_name)
os.rename(tmp_keyfile_name, self.keyfile)
except LockTimeout as e:
raise AnsibleError(
f"writing lock file for {self.keyfile} ran in to the timeout of {self.get_option('lock_file_timeout')}s"
) from e
except paramiko.hostkeys.InvalidHostKey as e:
raise AnsibleConnectionFailure(f"Invalid host key: {e.line}") from e
except Exception as e:
# unable to save keys, including scenario when key was invalid
# and caught earlier
raise AnsibleError(f"error occurred while writing SSH host keys!\n{to_text(e)}") from e
finally:
if tmp_keyfile_name is not None:
pathlib.Path(tmp_keyfile_name).unlink(missing_ok=True)
self.ssh.close()
self._connected = False
@@ -0,0 +1,202 @@
# Based on local.py (c) 2012, Michael DeHaan <michael.dehaan@gmail.com>
# and chroot.py (c) 2013, Maykel Moya <mmoya@speedyrails.com>
# and jail.py (c) 2013, Michael Scherer <misc@zarb.org>
# (c) 2015, Dagobert Michelsen <dam@baltic-online.de>
# (c) 2015, Toshio Kuratomi <tkuratomi@ansible.com>
# Copyright (c) 2017 Ansible Project
# 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
DOCUMENTATION = r"""
author: Ansible Core Team
name: zone
short_description: Run tasks in a zone instance
description:
- Run commands or put/fetch files to an existing zone.
options:
remote_addr:
description:
- Zone identifier.
type: string
default: inventory_hostname
vars:
- name: ansible_host
- name: ansible_zone_host
"""
import os
import os.path
import subprocess
import traceback
from shlex import quote as shlex_quote
from ansible.errors import AnsibleError
from ansible.module_utils.common.process import get_bin_path
from ansible.module_utils.common.text.converters import to_bytes
from ansible.plugins.connection import BUFSIZE, ConnectionBase
from ansible.utils.display import Display
display = Display()
class Connection(ConnectionBase):
"""Local zone based connections"""
transport = "community.general.zone"
has_pipelining = True
has_tty = False
def __init__(self, play_context, new_stdin, *args, **kwargs):
super().__init__(play_context, new_stdin, *args, **kwargs)
self.zone = self._play_context.remote_addr
if os.geteuid() != 0:
raise AnsibleError("zone connection requires running as root")
self.zoneadm_cmd = to_bytes(self._search_executable("zoneadm"))
self.zlogin_cmd = to_bytes(self._search_executable("zlogin"))
if self.zone not in self.list_zones():
raise AnsibleError(f"incorrect zone name {self.zone}")
@staticmethod
def _search_executable(executable):
try:
return get_bin_path(executable)
except ValueError as e:
raise AnsibleError(f"{executable} command not found in PATH") from e
def list_zones(self):
process = subprocess.Popen(
[self.zoneadm_cmd, "list", "-ip"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE
)
zones = []
for line in process.stdout.readlines():
# 1:work:running:/zones/work:3126dc59-9a07-4829-cde9-a816e4c5040e:native:shared
s = line.split(":")
if s[1] != "global":
zones.append(s[1])
return zones
def get_zone_path(self):
# solaris10vm# zoneadm -z cswbuild list -p
# -:cswbuild:installed:/zones/cswbuild:479f3c4b-d0c6-e97b-cd04-fd58f2c0238e:native:shared
process = subprocess.Popen(
[self.zoneadm_cmd, "-z", to_bytes(self.zone), "list", "-p"],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
# stdout, stderr = p.communicate()
path = process.stdout.readlines()[0].split(":")[3]
return f"{path}/root"
def _connect(self):
"""connect to the zone; nothing to do here"""
super()._connect()
if not self._connected:
display.vvv("THIS IS A LOCAL ZONE DIR", host=self.zone)
self._connected = True
def _buffered_exec_command(self, cmd, stdin=subprocess.PIPE):
"""run a command on the zone. This is only needed for implementing
put_file() get_file() so that we don't have to read the whole file
into memory.
compared to exec_command() it looses some niceties like being able to
return the process's exit code immediately.
"""
# NOTE: zlogin invokes a shell (just like ssh does) so we do not pass
# this through /bin/sh -c here. Instead it goes through the shell
# that zlogin selects.
local_cmd = [self.zlogin_cmd, self.zone, cmd]
local_cmd = map(to_bytes, local_cmd)
display.vvv(f"EXEC {local_cmd}", host=self.zone)
p = subprocess.Popen(local_cmd, shell=False, stdin=stdin, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
return p
def exec_command(self, cmd, in_data=None, sudoable=False):
"""run a command on the zone"""
super().exec_command(cmd, in_data=in_data, sudoable=sudoable)
p = self._buffered_exec_command(cmd)
stdout, stderr = p.communicate(in_data)
return p.returncode, stdout, stderr
def _prefix_login_path(self, remote_path):
"""Make sure that we put files into a standard path
If a path is relative, then we need to choose where to put it.
ssh chooses $HOME but we aren't guaranteed that a home dir will
exist in any given chroot. So for now we're choosing "/" instead.
This also happens to be the former default.
Can revisit using $HOME instead if it is a problem
"""
if not remote_path.startswith(os.path.sep):
remote_path = os.path.join(os.path.sep, remote_path)
return os.path.normpath(remote_path)
def put_file(self, in_path, out_path):
"""transfer a file from local to zone"""
super().put_file(in_path, out_path)
display.vvv(f"PUT {in_path} TO {out_path}", host=self.zone)
out_path = shlex_quote(self._prefix_login_path(out_path))
try:
with open(in_path, "rb") as in_file:
if not os.fstat(in_file.fileno()).st_size:
count = " count=0"
else:
count = ""
try:
p = self._buffered_exec_command(f"dd of={out_path} bs={BUFSIZE}{count}", stdin=in_file)
except OSError as e:
raise AnsibleError("jail connection requires dd command in the jail") from e
try:
stdout, stderr = p.communicate()
except Exception as e:
traceback.print_exc()
raise AnsibleError(f"failed to transfer file {in_path} to {out_path}") from e
if p.returncode != 0:
raise AnsibleError(f"failed to transfer file {in_path} to {out_path}:\n{stdout}\n{stderr}")
except OSError as e:
raise AnsibleError(f"file or module does not exist at: {in_path}") from e
def fetch_file(self, in_path, out_path):
"""fetch a file from zone to local"""
super().fetch_file(in_path, out_path)
display.vvv(f"FETCH {in_path} TO {out_path}", host=self.zone)
in_path = shlex_quote(self._prefix_login_path(in_path))
try:
p = self._buffered_exec_command(f"dd if={in_path} bs={BUFSIZE}")
except OSError as e:
raise AnsibleError("zone connection requires dd command in the zone") from e
with open(out_path, "wb+") as out_file:
try:
chunk = p.stdout.read(BUFSIZE)
while chunk:
out_file.write(chunk)
chunk = p.stdout.read(BUFSIZE)
except Exception as e:
traceback.print_exc()
raise AnsibleError(f"failed to transfer file {in_path} to {out_path}") from e
stdout, stderr = p.communicate()
if p.returncode != 0:
raise AnsibleError(f"failed to transfer file {in_path} to {out_path}:\n{stdout}\n{stderr}")
def close(self):
"""terminate the connection; nothing to do here"""
super().close()
self._connected = False