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
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:
+205
@@ -0,0 +1,205 @@
|
||||
# Copyright (c) 2020, quidame <quidame@poivron.org>
|
||||
# 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 time
|
||||
import typing as t
|
||||
|
||||
from ansible.errors import AnsibleActionFail, AnsibleConnectionFailure
|
||||
from ansible.plugins.action import ActionBase
|
||||
from ansible.utils.display import Display
|
||||
from ansible.utils.vars import merge_hash
|
||||
|
||||
display = Display()
|
||||
|
||||
|
||||
class ActionModule(ActionBase):
|
||||
# Keep internal params away from user interactions
|
||||
_VALID_ARGS = frozenset(("path", "state", "table", "noflush", "counters", "modprobe", "ip_version", "wait"))
|
||||
DEFAULT_SUDOABLE = True
|
||||
|
||||
@staticmethod
|
||||
def msg_error__async_and_poll_not_zero(task_poll, task_async, max_timeout) -> str:
|
||||
return (
|
||||
"This module doesn't support async>0 and poll>0 when its 'state' param "
|
||||
"is set to 'restored'. To enable its rollback feature (that needs the "
|
||||
"module to run asynchronously on the remote), please set task attribute "
|
||||
f"'poll' (={task_poll}) to 0, and 'async' (={task_async}) to a value >2 and not greater than "
|
||||
f"'ansible_timeout' (={max_timeout}) (recommended)."
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def msg_warning__no_async_is_no_rollback(task_poll, task_async, max_timeout) -> str:
|
||||
return (
|
||||
"Attempts to restore iptables state without rollback in case of mistake "
|
||||
"may lead the ansible controller to loose access to the hosts and never "
|
||||
"regain it before fixing firewall rules through a serial console, or any "
|
||||
f"other way except SSH. Please set task attribute 'poll' (={task_poll}) to 0, and "
|
||||
f"'async' (={task_async}) to a value >2 and not greater than 'ansible_timeout' (={max_timeout}) "
|
||||
"(recommended)."
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def msg_warning__async_greater_than_timeout(task_poll, task_async, max_timeout) -> str:
|
||||
return (
|
||||
"You attempt to restore iptables state with rollback in case of mistake, "
|
||||
"but with settings that will lead this rollback to happen AFTER that the "
|
||||
"controller will reach its own timeout. Please set task attribute 'poll' "
|
||||
f"(={task_poll}) to 0, and 'async' (={task_async}) to a value >2 and not greater than "
|
||||
f"'ansible_timeout' (={max_timeout}) (recommended)."
|
||||
)
|
||||
|
||||
def _async_result(
|
||||
self, async_status_args: dict[str, t.Any], task_vars: dict[str, t.Any], timeout: int
|
||||
) -> dict[str, t.Any]:
|
||||
"""
|
||||
Retrieve results of the asynchronous task, and display them in place of
|
||||
the async wrapper results (those with the ansible_job_id key).
|
||||
"""
|
||||
async_status = self._task.copy()
|
||||
async_status.args = async_status_args
|
||||
async_status.action = "ansible.builtin.async_status"
|
||||
async_status.async_val = 0
|
||||
async_action = self._shared_loader_obj.action_loader.get(
|
||||
async_status.action,
|
||||
task=async_status,
|
||||
connection=self._connection,
|
||||
play_context=self._play_context,
|
||||
loader=self._loader,
|
||||
templar=self._templar,
|
||||
shared_loader_obj=self._shared_loader_obj,
|
||||
)
|
||||
|
||||
if async_status.args["mode"] == "cleanup":
|
||||
return async_action.run(task_vars=task_vars)
|
||||
|
||||
# At least one iteration is required, even if timeout is 0.
|
||||
for dummy in range(max(1, timeout)):
|
||||
async_result = async_action.run(task_vars=task_vars)
|
||||
if async_result.get("finished", 0) == 1:
|
||||
break
|
||||
time.sleep(min(1, timeout))
|
||||
|
||||
return async_result
|
||||
|
||||
def run(self, tmp: str | None = None, task_vars: dict[str, t.Any] | None = None) -> dict[str, t.Any]:
|
||||
self._supports_check_mode = True
|
||||
self._supports_async = True
|
||||
|
||||
if task_vars is None:
|
||||
task_vars = {}
|
||||
|
||||
result = super().run(tmp, task_vars)
|
||||
del tmp # tmp no longer has any effect
|
||||
|
||||
if not result.get("skipped"):
|
||||
# FUTURE: better to let _execute_module calculate this internally?
|
||||
wrap_async = self._task.async_val and not self._connection.has_native_async
|
||||
|
||||
# Set short names for values we'll have to compare or reuse
|
||||
task_poll = self._task.poll
|
||||
task_async = self._task.async_val
|
||||
check_mode = self._play_context.check_mode
|
||||
max_timeout = self._connection._play_context.timeout
|
||||
module_args = self._task.args
|
||||
|
||||
async_status_args = {}
|
||||
starter_cmd = None
|
||||
confirm_cmd = None
|
||||
|
||||
if module_args.get("state", None) == "restored":
|
||||
if not wrap_async:
|
||||
if not check_mode:
|
||||
display.warning(self.msg_error__async_and_poll_not_zero(task_poll, task_async, max_timeout))
|
||||
elif task_poll:
|
||||
raise AnsibleActionFail(
|
||||
self.msg_warning__no_async_is_no_rollback(task_poll, task_async, max_timeout)
|
||||
)
|
||||
else:
|
||||
if task_async > max_timeout and not check_mode:
|
||||
display.warning(
|
||||
self.msg_warning__async_greater_than_timeout(task_poll, task_async, max_timeout)
|
||||
)
|
||||
|
||||
# inject the async directory based on the shell option into the
|
||||
# module args
|
||||
async_dir = self.get_shell_option("async_dir", default="~/.ansible_async")
|
||||
|
||||
# Bind the loop max duration to consistent values on both
|
||||
# remote and local sides (if not the same, make the loop
|
||||
# longer on the controller); and set a backup file path.
|
||||
module_args["_timeout"] = task_async
|
||||
module_args["_back"] = f"{async_dir}/iptables.state"
|
||||
async_status_args = dict(mode="status")
|
||||
confirm_cmd = f"rm -f {module_args['_back']}"
|
||||
starter_cmd = f"touch {module_args['_back']}.starter"
|
||||
remaining_time = max(task_async, max_timeout)
|
||||
|
||||
# do work!
|
||||
result = merge_hash(
|
||||
result, self._execute_module(module_args=module_args, task_vars=task_vars, wrap_async=wrap_async)
|
||||
)
|
||||
|
||||
# Then the 3-steps "go ahead or rollback":
|
||||
# 1. Catch early errors of the module (in asynchronous task) if any.
|
||||
# Touch a file on the target to signal the module to process now.
|
||||
# 2. Reset connection to ensure a persistent one will not be reused.
|
||||
# 3. Confirm the restored state by removing the backup on the remote.
|
||||
# Retrieve the results of the asynchronous task to return them.
|
||||
if starter_cmd is not None and confirm_cmd is not None:
|
||||
async_status_args["jid"] = result.get("ansible_job_id", None)
|
||||
if async_status_args["jid"] is None:
|
||||
raise AnsibleActionFail("Unable to get 'ansible_job_id'.")
|
||||
|
||||
# Catch early errors due to missing mandatory option, bad
|
||||
# option type/value, missing required system command, etc.
|
||||
result = merge_hash(result, self._async_result(async_status_args, task_vars, 0))
|
||||
|
||||
# The module is aware to not process the main iptables-restore
|
||||
# command before finding (and deleting) the 'starter' cookie on
|
||||
# the host, so the previous query will not reach ssh timeout.
|
||||
self._low_level_execute_command(starter_cmd, sudoable=self.DEFAULT_SUDOABLE)
|
||||
|
||||
# As the main command is not yet executed on the target, here
|
||||
# 'finished' means 'failed before main command be executed'.
|
||||
if not result["finished"]:
|
||||
try:
|
||||
self._connection.reset()
|
||||
except AttributeError:
|
||||
pass
|
||||
|
||||
for dummy in range(max_timeout):
|
||||
time.sleep(1)
|
||||
remaining_time -= 1
|
||||
# - AnsibleConnectionFailure covers rejected requests (i.e.
|
||||
# by rules with '--jump REJECT')
|
||||
# - ansible_timeout is able to cover dropped requests (due
|
||||
# to a rule or policy DROP) if not lower than async_val.
|
||||
try:
|
||||
self._low_level_execute_command(confirm_cmd, sudoable=self.DEFAULT_SUDOABLE)
|
||||
break
|
||||
except AnsibleConnectionFailure:
|
||||
continue
|
||||
|
||||
result = merge_hash(result, self._async_result(async_status_args, task_vars, remaining_time))
|
||||
|
||||
# Cleanup async related stuff and internal params
|
||||
for key in ("ansible_job_id", "results_file", "started", "finished"):
|
||||
if result.get(key):
|
||||
del result[key]
|
||||
|
||||
if result.get("invocation", {}).get("module_args"):
|
||||
for key in ("_back", "_timeout", "_async_dir", "jid"):
|
||||
if result["invocation"]["module_args"].get(key):
|
||||
del result["invocation"]["module_args"][key]
|
||||
|
||||
async_status_args["mode"] = "cleanup"
|
||||
self._async_result(async_status_args, task_vars, 0)
|
||||
|
||||
if not wrap_async:
|
||||
# remove a temporary path we created
|
||||
self._remove_tmp_path(self._connection._shell.tmpdir)
|
||||
|
||||
return result
|
||||
+225
@@ -0,0 +1,225 @@
|
||||
# Copyright (c) 2020, Amin Vakil <info@aminvakil.com>
|
||||
# Copyright (c) 2016-2018, Matt Davis <mdavis@ansible.com>
|
||||
# Copyright (c) 2018, Sam Doran <sdoran@redhat.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 typing as t
|
||||
|
||||
from ansible.errors import AnsibleConnectionFailure, AnsibleError
|
||||
from ansible.module_utils.common.collections import is_string
|
||||
from ansible.module_utils.common.text.converters import to_native, to_text
|
||||
from ansible.plugins.action import ActionBase
|
||||
from ansible.utils.display import Display
|
||||
|
||||
if t.TYPE_CHECKING:
|
||||
|
||||
class Distribution(t.TypedDict):
|
||||
name: str
|
||||
version: str
|
||||
family: str
|
||||
|
||||
|
||||
display = Display()
|
||||
|
||||
|
||||
class TimedOutException(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class ActionModule(ActionBase):
|
||||
TRANSFERS_FILES = False
|
||||
_VALID_ARGS = frozenset(("msg", "delay", "search_paths"))
|
||||
|
||||
DEFAULT_CONNECT_TIMEOUT = None
|
||||
DEFAULT_PRE_SHUTDOWN_DELAY = 0
|
||||
DEFAULT_SHUTDOWN_MESSAGE = "Shut down initiated by Ansible"
|
||||
DEFAULT_SHUTDOWN_COMMAND = "shutdown"
|
||||
DEFAULT_SHUTDOWN_COMMAND_ARGS = '-h {delay_min} "{message}"'
|
||||
DEFAULT_SUDOABLE = True
|
||||
|
||||
SHUTDOWN_COMMANDS = {
|
||||
"alpine": "poweroff",
|
||||
"vmkernel": "halt",
|
||||
}
|
||||
|
||||
SHUTDOWN_COMMAND_ARGS = {
|
||||
"alpine": "",
|
||||
"void": '-h +{delay_min} "{message}"',
|
||||
"freebsd": '-p +{delay_sec}s "{message}"',
|
||||
"linux": DEFAULT_SHUTDOWN_COMMAND_ARGS,
|
||||
"macosx": '-h +{delay_min} "{message}"',
|
||||
"openbsd": '-h +{delay_min} "{message}"',
|
||||
"solaris": '-y -g {delay_sec} -i 5 "{message}"',
|
||||
"sunos": '-y -g {delay_sec} -i 5 "{message}"',
|
||||
"vmkernel": "-d {delay_sec}",
|
||||
"aix": "-Fh",
|
||||
}
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
|
||||
@property
|
||||
def delay(self):
|
||||
return self._check_delay("delay", self.DEFAULT_PRE_SHUTDOWN_DELAY)
|
||||
|
||||
def _check_delay(self, key: str, default: int) -> int:
|
||||
"""Ensure that the value is positive or zero"""
|
||||
value = int(self._task.args.get(key, default))
|
||||
if value < 0:
|
||||
value = 0
|
||||
return value
|
||||
|
||||
@staticmethod
|
||||
def _get_value_from_facts(data: dict[str, str], distribution: Distribution, default_value: str) -> str:
|
||||
"""Get dist+version specific args first, then distribution, then family, lastly use default"""
|
||||
return data.get(
|
||||
distribution["name"] + distribution["version"],
|
||||
data.get(distribution["name"], data.get(distribution["family"], default_value)),
|
||||
)
|
||||
|
||||
def get_distribution(self, task_vars: dict[str, t.Any]) -> Distribution:
|
||||
# FIXME: only execute the module if we don't already have the facts we need
|
||||
display.debug(f"{self._task.action}: running setup module to get distribution")
|
||||
module_output = self._execute_module(
|
||||
task_vars=task_vars, module_name="ansible.legacy.setup", module_args={"gather_subset": "min"}
|
||||
)
|
||||
try:
|
||||
if module_output.get("failed", False):
|
||||
raise AnsibleError(
|
||||
f"Failed to determine system distribution. {to_native(module_output['module_stdout'])}, {to_native(module_output['module_stderr'])}"
|
||||
)
|
||||
# For some reason, ansible-core insists of using "object" for "arbitrary JSON", which makes it very awkward to use the result...
|
||||
ansible_facts: dict[str, t.Any] = module_output["ansible_facts"] # type: ignore
|
||||
distribution: Distribution = {
|
||||
"name": ansible_facts["ansible_distribution"].lower(),
|
||||
"version": to_text(ansible_facts["ansible_distribution_version"].split(".")[0]),
|
||||
"family": to_text(ansible_facts["ansible_os_family"].lower()),
|
||||
}
|
||||
display.debug(f"{self._task.action}: distribution: {distribution}")
|
||||
return distribution
|
||||
except KeyError as ke:
|
||||
raise AnsibleError(f'Failed to get distribution information. Missing "{ke.args[0]}" in output.') from ke
|
||||
|
||||
def get_shutdown_command(self, task_vars: dict[str, t.Any], distribution: Distribution) -> str:
|
||||
def find_command(command: str, find_search_paths: list[str]) -> list[str]:
|
||||
display.debug(
|
||||
f'{self._task.action}: running find module looking in {find_search_paths} to get path for "{command}"'
|
||||
)
|
||||
find_result = self._execute_module(
|
||||
task_vars=task_vars,
|
||||
# prevent collection search by calling with ansible.legacy (still allows library/ override of find)
|
||||
module_name="ansible.legacy.find",
|
||||
module_args={"paths": find_search_paths, "patterns": [command], "file_type": "any"},
|
||||
)
|
||||
files: list[dict[str, t.Any]] = find_result["files"] # type: ignore
|
||||
return [x["path"] for x in files]
|
||||
|
||||
shutdown_bin = self._get_value_from_facts(self.SHUTDOWN_COMMANDS, distribution, self.DEFAULT_SHUTDOWN_COMMAND)
|
||||
default_search_paths = ["/sbin", "/usr/sbin", "/usr/local/sbin"]
|
||||
search_paths = self._task.args.get("search_paths", default_search_paths)
|
||||
|
||||
# FIXME: switch all this to user arg spec validation methods when they are available
|
||||
# Convert bare strings to a list
|
||||
if is_string(search_paths):
|
||||
search_paths = [search_paths]
|
||||
|
||||
try:
|
||||
incorrect_type = any(not is_string(x) for x in search_paths)
|
||||
if not isinstance(search_paths, list) or incorrect_type:
|
||||
raise TypeError
|
||||
except TypeError as e:
|
||||
# Error if we didn't get a list
|
||||
err_msg = f"'search_paths' must be a string or flat list of strings, got {search_paths}"
|
||||
raise AnsibleError(err_msg) from e
|
||||
|
||||
full_path = find_command(shutdown_bin, search_paths) # find the path to the shutdown command
|
||||
if not full_path: # if we could not find the shutdown command
|
||||
# tell the user we will try with systemd
|
||||
display.vvv(
|
||||
f'Unable to find command "{shutdown_bin}" in search paths: {search_paths}, will attempt a shutdown using systemd directly.'
|
||||
)
|
||||
systemctl_search_paths = ["/bin", "/usr/bin"]
|
||||
full_path = find_command("systemctl", systemctl_search_paths) # find the path to the systemctl command
|
||||
if not full_path: # if we couldn't find systemctl
|
||||
raise AnsibleError(
|
||||
f'Could not find command "{shutdown_bin}" in search paths: {search_paths} or systemctl'
|
||||
f" command in search paths: {systemctl_search_paths}, unable to shutdown."
|
||||
) # we give up here
|
||||
else:
|
||||
return f"{full_path[0]} poweroff" # done, since we cannot use args with systemd shutdown
|
||||
|
||||
# systemd case taken care of, here we add args to the command
|
||||
args = self._get_value_from_facts(self.SHUTDOWN_COMMAND_ARGS, distribution, self.DEFAULT_SHUTDOWN_COMMAND_ARGS)
|
||||
# Convert seconds to minutes. If less that 60, set it to 0.
|
||||
delay_sec = self.delay
|
||||
shutdown_message = self._task.args.get("msg", self.DEFAULT_SHUTDOWN_MESSAGE)
|
||||
|
||||
af = args.format(delay_sec=delay_sec, delay_min=delay_sec // 60, message=shutdown_message)
|
||||
return f"{full_path[0]} {af}"
|
||||
|
||||
def perform_shutdown(self, task_vars, distribution) -> dict[str, t.Any]:
|
||||
result: dict[str, t.Any] = {}
|
||||
shutdown_result: dict[str, t.Any] = {}
|
||||
shutdown_command_exec = self.get_shutdown_command(task_vars, distribution)
|
||||
|
||||
self.cleanup(force=True)
|
||||
try:
|
||||
display.vvv(f"{self._task.action}: shutting down server...")
|
||||
display.debug(f"{self._task.action}: shutting down server with command '{shutdown_command_exec}'")
|
||||
if self._play_context.check_mode:
|
||||
shutdown_result["rc"] = 0
|
||||
else:
|
||||
shutdown_result.update(
|
||||
self._low_level_execute_command(shutdown_command_exec, sudoable=self.DEFAULT_SUDOABLE)
|
||||
)
|
||||
except AnsibleConnectionFailure as e:
|
||||
# If the connection is closed too quickly due to the system being shutdown, carry on
|
||||
display.debug(f"{self._task.action}: AnsibleConnectionFailure caught and handled: {e}")
|
||||
shutdown_result["rc"] = 0
|
||||
|
||||
if shutdown_result["rc"] != 0:
|
||||
result["failed"] = True
|
||||
result["shutdown"] = False
|
||||
result["msg"] = (
|
||||
f"Shutdown command failed. Error was {to_native(shutdown_result['stdout'])}, {to_native(shutdown_result['stderr'])}"
|
||||
)
|
||||
return result
|
||||
|
||||
result["failed"] = False
|
||||
result["shutdown_command"] = shutdown_command_exec
|
||||
return result
|
||||
|
||||
def run(self, tmp: str | None = None, task_vars: dict[str, t.Any] | None = None) -> dict[str, t.Any]:
|
||||
self._supports_check_mode = True
|
||||
self._supports_async = True
|
||||
|
||||
# If running with local connection, fail so we don't shutdown ourself
|
||||
if self._connection.transport == "local" and (not self._play_context.check_mode):
|
||||
msg = f"Running {self._task.action} with local connection would shutdown the control node."
|
||||
return {"changed": False, "elapsed": 0, "shutdown": False, "failed": True, "msg": msg}
|
||||
|
||||
if task_vars is None:
|
||||
task_vars = {}
|
||||
|
||||
result = super().run(tmp, task_vars)
|
||||
|
||||
if result.get("skipped", False) or result.get("failed", False):
|
||||
return result
|
||||
|
||||
distribution = self.get_distribution(task_vars)
|
||||
|
||||
# Initiate shutdown
|
||||
shutdown_result = self.perform_shutdown(task_vars, distribution)
|
||||
|
||||
if shutdown_result["failed"]:
|
||||
result = shutdown_result
|
||||
return result
|
||||
|
||||
result["shutdown"] = True
|
||||
result["changed"] = True
|
||||
result["shutdown_command"] = shutdown_result["shutdown_command"]
|
||||
|
||||
return result
|
||||
@@ -0,0 +1,157 @@
|
||||
# Copyright (c) 2018, 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"""
|
||||
name: doas
|
||||
short_description: Do As user
|
||||
description:
|
||||
- This become plugins allows your remote/login user to execute commands as another user using the C(doas) utility.
|
||||
author: Ansible Core Team
|
||||
options:
|
||||
become_user:
|
||||
description: User you 'become' to execute the task.
|
||||
type: string
|
||||
ini:
|
||||
- section: privilege_escalation
|
||||
key: become_user
|
||||
- section: doas_become_plugin
|
||||
key: user
|
||||
vars:
|
||||
- name: ansible_become_user
|
||||
- name: ansible_doas_user
|
||||
env:
|
||||
- name: ANSIBLE_BECOME_USER
|
||||
- name: ANSIBLE_DOAS_USER
|
||||
become_exe:
|
||||
description: C(doas) executable.
|
||||
type: string
|
||||
default: doas
|
||||
ini:
|
||||
- section: privilege_escalation
|
||||
key: become_exe
|
||||
- section: doas_become_plugin
|
||||
key: executable
|
||||
vars:
|
||||
- name: ansible_become_exe
|
||||
- name: ansible_doas_exe
|
||||
env:
|
||||
- name: ANSIBLE_BECOME_EXE
|
||||
- name: ANSIBLE_DOAS_EXE
|
||||
become_flags:
|
||||
description: Options to pass to C(doas).
|
||||
type: string
|
||||
default: ''
|
||||
ini:
|
||||
- section: privilege_escalation
|
||||
key: become_flags
|
||||
- section: doas_become_plugin
|
||||
key: flags
|
||||
vars:
|
||||
- name: ansible_become_flags
|
||||
- name: ansible_doas_flags
|
||||
env:
|
||||
- name: ANSIBLE_BECOME_FLAGS
|
||||
- name: ANSIBLE_DOAS_FLAGS
|
||||
become_pass:
|
||||
description: Password for C(doas) prompt.
|
||||
type: string
|
||||
required: false
|
||||
vars:
|
||||
- name: ansible_become_password
|
||||
- name: ansible_become_pass
|
||||
- name: ansible_doas_pass
|
||||
env:
|
||||
- name: ANSIBLE_BECOME_PASS
|
||||
- name: ANSIBLE_DOAS_PASS
|
||||
ini:
|
||||
- section: doas_become_plugin
|
||||
key: password
|
||||
secret: true
|
||||
prompt_l10n:
|
||||
description:
|
||||
- List of localized strings to match for prompt detection.
|
||||
- If empty the plugin uses the built-in one.
|
||||
type: list
|
||||
elements: string
|
||||
default: []
|
||||
ini:
|
||||
- section: doas_become_plugin
|
||||
key: localized_prompts
|
||||
vars:
|
||||
- name: ansible_doas_prompt_l10n
|
||||
env:
|
||||
- name: ANSIBLE_DOAS_PROMPT_L10N
|
||||
allow_pipelining:
|
||||
description:
|
||||
- When set to V(true), do allow pipelining.
|
||||
- This should only be used when doas is configured to not ask for a password (C(nopass)).
|
||||
type: boolean
|
||||
default: false
|
||||
version_added: 12.4.0
|
||||
ini:
|
||||
- section: doas_become_plugin
|
||||
key: allow_pipelining
|
||||
vars:
|
||||
- name: ansible_doas_allow_pipelining
|
||||
env:
|
||||
- name: ANSIBLE_DOAS_ALLOW_PIPELINING
|
||||
notes:
|
||||
- This become plugin does not work when connection pipelining is enabled
|
||||
and doas requests a password.
|
||||
Using this plugin automatically disables pipelining,
|
||||
unless O(allow_pipelining=true) is explicitly set by the user.
|
||||
"""
|
||||
|
||||
import re
|
||||
|
||||
from ansible.module_utils.common.text.converters import to_bytes
|
||||
from ansible.plugins.become import BecomeBase
|
||||
|
||||
|
||||
class BecomeModule(BecomeBase):
|
||||
name = "community.general.doas"
|
||||
|
||||
# messages for detecting prompted password issues
|
||||
fail = ("Permission denied",)
|
||||
missing = ("Authorization required",)
|
||||
|
||||
# See https://github.com/ansible-collections/community.general/issues/9977,
|
||||
# https://github.com/ansible/ansible/pull/78111,
|
||||
# https://github.com/ansible-collections/community.general/issues/11411
|
||||
@property
|
||||
def pipelining(self) -> bool: # type: ignore[override]
|
||||
return self.get_option("allow_pipelining")
|
||||
|
||||
def check_password_prompt(self, b_output):
|
||||
"""checks if the expected password prompt exists in b_output"""
|
||||
|
||||
# FIXME: more accurate would be: 'doas (%s@' % remote_user
|
||||
# however become plugins don't have that information currently
|
||||
b_prompts = [to_bytes(p) for p in self.get_option("prompt_l10n")] or [rb"doas \(", rb"Password:"]
|
||||
b_prompt = b"|".join(b_prompts)
|
||||
|
||||
return bool(re.match(b_prompt, b_output))
|
||||
|
||||
def build_become_command(self, cmd, shell):
|
||||
super().build_become_command(cmd, shell)
|
||||
|
||||
if not cmd:
|
||||
return cmd
|
||||
|
||||
self.prompt = True
|
||||
|
||||
become_exe = self.get_option("become_exe")
|
||||
|
||||
flags = self.get_option("become_flags")
|
||||
if not self.get_option("become_pass") and "-n" not in flags:
|
||||
flags += " -n"
|
||||
|
||||
become_user = self.get_option("become_user")
|
||||
user = f"-u {become_user}" if become_user else ""
|
||||
|
||||
success_cmd = self._build_success_command(cmd, shell, noexe=True)
|
||||
executable = getattr(shell, "executable", shell.SHELL_FAMILY)
|
||||
|
||||
return f"{become_exe} {flags} {user} {executable} -c {success_cmd}"
|
||||
@@ -0,0 +1,99 @@
|
||||
# Copyright (c) 2018, 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"""
|
||||
name: dzdo
|
||||
short_description: Centrify's Direct Authorize
|
||||
description:
|
||||
- This become plugins allows your remote/login user to execute commands as another user using the C(dzdo) utility.
|
||||
author: Ansible Core Team
|
||||
options:
|
||||
become_user:
|
||||
description: User you 'become' to execute the task.
|
||||
type: string
|
||||
ini:
|
||||
- section: privilege_escalation
|
||||
key: become_user
|
||||
- section: dzdo_become_plugin
|
||||
key: user
|
||||
vars:
|
||||
- name: ansible_become_user
|
||||
- name: ansible_dzdo_user
|
||||
env:
|
||||
- name: ANSIBLE_BECOME_USER
|
||||
- name: ANSIBLE_DZDO_USER
|
||||
become_exe:
|
||||
description: C(dzdo) executable.
|
||||
type: string
|
||||
default: dzdo
|
||||
ini:
|
||||
- section: privilege_escalation
|
||||
key: become_exe
|
||||
- section: dzdo_become_plugin
|
||||
key: executable
|
||||
vars:
|
||||
- name: ansible_become_exe
|
||||
- name: ansible_dzdo_exe
|
||||
env:
|
||||
- name: ANSIBLE_BECOME_EXE
|
||||
- name: ANSIBLE_DZDO_EXE
|
||||
become_flags:
|
||||
description: Options to pass to C(dzdo).
|
||||
type: string
|
||||
default: -H -S -n
|
||||
ini:
|
||||
- section: privilege_escalation
|
||||
key: become_flags
|
||||
- section: dzdo_become_plugin
|
||||
key: flags
|
||||
vars:
|
||||
- name: ansible_become_flags
|
||||
- name: ansible_dzdo_flags
|
||||
env:
|
||||
- name: ANSIBLE_BECOME_FLAGS
|
||||
- name: ANSIBLE_DZDO_FLAGS
|
||||
become_pass:
|
||||
description: Options to pass to C(dzdo).
|
||||
type: string
|
||||
required: false
|
||||
vars:
|
||||
- name: ansible_become_password
|
||||
- name: ansible_become_pass
|
||||
- name: ansible_dzdo_pass
|
||||
env:
|
||||
- name: ANSIBLE_BECOME_PASS
|
||||
- name: ANSIBLE_DZDO_PASS
|
||||
ini:
|
||||
- section: dzdo_become_plugin
|
||||
key: password
|
||||
secret: true
|
||||
"""
|
||||
|
||||
from ansible.plugins.become import BecomeBase
|
||||
|
||||
|
||||
class BecomeModule(BecomeBase):
|
||||
name = "community.general.dzdo"
|
||||
|
||||
# messages for detecting prompted password issues
|
||||
fail = ("Sorry, try again.",)
|
||||
|
||||
def build_become_command(self, cmd, shell):
|
||||
super().build_become_command(cmd, shell)
|
||||
|
||||
if not cmd:
|
||||
return cmd
|
||||
|
||||
becomecmd = self.get_option("become_exe")
|
||||
|
||||
flags = self.get_option("become_flags")
|
||||
if self.get_option("become_pass"):
|
||||
self.prompt = f"[dzdo via ansible, key={self._id}] password:"
|
||||
flags = f'{flags.replace("-n", "")} -p "{self.prompt}"'
|
||||
|
||||
become_user = self.get_option("become_user")
|
||||
user = f"-u {become_user}" if become_user else ""
|
||||
|
||||
return f"{becomecmd} {flags} {user} {self._build_success_command(cmd, shell)}"
|
||||
@@ -0,0 +1,124 @@
|
||||
# Copyright (c) 2018, 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"""
|
||||
name: ksu
|
||||
short_description: Kerberos substitute user
|
||||
description:
|
||||
- This become plugins allows your remote/login user to execute commands as another user using the C(ksu) utility.
|
||||
author: Ansible Core Team
|
||||
options:
|
||||
become_user:
|
||||
description: User you 'become' to execute the task.
|
||||
type: string
|
||||
ini:
|
||||
- section: privilege_escalation
|
||||
key: become_user
|
||||
- section: ksu_become_plugin
|
||||
key: user
|
||||
vars:
|
||||
- name: ansible_become_user
|
||||
- name: ansible_ksu_user
|
||||
env:
|
||||
- name: ANSIBLE_BECOME_USER
|
||||
- name: ANSIBLE_KSU_USER
|
||||
required: true
|
||||
become_exe:
|
||||
description: C(ksu) executable.
|
||||
type: string
|
||||
default: ksu
|
||||
ini:
|
||||
- section: privilege_escalation
|
||||
key: become_exe
|
||||
- section: ksu_become_plugin
|
||||
key: executable
|
||||
vars:
|
||||
- name: ansible_become_exe
|
||||
- name: ansible_ksu_exe
|
||||
env:
|
||||
- name: ANSIBLE_BECOME_EXE
|
||||
- name: ANSIBLE_KSU_EXE
|
||||
become_flags:
|
||||
description: Options to pass to C(ksu).
|
||||
type: string
|
||||
default: ''
|
||||
ini:
|
||||
- section: privilege_escalation
|
||||
key: become_flags
|
||||
- section: ksu_become_plugin
|
||||
key: flags
|
||||
vars:
|
||||
- name: ansible_become_flags
|
||||
- name: ansible_ksu_flags
|
||||
env:
|
||||
- name: ANSIBLE_BECOME_FLAGS
|
||||
- name: ANSIBLE_KSU_FLAGS
|
||||
become_pass:
|
||||
description: C(ksu) password.
|
||||
type: string
|
||||
required: false
|
||||
vars:
|
||||
- name: ansible_ksu_pass
|
||||
- name: ansible_become_pass
|
||||
- name: ansible_become_password
|
||||
env:
|
||||
- name: ANSIBLE_BECOME_PASS
|
||||
- name: ANSIBLE_KSU_PASS
|
||||
ini:
|
||||
- section: ksu_become_plugin
|
||||
key: password
|
||||
secret: true
|
||||
prompt_l10n:
|
||||
description:
|
||||
- List of localized strings to match for prompt detection.
|
||||
- If empty the plugin uses the built-in one.
|
||||
type: list
|
||||
elements: string
|
||||
default: []
|
||||
ini:
|
||||
- section: ksu_become_plugin
|
||||
key: localized_prompts
|
||||
vars:
|
||||
- name: ansible_ksu_prompt_l10n
|
||||
env:
|
||||
- name: ANSIBLE_KSU_PROMPT_L10N
|
||||
"""
|
||||
|
||||
import re
|
||||
|
||||
from ansible.module_utils.common.text.converters import to_bytes
|
||||
from ansible.plugins.become import BecomeBase
|
||||
|
||||
|
||||
class BecomeModule(BecomeBase):
|
||||
name = "community.general.ksu"
|
||||
|
||||
# messages for detecting prompted password issues
|
||||
fail = ("Password incorrect",)
|
||||
missing = ("No password given",)
|
||||
|
||||
def check_password_prompt(self, b_output):
|
||||
"""checks if the expected password prompt exists in b_output"""
|
||||
|
||||
prompts = self.get_option("prompt_l10n") or ["Kerberos password for .*@.*:"]
|
||||
b_prompt = b"|".join(to_bytes(p) for p in prompts)
|
||||
|
||||
return bool(re.match(b_prompt, b_output))
|
||||
|
||||
def build_become_command(self, cmd, shell):
|
||||
super().build_become_command(cmd, shell)
|
||||
|
||||
# Prompt handling for ``ksu`` is more complicated, this
|
||||
# is used to satisfy the connection plugin
|
||||
self.prompt = True
|
||||
|
||||
if not cmd:
|
||||
return cmd
|
||||
|
||||
exe = self.get_option("become_exe")
|
||||
|
||||
flags = self.get_option("become_flags")
|
||||
user = self.get_option("become_user")
|
||||
return f"{exe} {user} {flags} -e {self._build_success_command(cmd, shell)} "
|
||||
+143
@@ -0,0 +1,143 @@
|
||||
# Copyright (c) 2018, 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"""
|
||||
name: machinectl
|
||||
short_description: Systemd's machinectl privilege escalation
|
||||
description:
|
||||
- This become plugins allows your remote/login user to execute commands as another user using the C(machinectl) utility.
|
||||
author: Ansible Core Team
|
||||
options:
|
||||
become_user:
|
||||
description: User you 'become' to execute the task.
|
||||
type: string
|
||||
default: ''
|
||||
ini:
|
||||
- section: privilege_escalation
|
||||
key: become_user
|
||||
- section: machinectl_become_plugin
|
||||
key: user
|
||||
vars:
|
||||
- name: ansible_become_user
|
||||
- name: ansible_machinectl_user
|
||||
env:
|
||||
- name: ANSIBLE_BECOME_USER
|
||||
- name: ANSIBLE_MACHINECTL_USER
|
||||
become_exe:
|
||||
description: C(machinectl) executable.
|
||||
type: string
|
||||
default: machinectl
|
||||
ini:
|
||||
- section: privilege_escalation
|
||||
key: become_exe
|
||||
- section: machinectl_become_plugin
|
||||
key: executable
|
||||
vars:
|
||||
- name: ansible_become_exe
|
||||
- name: ansible_machinectl_exe
|
||||
env:
|
||||
- name: ANSIBLE_BECOME_EXE
|
||||
- name: ANSIBLE_MACHINECTL_EXE
|
||||
become_flags:
|
||||
description: Options to pass to C(machinectl).
|
||||
type: string
|
||||
default: ''
|
||||
ini:
|
||||
- section: privilege_escalation
|
||||
key: become_flags
|
||||
- section: machinectl_become_plugin
|
||||
key: flags
|
||||
vars:
|
||||
- name: ansible_become_flags
|
||||
- name: ansible_machinectl_flags
|
||||
env:
|
||||
- name: ANSIBLE_BECOME_FLAGS
|
||||
- name: ANSIBLE_MACHINECTL_FLAGS
|
||||
become_pass:
|
||||
description: Password for C(machinectl).
|
||||
type: string
|
||||
required: false
|
||||
vars:
|
||||
- name: ansible_become_password
|
||||
- name: ansible_become_pass
|
||||
- name: ansible_machinectl_pass
|
||||
env:
|
||||
- name: ANSIBLE_BECOME_PASS
|
||||
- name: ANSIBLE_MACHINECTL_PASS
|
||||
ini:
|
||||
- section: machinectl_become_plugin
|
||||
key: password
|
||||
secret: true
|
||||
notes:
|
||||
- When not using this plugin with user V(root), it only works correctly with a polkit rule which alters the behaviour
|
||||
of C(machinectl). This rule must alter the prompt behaviour to ask directly for the user credentials, if the user is allowed
|
||||
to perform the action (take a look at the examples section). If such a rule is not present the plugin only works if it
|
||||
is used in context with the root user, because then no further prompt is shown by C(machinectl).
|
||||
- This become plugin does not work when connection pipelining is enabled. Using it automatically
|
||||
disables pipelining.
|
||||
"""
|
||||
|
||||
EXAMPLES = r"""
|
||||
# A polkit rule needed to use the module with a non-root user.
|
||||
# See the Notes section for details.
|
||||
/etc/polkit-1/rules.d/60-machinectl-fast-user-auth.rules: |-
|
||||
polkit.addRule(function(action, subject) {
|
||||
if(action.id == "org.freedesktop.machine1.host-shell" &&
|
||||
subject.isInGroup("wheel")) {
|
||||
return polkit.Result.AUTH_SELF_KEEP;
|
||||
}
|
||||
});
|
||||
"""
|
||||
|
||||
from re import compile as re_compile
|
||||
|
||||
from ansible.module_utils.common.text.converters import to_bytes
|
||||
from ansible.plugins.become import BecomeBase
|
||||
|
||||
ansi_color_codes = re_compile(to_bytes(r"\x1B\[[0-9;]+m"))
|
||||
|
||||
|
||||
class BecomeModule(BecomeBase):
|
||||
name = "community.general.machinectl"
|
||||
|
||||
prompt = "Password: "
|
||||
fail = ("==== AUTHENTICATION FAILED ====",)
|
||||
success = ("==== AUTHENTICATION COMPLETE ====",)
|
||||
require_tty = True # see https://github.com/ansible-collections/community.general/issues/6932
|
||||
|
||||
# See https://github.com/ansible/ansible/issues/81254,
|
||||
# https://github.com/ansible/ansible/pull/78111
|
||||
pipelining = False
|
||||
|
||||
@staticmethod
|
||||
def remove_ansi_codes(line):
|
||||
return ansi_color_codes.sub(b"", line)
|
||||
|
||||
def build_become_command(self, cmd, shell):
|
||||
super().build_become_command(cmd, shell)
|
||||
|
||||
if not cmd:
|
||||
return cmd
|
||||
|
||||
become = self.get_option("become_exe")
|
||||
|
||||
flags = self.get_option("become_flags")
|
||||
user = self.get_option("become_user")
|
||||
# SYSTEMD_COLORS=0 stops machinectl from appending ANSI reset
|
||||
# sequences (ESC[0m, ESC[J) after the child exits, which would
|
||||
# otherwise land after the module JSON and break result parsing.
|
||||
return f"SYSTEMD_COLORS=0 {become} -q shell {flags} {user}@ {self._build_success_command(cmd, shell)}"
|
||||
|
||||
def check_success(self, b_output):
|
||||
b_output = self.remove_ansi_codes(b_output)
|
||||
return super().check_success(b_output)
|
||||
|
||||
def check_incorrect_password(self, b_output):
|
||||
b_output = self.remove_ansi_codes(b_output)
|
||||
return super().check_incorrect_password(b_output)
|
||||
|
||||
def check_missing_password(self, b_output):
|
||||
b_output = self.remove_ansi_codes(b_output)
|
||||
return super().check_missing_password(b_output)
|
||||
@@ -0,0 +1,107 @@
|
||||
# Copyright (c) 2018, 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"""
|
||||
name: pbrun
|
||||
short_description: PowerBroker run
|
||||
description:
|
||||
- This become plugins allows your remote/login user to execute commands as another user using the C(pbrun) utility.
|
||||
author: Ansible Core Team
|
||||
options:
|
||||
become_user:
|
||||
description: User you 'become' to execute the task.
|
||||
type: string
|
||||
default: ''
|
||||
ini:
|
||||
- section: privilege_escalation
|
||||
key: become_user
|
||||
- section: pbrun_become_plugin
|
||||
key: user
|
||||
vars:
|
||||
- name: ansible_become_user
|
||||
- name: ansible_pbrun_user
|
||||
env:
|
||||
- name: ANSIBLE_BECOME_USER
|
||||
- name: ANSIBLE_PBRUN_USER
|
||||
become_exe:
|
||||
description: C(pbrun) executable.
|
||||
type: string
|
||||
default: pbrun
|
||||
ini:
|
||||
- section: privilege_escalation
|
||||
key: become_exe
|
||||
- section: pbrun_become_plugin
|
||||
key: executable
|
||||
vars:
|
||||
- name: ansible_become_exe
|
||||
- name: ansible_pbrun_exe
|
||||
env:
|
||||
- name: ANSIBLE_BECOME_EXE
|
||||
- name: ANSIBLE_PBRUN_EXE
|
||||
become_flags:
|
||||
description: Options to pass to C(pbrun).
|
||||
type: string
|
||||
default: ''
|
||||
ini:
|
||||
- section: privilege_escalation
|
||||
key: become_flags
|
||||
- section: pbrun_become_plugin
|
||||
key: flags
|
||||
vars:
|
||||
- name: ansible_become_flags
|
||||
- name: ansible_pbrun_flags
|
||||
env:
|
||||
- name: ANSIBLE_BECOME_FLAGS
|
||||
- name: ANSIBLE_PBRUN_FLAGS
|
||||
become_pass:
|
||||
description: Password for C(pbrun).
|
||||
type: string
|
||||
required: false
|
||||
vars:
|
||||
- name: ansible_become_password
|
||||
- name: ansible_become_pass
|
||||
- name: ansible_pbrun_pass
|
||||
env:
|
||||
- name: ANSIBLE_BECOME_PASS
|
||||
- name: ANSIBLE_PBRUN_PASS
|
||||
ini:
|
||||
- section: pbrun_become_plugin
|
||||
key: password
|
||||
secret: true
|
||||
wrap_exe:
|
||||
description: Toggle to wrap the command C(pbrun) calls in C(shell -c) or not.
|
||||
default: false
|
||||
type: bool
|
||||
ini:
|
||||
- section: pbrun_become_plugin
|
||||
key: wrap_execution
|
||||
vars:
|
||||
- name: ansible_pbrun_wrap_execution
|
||||
env:
|
||||
- name: ANSIBLE_PBRUN_WRAP_EXECUTION
|
||||
"""
|
||||
|
||||
from ansible.plugins.become import BecomeBase
|
||||
|
||||
|
||||
class BecomeModule(BecomeBase):
|
||||
name = "community.general.pbrun"
|
||||
|
||||
prompt = "Password:"
|
||||
|
||||
def build_become_command(self, cmd, shell):
|
||||
super().build_become_command(cmd, shell)
|
||||
|
||||
if not cmd:
|
||||
return cmd
|
||||
|
||||
become_exe = self.get_option("become_exe")
|
||||
|
||||
flags = self.get_option("become_flags")
|
||||
become_user = self.get_option("become_user")
|
||||
user = f"-u {become_user}" if become_user else ""
|
||||
noexe = not self.get_option("wrap_exe")
|
||||
|
||||
return f"{become_exe} {flags} {user} {self._build_success_command(cmd, shell, noexe=noexe)}"
|
||||
@@ -0,0 +1,117 @@
|
||||
# Copyright (c) 2018, 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"""
|
||||
name: pfexec
|
||||
short_description: Profile based execution
|
||||
description:
|
||||
- This become plugins allows your remote/login user to execute commands as another user using the C(pfexec) utility.
|
||||
author: Ansible Core Team
|
||||
options:
|
||||
become_user:
|
||||
description:
|
||||
- User you 'become' to execute the task.
|
||||
- This plugin ignores this setting as pfexec uses its own C(exec_attr) to figure this out, but it is supplied here for
|
||||
Ansible to make decisions needed for the task execution, like file permissions.
|
||||
type: string
|
||||
default: root
|
||||
ini:
|
||||
- section: privilege_escalation
|
||||
key: become_user
|
||||
- section: pfexec_become_plugin
|
||||
key: user
|
||||
vars:
|
||||
- name: ansible_become_user
|
||||
- name: ansible_pfexec_user
|
||||
env:
|
||||
- name: ANSIBLE_BECOME_USER
|
||||
- name: ANSIBLE_PFEXEC_USER
|
||||
become_exe:
|
||||
description: C(pfexec) executable.
|
||||
type: string
|
||||
default: pfexec
|
||||
ini:
|
||||
- section: privilege_escalation
|
||||
key: become_exe
|
||||
- section: pfexec_become_plugin
|
||||
key: executable
|
||||
vars:
|
||||
- name: ansible_become_exe
|
||||
- name: ansible_pfexec_exe
|
||||
env:
|
||||
- name: ANSIBLE_BECOME_EXE
|
||||
- name: ANSIBLE_PFEXEC_EXE
|
||||
become_flags:
|
||||
description: Options to pass to C(pfexec).
|
||||
type: string
|
||||
default: ""
|
||||
ini:
|
||||
- section: privilege_escalation
|
||||
key: become_flags
|
||||
- section: pfexec_become_plugin
|
||||
key: flags
|
||||
vars:
|
||||
- name: ansible_become_flags
|
||||
- name: ansible_pfexec_flags
|
||||
env:
|
||||
- name: ANSIBLE_BECOME_FLAGS
|
||||
- name: ANSIBLE_PFEXEC_FLAGS
|
||||
become_pass:
|
||||
description: C(pfexec) password.
|
||||
type: string
|
||||
required: false
|
||||
vars:
|
||||
- name: ansible_become_password
|
||||
- name: ansible_become_pass
|
||||
- name: ansible_pfexec_pass
|
||||
env:
|
||||
- name: ANSIBLE_BECOME_PASS
|
||||
- name: ANSIBLE_PFEXEC_PASS
|
||||
ini:
|
||||
- section: pfexec_become_plugin
|
||||
key: password
|
||||
secret: true
|
||||
wrap_exe:
|
||||
description:
|
||||
- Toggle to wrap the command C(pfexec) calls in C(shell -c) or not.
|
||||
- Unlike C(sudo), C(pfexec) does not interpret shell constructs internally,
|
||||
so commands containing shell operators must be wrapped in a shell invocation.
|
||||
- The current default of V(false) only works in very limited cases (for example
|
||||
with M(ansible.builtin.raw)).
|
||||
- The default changed from V(false) to V(true) in community.general 14.0.0.
|
||||
type: bool
|
||||
default: true
|
||||
ini:
|
||||
- section: pfexec_become_plugin
|
||||
key: wrap_execution
|
||||
vars:
|
||||
- name: ansible_pfexec_wrap_execution
|
||||
env:
|
||||
- name: ANSIBLE_PFEXEC_WRAP_EXECUTION
|
||||
notes:
|
||||
- This plugin ignores O(become_user) as pfexec uses its own C(exec_attr) to figure this out.
|
||||
"""
|
||||
|
||||
from ansible.plugins.become import BecomeBase
|
||||
from ansible.utils.display import Display
|
||||
|
||||
display = Display()
|
||||
|
||||
|
||||
class BecomeModule(BecomeBase):
|
||||
name = "community.general.pfexec"
|
||||
|
||||
def build_become_command(self, cmd, shell):
|
||||
super().build_become_command(cmd, shell)
|
||||
|
||||
if not cmd:
|
||||
return cmd
|
||||
|
||||
exe = self.get_option("become_exe")
|
||||
flags = self.get_option("become_flags")
|
||||
wrap_exe = self.get_option("wrap_exe")
|
||||
|
||||
become_cmd = self._build_success_command(cmd, shell, noexe=not wrap_exe)
|
||||
return " ".join(part for part in (exe, flags, become_cmd) if part)
|
||||
@@ -0,0 +1,80 @@
|
||||
# Copyright (c) 2018, 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"""
|
||||
name: pmrun
|
||||
short_description: Privilege Manager run
|
||||
description:
|
||||
- This become plugins allows your remote/login user to execute commands as another user using the C(pmrun) utility.
|
||||
author: Ansible Core Team
|
||||
options:
|
||||
become_exe:
|
||||
description: C(pmrun) executable.
|
||||
type: string
|
||||
default: pmrun
|
||||
ini:
|
||||
- section: privilege_escalation
|
||||
key: become_exe
|
||||
- section: pmrun_become_plugin
|
||||
key: executable
|
||||
vars:
|
||||
- name: ansible_become_exe
|
||||
- name: ansible_pmrun_exe
|
||||
env:
|
||||
- name: ANSIBLE_BECOME_EXE
|
||||
- name: ANSIBLE_PMRUN_EXE
|
||||
become_flags:
|
||||
description: Options to pass to C(pmrun).
|
||||
type: string
|
||||
default: ''
|
||||
ini:
|
||||
- section: privilege_escalation
|
||||
key: become_flags
|
||||
- section: pmrun_become_plugin
|
||||
key: flags
|
||||
vars:
|
||||
- name: ansible_become_flags
|
||||
- name: ansible_pmrun_flags
|
||||
env:
|
||||
- name: ANSIBLE_BECOME_FLAGS
|
||||
- name: ANSIBLE_PMRUN_FLAGS
|
||||
become_pass:
|
||||
description: C(pmrun) password.
|
||||
type: string
|
||||
required: false
|
||||
vars:
|
||||
- name: ansible_become_password
|
||||
- name: ansible_become_pass
|
||||
- name: ansible_pmrun_pass
|
||||
env:
|
||||
- name: ANSIBLE_BECOME_PASS
|
||||
- name: ANSIBLE_PMRUN_PASS
|
||||
ini:
|
||||
- section: pmrun_become_plugin
|
||||
key: password
|
||||
secret: true
|
||||
notes:
|
||||
- This plugin ignores the C(become_user) supplied and uses C(pmrun)'s own configuration to select the user.
|
||||
"""
|
||||
|
||||
from shlex import quote as shlex_quote
|
||||
|
||||
from ansible.plugins.become import BecomeBase
|
||||
|
||||
|
||||
class BecomeModule(BecomeBase):
|
||||
name = "community.general.pmrun"
|
||||
prompt = "Enter UPM user password:"
|
||||
|
||||
def build_become_command(self, cmd, shell):
|
||||
super().build_become_command(cmd, shell)
|
||||
|
||||
if not cmd:
|
||||
return cmd
|
||||
|
||||
become = self.get_option("become_exe")
|
||||
|
||||
flags = self.get_option("become_flags")
|
||||
return f"{become} {flags} {shlex_quote(self._build_success_command(cmd, shell))}"
|
||||
@@ -0,0 +1,130 @@
|
||||
# Copyright (c) 2024, 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"""
|
||||
name: run0
|
||||
short_description: Systemd's run0
|
||||
description:
|
||||
- This become plugins allows your remote/login user to execute commands as another user using the C(run0) utility.
|
||||
author:
|
||||
- Thomas Sjögren (@konstruktoid)
|
||||
version_added: '9.0.0'
|
||||
options:
|
||||
become_user:
|
||||
description: User you 'become' to execute the task.
|
||||
default: root
|
||||
ini:
|
||||
- section: privilege_escalation
|
||||
key: become_user
|
||||
- section: run0_become_plugin
|
||||
key: user
|
||||
vars:
|
||||
- name: ansible_become_user
|
||||
- name: ansible_run0_user
|
||||
env:
|
||||
- name: ANSIBLE_BECOME_USER
|
||||
- name: ANSIBLE_RUN0_USER
|
||||
type: string
|
||||
become_exe:
|
||||
description: C(run0) executable.
|
||||
default: run0
|
||||
ini:
|
||||
- section: privilege_escalation
|
||||
key: become_exe
|
||||
- section: run0_become_plugin
|
||||
key: executable
|
||||
vars:
|
||||
- name: ansible_become_exe
|
||||
- name: ansible_run0_exe
|
||||
env:
|
||||
- name: ANSIBLE_BECOME_EXE
|
||||
- name: ANSIBLE_RUN0_EXE
|
||||
type: string
|
||||
become_flags:
|
||||
description: Options to pass to C(run0).
|
||||
default: ''
|
||||
ini:
|
||||
- section: privilege_escalation
|
||||
key: become_flags
|
||||
- section: run0_become_plugin
|
||||
key: flags
|
||||
vars:
|
||||
- name: ansible_become_flags
|
||||
- name: ansible_run0_flags
|
||||
env:
|
||||
- name: ANSIBLE_BECOME_FLAGS
|
||||
- name: ANSIBLE_RUN0_FLAGS
|
||||
type: string
|
||||
notes:
|
||||
- This plugin only works when a C(polkit) rule is in place.
|
||||
- This become plugin does not work when connection pipelining is enabled. Using it automatically
|
||||
disables pipelining.
|
||||
"""
|
||||
|
||||
EXAMPLES = r"""
|
||||
# An example polkit rule that allows the user 'ansible' in the 'wheel' group
|
||||
# to execute commands using run0 without authentication.
|
||||
/etc/polkit-1/rules.d/60-run0-fast-user-auth.rules: |-
|
||||
polkit.addRule(function(action, subject) {
|
||||
if(action.id == "org.freedesktop.systemd1.manage-units" &&
|
||||
subject.isInGroup("wheel") &&
|
||||
subject.user == "ansible") {
|
||||
return polkit.Result.YES;
|
||||
}
|
||||
});
|
||||
"""
|
||||
|
||||
from re import compile as re_compile
|
||||
|
||||
from ansible.module_utils.common.text.converters import to_bytes
|
||||
from ansible.plugins.become import BecomeBase
|
||||
|
||||
ansi_color_codes = re_compile(to_bytes(r"\x1B\[[0-9;]+m"))
|
||||
|
||||
|
||||
class BecomeModule(BecomeBase):
|
||||
name = "community.general.run0"
|
||||
|
||||
prompt = "Password: "
|
||||
fail = ("==== AUTHENTICATION FAILED ====",)
|
||||
success = ("==== AUTHENTICATION COMPLETE ====",)
|
||||
require_tty = True # see https://github.com/ansible-collections/community.general/issues/6932
|
||||
|
||||
# See https://github.com/ansible/ansible/issues/81254,
|
||||
# https://github.com/ansible/ansible/pull/78111
|
||||
pipelining = False
|
||||
|
||||
@staticmethod
|
||||
def remove_ansi_codes(line):
|
||||
return ansi_color_codes.sub(b"", line)
|
||||
|
||||
def build_become_command(self, cmd, shell):
|
||||
super().build_become_command(cmd, shell)
|
||||
|
||||
if not cmd:
|
||||
return cmd
|
||||
|
||||
become = self.get_option("become_exe")
|
||||
flags = self.get_option("become_flags")
|
||||
user = self.get_option("become_user")
|
||||
|
||||
# SYSTEMD_COLORS=0 stops run0 from emitting terminal control
|
||||
# sequences (window title OSC, ANSI reset) around the child
|
||||
# command, which would otherwise corrupt the module JSON and
|
||||
# break result parsing.
|
||||
return f"SYSTEMD_COLORS=0 {become} --user={user} {flags} {self._build_success_command(cmd, shell)}"
|
||||
|
||||
def check_success(self, b_output):
|
||||
b_output = self.remove_ansi_codes(b_output)
|
||||
return super().check_success(b_output)
|
||||
|
||||
def check_incorrect_password(self, b_output):
|
||||
b_output = self.remove_ansi_codes(b_output)
|
||||
return super().check_incorrect_password(b_output)
|
||||
|
||||
def check_missing_password(self, b_output):
|
||||
b_output = self.remove_ansi_codes(b_output)
|
||||
return super().check_missing_password(b_output)
|
||||
@@ -0,0 +1,94 @@
|
||||
# Copyright (c) 2018, 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"""
|
||||
name: sesu
|
||||
short_description: CA Privileged Access Manager
|
||||
description:
|
||||
- This become plugins allows your remote/login user to execute commands as another user using the C(sesu) utility.
|
||||
author: ansible (@nekonyuu)
|
||||
options:
|
||||
become_user:
|
||||
description: User you 'become' to execute the task.
|
||||
type: string
|
||||
default: ''
|
||||
ini:
|
||||
- section: privilege_escalation
|
||||
key: become_user
|
||||
- section: sesu_become_plugin
|
||||
key: user
|
||||
vars:
|
||||
- name: ansible_become_user
|
||||
- name: ansible_sesu_user
|
||||
env:
|
||||
- name: ANSIBLE_BECOME_USER
|
||||
- name: ANSIBLE_SESU_USER
|
||||
become_exe:
|
||||
description: C(sesu) executable.
|
||||
type: string
|
||||
default: sesu
|
||||
ini:
|
||||
- section: privilege_escalation
|
||||
key: become_exe
|
||||
- section: sesu_become_plugin
|
||||
key: executable
|
||||
vars:
|
||||
- name: ansible_become_exe
|
||||
- name: ansible_sesu_exe
|
||||
env:
|
||||
- name: ANSIBLE_BECOME_EXE
|
||||
- name: ANSIBLE_SESU_EXE
|
||||
become_flags:
|
||||
description: Options to pass to C(sesu).
|
||||
type: string
|
||||
default: -H -S -n
|
||||
ini:
|
||||
- section: privilege_escalation
|
||||
key: become_flags
|
||||
- section: sesu_become_plugin
|
||||
key: flags
|
||||
vars:
|
||||
- name: ansible_become_flags
|
||||
- name: ansible_sesu_flags
|
||||
env:
|
||||
- name: ANSIBLE_BECOME_FLAGS
|
||||
- name: ANSIBLE_SESU_FLAGS
|
||||
become_pass:
|
||||
description: Password to pass to C(sesu).
|
||||
type: string
|
||||
required: false
|
||||
vars:
|
||||
- name: ansible_become_password
|
||||
- name: ansible_become_pass
|
||||
- name: ansible_sesu_pass
|
||||
env:
|
||||
- name: ANSIBLE_BECOME_PASS
|
||||
- name: ANSIBLE_SESU_PASS
|
||||
ini:
|
||||
- section: sesu_become_plugin
|
||||
key: password
|
||||
secret: true
|
||||
"""
|
||||
|
||||
from ansible.plugins.become import BecomeBase
|
||||
|
||||
|
||||
class BecomeModule(BecomeBase):
|
||||
name = "community.general.sesu"
|
||||
|
||||
prompt = "Please enter your password:"
|
||||
fail = missing = ("Sorry, try again with sesu.",)
|
||||
|
||||
def build_become_command(self, cmd, shell):
|
||||
super().build_become_command(cmd, shell)
|
||||
|
||||
if not cmd:
|
||||
return cmd
|
||||
|
||||
become = self.get_option("become_exe")
|
||||
|
||||
flags = self.get_option("become_flags")
|
||||
user = self.get_option("become_user")
|
||||
return f"{become} {flags} {user} -c {self._build_success_command(cmd, shell)}"
|
||||
@@ -0,0 +1,112 @@
|
||||
# Copyright (c) 2021, 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"""
|
||||
name: sudosu
|
||||
short_description: Run tasks using sudo su -
|
||||
description:
|
||||
- This become plugin allows your remote/login user to execute commands as another user using the C(sudo) and C(su) utilities
|
||||
combined.
|
||||
author:
|
||||
- Dag Wieers (@dagwieers)
|
||||
version_added: 2.4.0
|
||||
options:
|
||||
become_user:
|
||||
description: User you 'become' to execute the task.
|
||||
type: string
|
||||
default: root
|
||||
ini:
|
||||
- section: privilege_escalation
|
||||
key: become_user
|
||||
- section: sudo_become_plugin
|
||||
key: user
|
||||
vars:
|
||||
- name: ansible_become_user
|
||||
- name: ansible_sudo_user
|
||||
env:
|
||||
- name: ANSIBLE_BECOME_USER
|
||||
- name: ANSIBLE_SUDO_USER
|
||||
become_flags:
|
||||
description: Options to pass to C(sudo).
|
||||
type: string
|
||||
default: -H -S -n
|
||||
ini:
|
||||
- section: privilege_escalation
|
||||
key: become_flags
|
||||
- section: sudo_become_plugin
|
||||
key: flags
|
||||
vars:
|
||||
- name: ansible_become_flags
|
||||
- name: ansible_sudo_flags
|
||||
env:
|
||||
- name: ANSIBLE_BECOME_FLAGS
|
||||
- name: ANSIBLE_SUDO_FLAGS
|
||||
become_pass:
|
||||
description: Password to pass to C(sudo).
|
||||
type: string
|
||||
required: false
|
||||
vars:
|
||||
- name: ansible_become_password
|
||||
- name: ansible_become_pass
|
||||
- name: ansible_sudo_pass
|
||||
env:
|
||||
- name: ANSIBLE_BECOME_PASS
|
||||
- name: ANSIBLE_SUDO_PASS
|
||||
ini:
|
||||
- section: sudo_become_plugin
|
||||
key: password
|
||||
secret: true
|
||||
alt_method:
|
||||
description:
|
||||
- Whether to use an alternative method to call C(su). Instead of running C(su -l user /path/to/shell -c command), it
|
||||
runs C(su -l user -c command).
|
||||
- Use this when the default one is not working on your system.
|
||||
required: false
|
||||
type: boolean
|
||||
ini:
|
||||
- section: community.general.sudosu
|
||||
key: alternative_method
|
||||
vars:
|
||||
- name: ansible_sudosu_alt_method
|
||||
env:
|
||||
- name: ANSIBLE_SUDOSU_ALT_METHOD
|
||||
version_added: 9.2.0
|
||||
"""
|
||||
|
||||
|
||||
from ansible.plugins.become import BecomeBase
|
||||
|
||||
|
||||
class BecomeModule(BecomeBase):
|
||||
name = "community.general.sudosu"
|
||||
|
||||
# messages for detecting prompted password issues
|
||||
fail = ("Sorry, try again.",)
|
||||
missing = ("Sorry, a password is required to run sudo", "sudo: a password is required")
|
||||
|
||||
def build_become_command(self, cmd, shell):
|
||||
super().build_become_command(cmd, shell)
|
||||
|
||||
if not cmd:
|
||||
return cmd
|
||||
|
||||
becomecmd = "sudo"
|
||||
|
||||
flags = self.get_option("become_flags") or ""
|
||||
prompt = ""
|
||||
if self.get_option("become_pass"):
|
||||
self.prompt = f"[sudo via ansible, key={self._id}] password:"
|
||||
if flags: # this could be simplified, but kept as is for now for backwards string matching
|
||||
flags = flags.replace("-n", "")
|
||||
prompt = f'-p "{self.prompt}"'
|
||||
|
||||
user = self.get_option("become_user") or ""
|
||||
if user:
|
||||
user = f"{user}"
|
||||
|
||||
if self.get_option("alt_method"):
|
||||
return f"{becomecmd} {flags} {prompt} su -l {user} -c {self._build_success_command(cmd, shell, True)}"
|
||||
else:
|
||||
return f"{becomecmd} {flags} {prompt} su -l {user} {self._build_success_command(cmd, shell)}"
|
||||
+243
@@ -0,0 +1,243 @@
|
||||
# Copyright (c) 2014, Brian Coca, Josh Drake, et al
|
||||
# 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: Unknown (!UNKNOWN)
|
||||
name: memcached
|
||||
short_description: Use memcached DB for cache
|
||||
description:
|
||||
- This cache uses JSON formatted, per host records saved in memcached.
|
||||
requirements:
|
||||
- memcache (python lib)
|
||||
options:
|
||||
_uri:
|
||||
description:
|
||||
- List of connection information for the memcached DBs.
|
||||
default: ['127.0.0.1:11211']
|
||||
type: list
|
||||
elements: string
|
||||
env:
|
||||
- name: ANSIBLE_CACHE_PLUGIN_CONNECTION
|
||||
ini:
|
||||
- key: fact_caching_connection
|
||||
section: defaults
|
||||
_prefix:
|
||||
description: User defined prefix to use when creating the DB entries.
|
||||
type: string
|
||||
default: ansible_facts
|
||||
env:
|
||||
- name: ANSIBLE_CACHE_PLUGIN_PREFIX
|
||||
ini:
|
||||
- key: fact_caching_prefix
|
||||
section: defaults
|
||||
_timeout:
|
||||
default: 86400
|
||||
type: integer
|
||||
# TODO: determine whether it is OK to change to: type: float
|
||||
description: Expiration timeout in seconds for the cache plugin data. Set to 0 to never expire.
|
||||
env:
|
||||
- name: ANSIBLE_CACHE_PLUGIN_TIMEOUT
|
||||
ini:
|
||||
- key: fact_caching_timeout
|
||||
section: defaults
|
||||
"""
|
||||
|
||||
import collections
|
||||
import os
|
||||
import time
|
||||
from collections.abc import MutableSet
|
||||
from itertools import chain
|
||||
from multiprocessing import Lock
|
||||
|
||||
from ansible.errors import AnsibleError
|
||||
from ansible.plugins.cache import BaseCacheModule
|
||||
from ansible.utils.display import Display
|
||||
|
||||
try:
|
||||
import memcache
|
||||
|
||||
HAS_MEMCACHE = True
|
||||
except ImportError:
|
||||
HAS_MEMCACHE = False
|
||||
|
||||
display = Display()
|
||||
|
||||
|
||||
class ProxyClientPool:
|
||||
"""
|
||||
Memcached connection pooling for thread/fork safety. Inspired by py-redis
|
||||
connection pool.
|
||||
|
||||
Available connections are maintained in a deque and released in a FIFO manner.
|
||||
"""
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
self.max_connections = kwargs.pop("max_connections", 1024)
|
||||
self.connection_args = args
|
||||
self.connection_kwargs = kwargs
|
||||
self.reset()
|
||||
|
||||
def reset(self):
|
||||
self.pid = os.getpid()
|
||||
self._num_connections = 0
|
||||
self._available_connections = collections.deque(maxlen=self.max_connections)
|
||||
self._locked_connections = set()
|
||||
self._lock = Lock()
|
||||
|
||||
def _check_safe(self):
|
||||
if self.pid != os.getpid():
|
||||
with self._lock:
|
||||
if self.pid == os.getpid():
|
||||
# bail out - another thread already acquired the lock
|
||||
return
|
||||
self.disconnect_all()
|
||||
self.reset()
|
||||
|
||||
def get_connection(self):
|
||||
self._check_safe()
|
||||
try:
|
||||
connection = self._available_connections.popleft()
|
||||
except IndexError:
|
||||
connection = self.create_connection()
|
||||
self._locked_connections.add(connection)
|
||||
return connection
|
||||
|
||||
def create_connection(self):
|
||||
if self._num_connections >= self.max_connections:
|
||||
raise RuntimeError("Too many memcached connections")
|
||||
self._num_connections += 1
|
||||
return memcache.Client(*self.connection_args, **self.connection_kwargs)
|
||||
|
||||
def release_connection(self, connection):
|
||||
self._check_safe()
|
||||
self._locked_connections.remove(connection)
|
||||
self._available_connections.append(connection)
|
||||
|
||||
def disconnect_all(self):
|
||||
for conn in chain(self._available_connections, self._locked_connections):
|
||||
conn.disconnect_all()
|
||||
|
||||
def __getattr__(self, name):
|
||||
def wrapped(*args, **kwargs):
|
||||
return self._proxy_client(name, *args, **kwargs)
|
||||
|
||||
return wrapped
|
||||
|
||||
def _proxy_client(self, name, *args, **kwargs):
|
||||
conn = self.get_connection()
|
||||
|
||||
try:
|
||||
return getattr(conn, name)(*args, **kwargs)
|
||||
finally:
|
||||
self.release_connection(conn)
|
||||
|
||||
|
||||
class CacheModuleKeys(MutableSet):
|
||||
"""
|
||||
A set subclass that keeps track of insertion time and persists
|
||||
the set in memcached.
|
||||
"""
|
||||
|
||||
PREFIX = "ansible_cache_keys"
|
||||
|
||||
def __init__(self, cache, *args, **kwargs):
|
||||
self._cache = cache
|
||||
self._keyset = dict(*args, **kwargs)
|
||||
|
||||
def __contains__(self, key):
|
||||
return key in self._keyset
|
||||
|
||||
def __iter__(self):
|
||||
return iter(self._keyset)
|
||||
|
||||
def __len__(self):
|
||||
return len(self._keyset)
|
||||
|
||||
def add(self, value):
|
||||
self._keyset[value] = time.time()
|
||||
self._cache.set(self.PREFIX, self._keyset)
|
||||
|
||||
def discard(self, value):
|
||||
del self._keyset[value]
|
||||
self._cache.set(self.PREFIX, self._keyset)
|
||||
|
||||
def remove_by_timerange(self, s_min, s_max):
|
||||
for k in list(self._keyset.keys()):
|
||||
t = self._keyset[k]
|
||||
if s_min < t < s_max:
|
||||
del self._keyset[k]
|
||||
self._cache.set(self.PREFIX, self._keyset)
|
||||
|
||||
|
||||
class CacheModule(BaseCacheModule):
|
||||
def __init__(self, *args, **kwargs):
|
||||
connection = ["127.0.0.1:11211"]
|
||||
|
||||
super().__init__(*args, **kwargs)
|
||||
if self.get_option("_uri"):
|
||||
connection = self.get_option("_uri")
|
||||
self._timeout = self.get_option("_timeout")
|
||||
self._prefix = self.get_option("_prefix")
|
||||
|
||||
if not HAS_MEMCACHE:
|
||||
raise AnsibleError("python-memcached is required for the memcached fact cache")
|
||||
|
||||
self._cache = {}
|
||||
self._db = ProxyClientPool(connection, debug=0)
|
||||
self._keys = CacheModuleKeys(self._db, self._db.get(CacheModuleKeys.PREFIX) or [])
|
||||
|
||||
def _make_key(self, key):
|
||||
return f"{self._prefix}{key}"
|
||||
|
||||
def _expire_keys(self):
|
||||
if self._timeout > 0:
|
||||
expiry_age = time.time() - self._timeout
|
||||
self._keys.remove_by_timerange(0, expiry_age)
|
||||
|
||||
def get(self, key):
|
||||
if key not in self._cache:
|
||||
value = self._db.get(self._make_key(key))
|
||||
# guard against the key not being removed from the keyset;
|
||||
# this could happen in cases where the timeout value is changed
|
||||
# between invocations
|
||||
if value is None:
|
||||
self.delete(key)
|
||||
raise KeyError
|
||||
self._cache[key] = value
|
||||
|
||||
return self._cache.get(key)
|
||||
|
||||
def set(self, key, value):
|
||||
self._db.set(self._make_key(key), value, time=self._timeout, min_compress_len=1)
|
||||
self._cache[key] = value
|
||||
self._keys.add(key)
|
||||
|
||||
def keys(self):
|
||||
self._expire_keys()
|
||||
return list(iter(self._keys))
|
||||
|
||||
def contains(self, key):
|
||||
self._expire_keys()
|
||||
return key in self._keys
|
||||
|
||||
def delete(self, key):
|
||||
del self._cache[key]
|
||||
self._db.delete(self._make_key(key))
|
||||
self._keys.discard(key)
|
||||
|
||||
def flush(self):
|
||||
for key in self.keys():
|
||||
self.delete(key)
|
||||
|
||||
def copy(self):
|
||||
return self._keys.copy()
|
||||
|
||||
def __getstate__(self):
|
||||
return dict()
|
||||
|
||||
def __setstate__(self, data):
|
||||
self.__init__()
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
# Copyright (c) 2017, Brian Coca
|
||||
# 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"""
|
||||
name: pickle
|
||||
short_description: Pickle formatted files
|
||||
description:
|
||||
- This cache uses Python's pickle serialization format, in per host files, saved to the filesystem.
|
||||
author: Brian Coca (@bcoca)
|
||||
options:
|
||||
_uri:
|
||||
required: true
|
||||
description:
|
||||
- Path in which the cache plugin saves the files.
|
||||
env:
|
||||
- name: ANSIBLE_CACHE_PLUGIN_CONNECTION
|
||||
ini:
|
||||
- key: fact_caching_connection
|
||||
section: defaults
|
||||
type: path
|
||||
_prefix:
|
||||
description: User defined prefix to use when creating the files.
|
||||
env:
|
||||
- name: ANSIBLE_CACHE_PLUGIN_PREFIX
|
||||
ini:
|
||||
- key: fact_caching_prefix
|
||||
section: defaults
|
||||
type: string
|
||||
_timeout:
|
||||
default: 86400
|
||||
description: Expiration timeout in seconds for the cache plugin data. Set to 0 to never expire.
|
||||
env:
|
||||
- name: ANSIBLE_CACHE_PLUGIN_TIMEOUT
|
||||
ini:
|
||||
- key: fact_caching_timeout
|
||||
section: defaults
|
||||
type: float
|
||||
"""
|
||||
|
||||
import pickle
|
||||
|
||||
from ansible.plugins.cache import BaseFileCacheModule
|
||||
|
||||
|
||||
class CacheModule(BaseFileCacheModule):
|
||||
"""
|
||||
A caching module backed by pickle files.
|
||||
"""
|
||||
|
||||
_persistent = False # prevent unnecessary JSON serialization and key munging
|
||||
|
||||
def _load(self, filepath):
|
||||
# Pickle is a binary format
|
||||
with open(filepath, "rb") as f:
|
||||
return pickle.load(f, encoding="bytes")
|
||||
|
||||
def _dump(self, value, filepath):
|
||||
with open(filepath, "wb") as f:
|
||||
# Use pickle protocol 2 which is compatible with Python 2.3+.
|
||||
pickle.dump(value, f, protocol=2)
|
||||
+238
@@ -0,0 +1,238 @@
|
||||
# Copyright (c) 2014, Brian Coca, Josh Drake, et al
|
||||
# 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: Unknown (!UNKNOWN)
|
||||
name: redis
|
||||
short_description: Use Redis DB for cache
|
||||
description:
|
||||
- This cache uses JSON formatted, per host records saved in Redis.
|
||||
requirements:
|
||||
- redis>=2.4.5 (python lib)
|
||||
options:
|
||||
_uri:
|
||||
description:
|
||||
- A colon separated string of connection information for Redis.
|
||||
- The format is V(host:port:db:password), for example V(localhost:6379:0:changeme).
|
||||
- To use encryption in transit, prefix the connection with V(tls://), as in V(tls://localhost:6379:0:changeme).
|
||||
- To use redis sentinel, use separator V(;), for example V(localhost:26379;localhost:26379;0:changeme). Requires redis>=2.9.0.
|
||||
type: string
|
||||
required: true
|
||||
env:
|
||||
- name: ANSIBLE_CACHE_PLUGIN_CONNECTION
|
||||
ini:
|
||||
- key: fact_caching_connection
|
||||
section: defaults
|
||||
_prefix:
|
||||
description: User defined prefix to use when creating the DB entries.
|
||||
type: string
|
||||
default: ansible_facts
|
||||
env:
|
||||
- name: ANSIBLE_CACHE_PLUGIN_PREFIX
|
||||
ini:
|
||||
- key: fact_caching_prefix
|
||||
section: defaults
|
||||
_keyset_name:
|
||||
description: User defined name for cache keyset name.
|
||||
type: string
|
||||
default: ansible_cache_keys
|
||||
env:
|
||||
- name: ANSIBLE_CACHE_REDIS_KEYSET_NAME
|
||||
ini:
|
||||
- key: fact_caching_redis_keyset_name
|
||||
section: defaults
|
||||
version_added: 1.3.0
|
||||
_sentinel_service_name:
|
||||
description: The redis sentinel service name (or referenced as cluster name).
|
||||
type: string
|
||||
env:
|
||||
- name: ANSIBLE_CACHE_REDIS_SENTINEL
|
||||
ini:
|
||||
- key: fact_caching_redis_sentinel
|
||||
section: defaults
|
||||
version_added: 1.3.0
|
||||
_timeout:
|
||||
default: 86400
|
||||
type: integer
|
||||
# TODO: determine whether it is OK to change to: type: float
|
||||
description: Expiration timeout in seconds for the cache plugin data. Set to 0 to never expire.
|
||||
env:
|
||||
- name: ANSIBLE_CACHE_PLUGIN_TIMEOUT
|
||||
ini:
|
||||
- key: fact_caching_timeout
|
||||
section: defaults
|
||||
"""
|
||||
|
||||
import json
|
||||
import re
|
||||
import time
|
||||
|
||||
from ansible.errors import AnsibleError
|
||||
from ansible.parsing.ajson import AnsibleJSONDecoder, AnsibleJSONEncoder
|
||||
from ansible.plugins.cache import BaseCacheModule
|
||||
from ansible.utils.display import Display
|
||||
|
||||
try:
|
||||
from redis import VERSION, StrictRedis
|
||||
|
||||
HAS_REDIS = True
|
||||
except ImportError:
|
||||
HAS_REDIS = False
|
||||
|
||||
display = Display()
|
||||
|
||||
|
||||
class CacheModule(BaseCacheModule):
|
||||
"""
|
||||
A caching module backed by redis.
|
||||
|
||||
Keys are maintained in a zset with their score being the timestamp
|
||||
when they are inserted. This allows for the usage of 'zremrangebyscore'
|
||||
to expire keys. This mechanism is used or a pattern matched 'scan' for
|
||||
performance.
|
||||
"""
|
||||
|
||||
_sentinel_service_name = None
|
||||
re_url_conn = re.compile(r"^([^:]+|\[[^]]+\]):(\d+):(\d+)(?::(.*))?$")
|
||||
re_sent_conn = re.compile(r"^(.*):(\d+)$")
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
uri = ""
|
||||
|
||||
super().__init__(*args, **kwargs)
|
||||
if self.get_option("_uri"):
|
||||
uri = self.get_option("_uri")
|
||||
self._timeout = float(self.get_option("_timeout"))
|
||||
self._prefix = self.get_option("_prefix")
|
||||
self._keys_set = self.get_option("_keyset_name")
|
||||
self._sentinel_service_name = self.get_option("_sentinel_service_name")
|
||||
|
||||
if not HAS_REDIS:
|
||||
raise AnsibleError(
|
||||
"The 'redis' python module (version 2.4.5 or newer) is required for the redis fact cache, 'pip install redis'"
|
||||
)
|
||||
|
||||
self._cache = {}
|
||||
kw = {}
|
||||
|
||||
# tls connection
|
||||
tlsprefix = "tls://"
|
||||
if uri.startswith(tlsprefix):
|
||||
kw["ssl"] = True
|
||||
uri = uri[len(tlsprefix) :]
|
||||
|
||||
# redis sentinel connection
|
||||
if self._sentinel_service_name:
|
||||
self._db = self._get_sentinel_connection(uri, kw)
|
||||
# normal connection
|
||||
else:
|
||||
connection = self._parse_connection(self.re_url_conn, uri)
|
||||
self._db = StrictRedis(*connection, **kw)
|
||||
|
||||
display.vv(f"Redis connection: {self._db}")
|
||||
|
||||
@staticmethod
|
||||
def _parse_connection(re_patt, uri):
|
||||
match = re_patt.match(uri)
|
||||
if not match:
|
||||
raise AnsibleError("Unable to parse connection string")
|
||||
return match.groups()
|
||||
|
||||
def _get_sentinel_connection(self, uri, kw):
|
||||
"""
|
||||
get sentinel connection details from _uri
|
||||
"""
|
||||
try:
|
||||
from redis.sentinel import Sentinel
|
||||
except ImportError as e:
|
||||
raise AnsibleError(
|
||||
"The 'redis' python module (version 2.9.0 or newer) is required to use redis sentinel."
|
||||
) from e
|
||||
|
||||
if ";" not in uri:
|
||||
raise AnsibleError("_uri does not have sentinel syntax.")
|
||||
|
||||
# format: "localhost:26379;localhost2:26379;0:changeme"
|
||||
connections = uri.split(";")
|
||||
connection_args = connections.pop(-1)
|
||||
if len(connection_args) > 0: # handle if no db nr is given
|
||||
connection_args = connection_args.split(":")
|
||||
kw["db"] = connection_args.pop(0)
|
||||
try:
|
||||
kw["password"] = connection_args.pop(0)
|
||||
except IndexError:
|
||||
pass # password is optional
|
||||
|
||||
sentinels = [self._parse_connection(self.re_sent_conn, shost) for shost in connections]
|
||||
display.vv(f"\nUsing redis sentinels: {sentinels}")
|
||||
scon = Sentinel(sentinels, **kw)
|
||||
try:
|
||||
return scon.master_for(self._sentinel_service_name, socket_timeout=0.2)
|
||||
except Exception as exc:
|
||||
raise AnsibleError(f"Could not connect to redis sentinel: {exc}") from exc
|
||||
|
||||
def _make_key(self, key):
|
||||
return self._prefix + key
|
||||
|
||||
def get(self, key):
|
||||
if key not in self._cache:
|
||||
value = self._db.get(self._make_key(key))
|
||||
# guard against the key not being removed from the zset;
|
||||
# this could happen in cases where the timeout value is changed
|
||||
# between invocations
|
||||
if value is None:
|
||||
self.delete(key)
|
||||
raise KeyError
|
||||
self._cache[key] = json.loads(value, cls=AnsibleJSONDecoder)
|
||||
|
||||
return self._cache.get(key)
|
||||
|
||||
def set(self, key, value):
|
||||
value2 = json.dumps(value, cls=AnsibleJSONEncoder, sort_keys=True, indent=4)
|
||||
if self._timeout > 0: # a timeout of 0 is handled as meaning 'never expire'
|
||||
self._db.setex(self._make_key(key), int(self._timeout), value2)
|
||||
else:
|
||||
self._db.set(self._make_key(key), value2)
|
||||
|
||||
if VERSION[0] == 2:
|
||||
self._db.zadd(self._keys_set, time.time(), key)
|
||||
else:
|
||||
self._db.zadd(self._keys_set, {key: time.time()})
|
||||
self._cache[key] = value
|
||||
|
||||
def _expire_keys(self):
|
||||
if self._timeout > 0:
|
||||
expiry_age = time.time() - self._timeout
|
||||
self._db.zremrangebyscore(self._keys_set, 0, expiry_age)
|
||||
|
||||
def keys(self):
|
||||
self._expire_keys()
|
||||
return self._db.zrange(self._keys_set, 0, -1)
|
||||
|
||||
def contains(self, key):
|
||||
self._expire_keys()
|
||||
return self._db.zrank(self._keys_set, key) is not None
|
||||
|
||||
def delete(self, key):
|
||||
if key in self._cache:
|
||||
del self._cache[key]
|
||||
self._db.delete(self._make_key(key))
|
||||
self._db.zrem(self._keys_set, key)
|
||||
|
||||
def flush(self):
|
||||
for key in list(self.keys()):
|
||||
self.delete(key)
|
||||
|
||||
def copy(self):
|
||||
# TODO: there is probably a better way to do this in redis
|
||||
ret = {k: self.get(k) for k in self.keys()}
|
||||
return ret
|
||||
|
||||
def __getstate__(self):
|
||||
return dict()
|
||||
|
||||
def __setstate__(self, data):
|
||||
self.__init__()
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
# Copyright (c) 2017, Brian Coca
|
||||
# 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"""
|
||||
name: yaml
|
||||
short_description: YAML formatted files
|
||||
description:
|
||||
- This cache uses YAML formatted, per host, files saved to the filesystem.
|
||||
author: Brian Coca (@bcoca)
|
||||
options:
|
||||
_uri:
|
||||
required: true
|
||||
description:
|
||||
- Path in which the cache plugin saves the files.
|
||||
env:
|
||||
- name: ANSIBLE_CACHE_PLUGIN_CONNECTION
|
||||
ini:
|
||||
- key: fact_caching_connection
|
||||
section: defaults
|
||||
type: string
|
||||
_prefix:
|
||||
description: User defined prefix to use when creating the files.
|
||||
env:
|
||||
- name: ANSIBLE_CACHE_PLUGIN_PREFIX
|
||||
ini:
|
||||
- key: fact_caching_prefix
|
||||
section: defaults
|
||||
type: string
|
||||
_timeout:
|
||||
default: 86400
|
||||
description: Expiration timeout in seconds for the cache plugin data. Set to 0 to never expire.
|
||||
env:
|
||||
- name: ANSIBLE_CACHE_PLUGIN_TIMEOUT
|
||||
ini:
|
||||
- key: fact_caching_timeout
|
||||
section: defaults
|
||||
type: integer
|
||||
# TODO: determine whether it is OK to change to: type: float
|
||||
"""
|
||||
|
||||
import os
|
||||
|
||||
import yaml
|
||||
from ansible.parsing.yaml.dumper import AnsibleDumper
|
||||
from ansible.parsing.yaml.loader import AnsibleLoader
|
||||
from ansible.plugins.cache import BaseFileCacheModule
|
||||
|
||||
|
||||
class CacheModule(BaseFileCacheModule):
|
||||
"""
|
||||
A caching module backed by yaml files.
|
||||
"""
|
||||
|
||||
def _load(self, filepath):
|
||||
with open(os.path.abspath(filepath), encoding="utf-8") as f:
|
||||
return AnsibleLoader(f).get_single_data()
|
||||
|
||||
def _dump(self, value, filepath):
|
||||
with open(os.path.abspath(filepath), "w", encoding="utf-8") as f:
|
||||
yaml.dump(value, f, Dumper=AnsibleDumper, default_flow_style=False)
|
||||
+119
@@ -0,0 +1,119 @@
|
||||
# Copyright (c) 2018 Matt Martz <matt@sivel.net>
|
||||
# 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: Unknown (!UNKNOWN)
|
||||
name: cgroup_memory_recap
|
||||
type: aggregate
|
||||
requirements:
|
||||
- whitelist in configuration
|
||||
- cgroups
|
||||
short_description: Profiles maximum memory usage of tasks and full execution using cgroups
|
||||
description:
|
||||
- This is an Ansible callback plugin that profiles maximum memory usage of Ansible and individual tasks, and displays a
|
||||
recap at the end using cgroups.
|
||||
notes:
|
||||
- Requires ansible to be run from within a C(cgroup), such as with C(cgexec -g memory:ansible_profile ansible-playbook ...).
|
||||
- This C(cgroup) should only be used by Ansible to get accurate results.
|
||||
- To create the C(cgroup), first use a command such as C(sudo cgcreate -a ec2-user:ec2-user -t ec2-user:ec2-user -g memory:ansible_profile).
|
||||
options:
|
||||
max_mem_file:
|
||||
required: true
|
||||
description: Path to cgroups C(memory.max_usage_in_bytes) file. Example V(/sys/fs/cgroup/memory/ansible_profile/memory.max_usage_in_bytes).
|
||||
type: str
|
||||
env:
|
||||
- name: CGROUP_MAX_MEM_FILE
|
||||
ini:
|
||||
- section: callback_cgroupmemrecap
|
||||
key: max_mem_file
|
||||
cur_mem_file:
|
||||
required: true
|
||||
description: Path to C(memory.usage_in_bytes) file. Example V(/sys/fs/cgroup/memory/ansible_profile/memory.usage_in_bytes).
|
||||
type: str
|
||||
env:
|
||||
- name: CGROUP_CUR_MEM_FILE
|
||||
ini:
|
||||
- section: callback_cgroupmemrecap
|
||||
key: cur_mem_file
|
||||
"""
|
||||
|
||||
import threading
|
||||
import time
|
||||
|
||||
from ansible.plugins.callback import CallbackBase
|
||||
|
||||
|
||||
class MemProf(threading.Thread):
|
||||
"""Python thread for recording memory usage"""
|
||||
|
||||
def __init__(self, path, obj=None):
|
||||
threading.Thread.__init__(self)
|
||||
self.obj = obj
|
||||
self.path = path
|
||||
self.results = []
|
||||
self.running = True
|
||||
|
||||
def run(self):
|
||||
while self.running:
|
||||
with open(self.path) as f:
|
||||
val = f.read()
|
||||
self.results.append(int(val.strip()) / 1024 / 1024)
|
||||
time.sleep(0.001)
|
||||
|
||||
|
||||
class CallbackModule(CallbackBase):
|
||||
CALLBACK_VERSION = 2.0
|
||||
CALLBACK_TYPE = "aggregate"
|
||||
CALLBACK_NAME = "community.general.cgroup_memory_recap"
|
||||
CALLBACK_NEEDS_WHITELIST = True
|
||||
|
||||
def __init__(self, display=None):
|
||||
super().__init__(display)
|
||||
|
||||
self._task_memprof = None
|
||||
|
||||
self.task_results = []
|
||||
|
||||
def set_options(self, task_keys=None, var_options=None, direct=None):
|
||||
super().set_options(task_keys=task_keys, var_options=var_options, direct=direct)
|
||||
|
||||
self.cgroup_max_file = self.get_option("max_mem_file")
|
||||
self.cgroup_current_file = self.get_option("cur_mem_file")
|
||||
|
||||
with open(self.cgroup_max_file, "w+") as f:
|
||||
f.write("0")
|
||||
|
||||
def _profile_memory(self, obj=None):
|
||||
prev_task = None
|
||||
results = None
|
||||
try:
|
||||
self._task_memprof.running = False
|
||||
results = self._task_memprof.results
|
||||
prev_task = self._task_memprof.obj
|
||||
except AttributeError:
|
||||
pass
|
||||
|
||||
if obj is not None:
|
||||
self._task_memprof = MemProf(self.cgroup_current_file, obj=obj)
|
||||
self._task_memprof.start()
|
||||
|
||||
if results is not None:
|
||||
self.task_results.append((prev_task, max(results)))
|
||||
|
||||
def v2_playbook_on_task_start(self, task, is_conditional):
|
||||
self._profile_memory(task)
|
||||
|
||||
def v2_playbook_on_stats(self, stats):
|
||||
self._profile_memory()
|
||||
|
||||
with open(self.cgroup_max_file) as f:
|
||||
max_results = int(f.read().strip()) / 1024 / 1024
|
||||
|
||||
self._display.banner("CGROUP MEMORY RECAP")
|
||||
self._display.display(f"Execution Maximum: {max_results:0.2f}MB\n\n")
|
||||
|
||||
for task, memory in self.task_results:
|
||||
self._display.display(f"{task.get_name()} ({task._uuid}): {memory:0.2f}MB")
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
# Copyright (C) 2012, Michael DeHaan, <michael.dehaan@gmail.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: Unknown (!UNKNOWN)
|
||||
name: context_demo
|
||||
type: aggregate
|
||||
short_description: Demo callback that adds play/task context
|
||||
description:
|
||||
- Displays some play and task context along with normal output.
|
||||
- This is mostly for demo purposes.
|
||||
requirements:
|
||||
- whitelist in configuration
|
||||
"""
|
||||
|
||||
from ansible.plugins.callback import CallbackBase
|
||||
|
||||
|
||||
class CallbackModule(CallbackBase):
|
||||
"""
|
||||
This is a very trivial example of how any callback function can get at play and task objects.
|
||||
play will be 'None' for runner invocations, and task will be None for 'setup' invocations.
|
||||
"""
|
||||
|
||||
CALLBACK_VERSION = 2.0
|
||||
CALLBACK_TYPE = "aggregate"
|
||||
CALLBACK_NAME = "community.general.context_demo"
|
||||
CALLBACK_NEEDS_WHITELIST = True
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self.task = None
|
||||
self.play = None
|
||||
|
||||
def v2_on_any(self, *args, **kwargs):
|
||||
self._display.display(f"--- play: {getattr(self.play, 'name', None)} task: {self.task} ---")
|
||||
|
||||
self._display.display(" --- ARGS ")
|
||||
for i, a in enumerate(args):
|
||||
self._display.display(f" {i}: {a}")
|
||||
|
||||
self._display.display(" --- KWARGS ")
|
||||
for k in kwargs:
|
||||
self._display.display(f" {k}: {kwargs[k]}")
|
||||
|
||||
def v2_playbook_on_play_start(self, play):
|
||||
self.play = play
|
||||
|
||||
def v2_playbook_on_task_start(self, task, is_conditional):
|
||||
self.task = task
|
||||
+245
@@ -0,0 +1,245 @@
|
||||
# Copyright (c) 2018, Ivan Aragones Muniesa <ivan.aragones.muniesa@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
|
||||
"""
|
||||
Counter enabled Ansible callback plugin (See DOCUMENTATION for more information)
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
DOCUMENTATION = r"""
|
||||
author: Unknown (!UNKNOWN)
|
||||
name: counter_enabled
|
||||
type: stdout
|
||||
short_description: Adds counters to the output items (tasks and hosts/task)
|
||||
description:
|
||||
- Use this callback when you need a kind of progress bar on a large environments.
|
||||
- You can see how many tasks has the playbook to run, and which one is actually running.
|
||||
- You can see how many hosts may run a task, and which of them is actually running.
|
||||
extends_documentation_fragment:
|
||||
- ansible.builtin.default_callback
|
||||
requirements:
|
||||
- set as stdout callback in C(ansible.cfg) (C(stdout_callback = counter_enabled))
|
||||
"""
|
||||
|
||||
from ansible import constants as C
|
||||
from ansible.playbook.task_include import TaskInclude
|
||||
from ansible.plugins.callback import CallbackBase
|
||||
from ansible.utils.color import colorize, hostcolor
|
||||
|
||||
|
||||
class CallbackModule(CallbackBase):
|
||||
"""
|
||||
This is the default callback interface, which simply prints messages
|
||||
to stdout when new callback events are received.
|
||||
"""
|
||||
|
||||
CALLBACK_VERSION = 2.0
|
||||
CALLBACK_TYPE = "stdout"
|
||||
CALLBACK_NAME = "community.general.counter_enabled"
|
||||
|
||||
_task_counter = 1
|
||||
_task_total = 0
|
||||
_host_counter = 1
|
||||
_host_total = 0
|
||||
_current_batch_total = 0
|
||||
_previous_batch_total = 0
|
||||
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
|
||||
self._playbook = ""
|
||||
self._play = ""
|
||||
|
||||
def _all_vars(self, host=None, task=None):
|
||||
# host and task need to be specified in case 'magic variables' (host vars, group vars, etc)
|
||||
# need to be loaded as well
|
||||
return self._play.get_variable_manager().get_vars(play=self._play, host=host, task=task)
|
||||
|
||||
def v2_playbook_on_start(self, playbook):
|
||||
self._playbook = playbook
|
||||
|
||||
def v2_playbook_on_play_start(self, play):
|
||||
name = play.get_name().strip()
|
||||
if not name:
|
||||
msg = "play"
|
||||
else:
|
||||
msg = f"PLAY [{name}]"
|
||||
|
||||
self._play = play
|
||||
|
||||
self._display.banner(msg)
|
||||
self._play = play
|
||||
|
||||
self._previous_batch_total = self._current_batch_total
|
||||
self._current_batch_total = self._previous_batch_total + len(self._all_vars()["vars"]["ansible_play_batch"])
|
||||
self._host_total = len(self._all_vars()["vars"]["ansible_play_hosts_all"])
|
||||
self._task_total = len(self._play.get_tasks()[0])
|
||||
self._task_counter = 1
|
||||
|
||||
def v2_playbook_on_stats(self, stats):
|
||||
self._display.banner("PLAY RECAP")
|
||||
|
||||
hosts = sorted(stats.processed.keys())
|
||||
for host in hosts:
|
||||
stat = stats.summarize(host)
|
||||
|
||||
self._display.display(
|
||||
f"{hostcolor(host, stat)} : {colorize('ok', stat['ok'], C.COLOR_OK)} {colorize('changed', stat['changed'], C.COLOR_CHANGED)} "
|
||||
f"{colorize('unreachable', stat['unreachable'], C.COLOR_UNREACHABLE)} {colorize('failed', stat['failures'], C.COLOR_ERROR)} "
|
||||
f"{colorize('rescued', stat['rescued'], C.COLOR_OK)} {colorize('ignored', stat['ignored'], C.COLOR_WARN)}",
|
||||
screen_only=True,
|
||||
)
|
||||
|
||||
self._display.display(
|
||||
f"{hostcolor(host, stat, False)} : {colorize('ok', stat['ok'], None)} {colorize('changed', stat['changed'], None)} "
|
||||
f"{colorize('unreachable', stat['unreachable'], None)} {colorize('failed', stat['failures'], None)} "
|
||||
f"{colorize('rescued', stat['rescued'], None)} {colorize('ignored', stat['ignored'], None)}",
|
||||
log_only=True,
|
||||
)
|
||||
|
||||
self._display.display("", screen_only=True)
|
||||
|
||||
# print custom stats
|
||||
if self._plugin_options.get("show_custom_stats", C.SHOW_CUSTOM_STATS) and stats.custom:
|
||||
# fallback on constants for inherited plugins missing docs
|
||||
self._display.banner("CUSTOM STATS: ")
|
||||
# per host
|
||||
# TODO: come up with 'pretty format'
|
||||
for k in sorted(stats.custom.keys()):
|
||||
if k == "_run":
|
||||
continue
|
||||
_custom_stats = self._dump_results(stats.custom[k], indent=1).replace("\n", "")
|
||||
self._display.display(f"\t{k}: {_custom_stats}")
|
||||
|
||||
# print per run custom stats
|
||||
if "_run" in stats.custom:
|
||||
self._display.display("", screen_only=True)
|
||||
_custom_stats_run = self._dump_results(stats.custom["_run"], indent=1).replace("\n", "")
|
||||
self._display.display(f"\tRUN: {_custom_stats_run}")
|
||||
self._display.display("", screen_only=True)
|
||||
|
||||
def v2_playbook_on_task_start(self, task, is_conditional):
|
||||
args = ""
|
||||
# args can be specified as no_log in several places: in the task or in
|
||||
# the argument spec. We can check whether the task is no_log but the
|
||||
# argument spec can't be because that is only run on the target
|
||||
# machine and we haven't run it there yet at this time.
|
||||
#
|
||||
# So we give people a config option to affect display of the args so
|
||||
# that they can secure this if they feel that their stdout is insecure
|
||||
# (shoulder surfing, logging stdout straight to a file, etc).
|
||||
if not task.no_log and C.DISPLAY_ARGS_TO_STDOUT:
|
||||
args = ", ".join(("{k}={v}" for k, v in task.args.items()))
|
||||
args = f" {args}"
|
||||
self._display.banner(f"TASK {self._task_counter}/{self._task_total} [{task.get_name().strip()}{args}]")
|
||||
if self._display.verbosity >= 2:
|
||||
path = task.get_path()
|
||||
if path:
|
||||
self._display.display(f"task path: {path}", color=C.COLOR_DEBUG)
|
||||
self._host_counter = self._previous_batch_total
|
||||
self._task_counter += 1
|
||||
|
||||
def _host_label(self, result):
|
||||
host_name = result._host.get_name()
|
||||
delegate_to = result._task.delegate_to
|
||||
if delegate_to and delegate_to != host_name:
|
||||
delegated_vars = result._result.get("_ansible_delegated_vars", {})
|
||||
ahost = delegated_vars.get("ansible_host", delegate_to)
|
||||
label = f"{host_name} -> {delegate_to}"
|
||||
if ahost != delegate_to:
|
||||
label += f"({ahost})"
|
||||
return f"[{label}]"
|
||||
return f"[{host_name}]"
|
||||
|
||||
def _display_result_ok(self, result, counter_str="", item_suffix=""):
|
||||
if isinstance(result._task, TaskInclude):
|
||||
return
|
||||
elif result._result.get("changed", False):
|
||||
msg = f"changed: {counter_str}{self._host_label(result)}{item_suffix}"
|
||||
color = C.COLOR_CHANGED
|
||||
else:
|
||||
if not self._plugin_options.get("display_ok_hosts", True):
|
||||
return
|
||||
msg = f"ok: {counter_str}{self._host_label(result)}{item_suffix}"
|
||||
color = C.COLOR_OK
|
||||
|
||||
self._handle_warnings(result._result)
|
||||
self._clean_results(result._result, result._task.action)
|
||||
if self._run_is_verbose(result):
|
||||
msg += f" => {self._dump_results(result._result)}"
|
||||
self._display.display(msg, color=color)
|
||||
|
||||
def v2_runner_on_ok(self, result):
|
||||
self._host_counter += 1
|
||||
|
||||
if self._play.strategy == "free" and self._last_task_banner != result._task._uuid:
|
||||
self._print_task_banner(result._task)
|
||||
|
||||
if result._task.loop and "results" in result._result:
|
||||
self._process_items(result)
|
||||
else:
|
||||
self._display_result_ok(result, f"{self._host_counter}/{self._host_total} ")
|
||||
|
||||
def v2_runner_item_on_ok(self, result):
|
||||
self._display_result_ok(result, item_suffix=f" => (item={self._get_item_label(result._result)})")
|
||||
|
||||
def _display_result_failed(self, result, counter_str="", item_suffix=""):
|
||||
self._clean_results(result._result, result._task.action)
|
||||
self._handle_warnings(result._result)
|
||||
prefix = "failed" if item_suffix else "fatal"
|
||||
msg = f"{prefix}: {counter_str}{self._host_label(result)}{item_suffix}"
|
||||
self._display.display(f"{msg} => {self._dump_results(result._result)}", color=C.COLOR_ERROR)
|
||||
|
||||
def v2_runner_item_on_failed(self, result):
|
||||
self._display_result_failed(result, item_suffix=f" (item={self._get_item_label(result._result)})")
|
||||
|
||||
def _display_result_skipped(self, result, counter_str="", item_suffix=""):
|
||||
self._clean_results(result._result, result._task.action)
|
||||
msg = f"skipping: {counter_str}[{result._host.get_name()}]{item_suffix}"
|
||||
if self._run_is_verbose(result):
|
||||
msg += f" => {self._dump_results(result._result)}"
|
||||
self._display.display(msg, color=C.COLOR_SKIP)
|
||||
|
||||
def v2_runner_item_on_skipped(self, result):
|
||||
if self._plugin_options.get("show_skipped_hosts", C.DISPLAY_SKIPPED_HOSTS):
|
||||
self._display_result_skipped(result, item_suffix=f" => (item={self._get_item_label(result._result)})")
|
||||
|
||||
def v2_runner_on_failed(self, result, ignore_errors=False):
|
||||
self._host_counter += 1
|
||||
|
||||
if self._play.strategy == "free" and self._last_task_banner != result._task._uuid:
|
||||
self._print_task_banner(result._task)
|
||||
|
||||
self._handle_exception(result._result)
|
||||
|
||||
if result._task.loop and "results" in result._result:
|
||||
self._process_items(result)
|
||||
else:
|
||||
self._display_result_failed(result, f"{self._host_counter}/{self._host_total} ", ": FAILED!")
|
||||
|
||||
if ignore_errors:
|
||||
self._display.display("...ignoring", color=C.COLOR_SKIP)
|
||||
|
||||
def v2_runner_on_skipped(self, result):
|
||||
self._host_counter += 1
|
||||
|
||||
if self._plugin_options.get("show_skipped_hosts", C.DISPLAY_SKIPPED_HOSTS):
|
||||
if self._play.strategy == "free" and self._last_task_banner != result._task._uuid:
|
||||
self._print_task_banner(result._task)
|
||||
|
||||
if result._task.loop and "results" in result._result:
|
||||
self._process_items(result)
|
||||
else:
|
||||
self._display_result_skipped(result, f"{self._host_counter}/{self._host_total} ")
|
||||
|
||||
def v2_runner_on_unreachable(self, result):
|
||||
self._host_counter += 1
|
||||
|
||||
if self._play.strategy == "free" and self._last_task_banner != result._task._uuid:
|
||||
self._print_task_banner(result._task)
|
||||
|
||||
self._display.display(
|
||||
f"fatal: {self._host_counter}/{self._host_total} {self._host_label(result)}: UNREACHABLE! => {self._dump_results(result._result)}",
|
||||
color=C.COLOR_UNREACHABLE,
|
||||
)
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
# Copyright (c) 2024, Felix Fontein <felix@fontein.de>
|
||||
# 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"""
|
||||
name: default_without_diff
|
||||
type: stdout
|
||||
short_description: The default ansible callback without diff output
|
||||
version_added: 8.4.0
|
||||
description:
|
||||
- This is basically the default ansible callback plugin (P(ansible.builtin.default#callback)) without showing diff output.
|
||||
This can be useful when using another callback which sends more detailed information to another service, like the L(ARA,
|
||||
https://ara.recordsansible.org/) callback, and you want diff output sent to that plugin but not shown on the console output.
|
||||
author: Felix Fontein (@felixfontein)
|
||||
extends_documentation_fragment:
|
||||
- ansible.builtin.default_callback
|
||||
- ansible.builtin.result_format_callback
|
||||
"""
|
||||
|
||||
EXAMPLES = r"""
|
||||
# Enable callback in ansible.cfg:
|
||||
ansible_config: |
|
||||
[defaults]
|
||||
stdout_callback = community.general.default_without_diff
|
||||
|
||||
# Enable callback with environment variables:
|
||||
environment_variable: |-
|
||||
ANSIBLE_STDOUT_CALLBACK=community.general.default_without_diff
|
||||
"""
|
||||
|
||||
from ansible.plugins.callback.default import CallbackModule as Default
|
||||
|
||||
|
||||
class CallbackModule(Default):
|
||||
CALLBACK_VERSION = 2.0
|
||||
CALLBACK_TYPE = "stdout"
|
||||
CALLBACK_NAME = "community.general.default_without_diff"
|
||||
|
||||
def v2_on_file_diff(self, result):
|
||||
pass
|
||||
@@ -0,0 +1,490 @@
|
||||
# Copyright (c) 2016, Dag Wieers <dag@wieers.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"""
|
||||
name: dense
|
||||
type: stdout
|
||||
short_description: Minimal stdout output
|
||||
extends_documentation_fragment:
|
||||
- ansible.builtin.default_callback
|
||||
description:
|
||||
- When in verbose mode it acts the same as the default callback.
|
||||
author:
|
||||
- Dag Wieers (@dagwieers)
|
||||
requirements:
|
||||
- set as stdout in configuration
|
||||
"""
|
||||
|
||||
HAS_OD = False
|
||||
try:
|
||||
from collections import OrderedDict
|
||||
|
||||
HAS_OD = True
|
||||
except ImportError:
|
||||
pass
|
||||
|
||||
import sys
|
||||
from collections.abc import MutableMapping, MutableSequence
|
||||
|
||||
from ansible.plugins.callback.default import CallbackModule as CallbackModule_default
|
||||
from ansible.utils.color import colorize, hostcolor
|
||||
from ansible.utils.display import Display
|
||||
|
||||
display = Display()
|
||||
|
||||
|
||||
# Design goals:
|
||||
#
|
||||
# + On screen there should only be relevant stuff
|
||||
# - How far are we ? (during run, last line)
|
||||
# - What issues occurred
|
||||
# - What changes occurred
|
||||
# - Diff output (in diff-mode)
|
||||
#
|
||||
# + If verbosity increases, act as default output
|
||||
# So that users can easily switch to default for troubleshooting
|
||||
#
|
||||
# + Rewrite the output during processing
|
||||
# - We use the cursor to indicate where in the task we are.
|
||||
# Output after the prompt is the output of the previous task.
|
||||
# - If we would clear the line at the start of a task, there would often
|
||||
# be no information at all, so we leave it until it gets updated
|
||||
#
|
||||
# + Use the same color-conventions of Ansible
|
||||
#
|
||||
# + Ensure the verbose output (-v) is also dense.
|
||||
# Remove information that is not essential (eg. timestamps, status)
|
||||
|
||||
|
||||
# TODO:
|
||||
#
|
||||
# + Properly test for terminal capabilities, and fall back to default
|
||||
# + Modify Ansible mechanism so we don't need to use sys.stdout directly
|
||||
# + Find an elegant solution for progress bar line wrapping
|
||||
|
||||
|
||||
# FIXME: Importing constants as C simply does not work, beats me :-/
|
||||
# from ansible import constants as C
|
||||
class C:
|
||||
COLOR_HIGHLIGHT = "white"
|
||||
COLOR_VERBOSE = "blue"
|
||||
COLOR_WARN = "bright purple"
|
||||
COLOR_ERROR = "red"
|
||||
COLOR_DEBUG = "dark gray"
|
||||
COLOR_DEPRECATE = "purple"
|
||||
COLOR_SKIP = "cyan"
|
||||
COLOR_UNREACHABLE = "bright red"
|
||||
COLOR_OK = "green"
|
||||
COLOR_CHANGED = "yellow"
|
||||
|
||||
|
||||
# Taken from Dstat
|
||||
class vt100:
|
||||
black = "\033[0;30m"
|
||||
darkred = "\033[0;31m"
|
||||
darkgreen = "\033[0;32m"
|
||||
darkyellow = "\033[0;33m"
|
||||
darkblue = "\033[0;34m"
|
||||
darkmagenta = "\033[0;35m"
|
||||
darkcyan = "\033[0;36m"
|
||||
gray = "\033[0;37m"
|
||||
|
||||
darkgray = "\033[1;30m"
|
||||
red = "\033[1;31m"
|
||||
green = "\033[1;32m"
|
||||
yellow = "\033[1;33m"
|
||||
blue = "\033[1;34m"
|
||||
magenta = "\033[1;35m"
|
||||
cyan = "\033[1;36m"
|
||||
white = "\033[1;37m"
|
||||
|
||||
blackbg = "\033[40m"
|
||||
redbg = "\033[41m"
|
||||
greenbg = "\033[42m"
|
||||
yellowbg = "\033[43m"
|
||||
bluebg = "\033[44m"
|
||||
magentabg = "\033[45m"
|
||||
cyanbg = "\033[46m"
|
||||
whitebg = "\033[47m"
|
||||
|
||||
reset = "\033[0;0m"
|
||||
bold = "\033[1m"
|
||||
reverse = "\033[2m"
|
||||
underline = "\033[4m"
|
||||
|
||||
clear = "\033[2J"
|
||||
# clearline = '\033[K'
|
||||
clearline = "\033[2K"
|
||||
save = "\033[s"
|
||||
restore = "\033[u"
|
||||
save_all = "\0337"
|
||||
restore_all = "\0338"
|
||||
linewrap = "\033[7h"
|
||||
nolinewrap = "\033[7l"
|
||||
|
||||
up = "\033[1A"
|
||||
down = "\033[1B"
|
||||
right = "\033[1C"
|
||||
left = "\033[1D"
|
||||
|
||||
|
||||
colors = dict(
|
||||
ok=vt100.darkgreen,
|
||||
changed=vt100.darkyellow,
|
||||
skipped=vt100.darkcyan,
|
||||
ignored=vt100.cyanbg + vt100.red,
|
||||
failed=vt100.darkred,
|
||||
unreachable=vt100.red,
|
||||
)
|
||||
|
||||
states = ("skipped", "ok", "changed", "failed", "unreachable")
|
||||
|
||||
|
||||
class CallbackModule(CallbackModule_default):
|
||||
"""
|
||||
This is the dense callback interface, where screen estate is still valued.
|
||||
"""
|
||||
|
||||
CALLBACK_VERSION = 2.0
|
||||
CALLBACK_TYPE = "stdout"
|
||||
CALLBACK_NAME = "dense"
|
||||
|
||||
def __init__(self):
|
||||
# From CallbackModule
|
||||
self._display = display
|
||||
|
||||
if HAS_OD:
|
||||
self.disabled = False
|
||||
self.super_ref = super()
|
||||
self.super_ref.__init__()
|
||||
|
||||
# Attributes to remove from results for more density
|
||||
self.removed_attributes = (
|
||||
# 'changed',
|
||||
"delta",
|
||||
# 'diff',
|
||||
"end",
|
||||
"failed",
|
||||
"failed_when_result",
|
||||
"invocation",
|
||||
"start",
|
||||
"stdout_lines",
|
||||
)
|
||||
|
||||
# Initiate data structures
|
||||
self.hosts = OrderedDict()
|
||||
self.keep = False
|
||||
self.shown_title = False
|
||||
self.count = dict(play=0, handler=0, task=0)
|
||||
self.type = "foo"
|
||||
|
||||
# Start immediately on the first line
|
||||
sys.stdout.write(vt100.reset + vt100.save + vt100.clearline)
|
||||
sys.stdout.flush()
|
||||
else:
|
||||
display.warning(
|
||||
"The 'dense' callback plugin requires OrderedDict which is not available in this version of python, disabling."
|
||||
)
|
||||
self.disabled = True
|
||||
|
||||
def __del__(self):
|
||||
sys.stdout.write(f"{vt100.restore}{vt100.reset}\n{vt100.save}{vt100.clearline}")
|
||||
|
||||
def _add_host(self, result, status):
|
||||
name = result._host.get_name()
|
||||
|
||||
# Add a new status in case a failed task is ignored
|
||||
if status == "failed" and result._task.ignore_errors:
|
||||
status = "ignored"
|
||||
|
||||
# Check if we have to update an existing state (when looping over items)
|
||||
if name not in self.hosts:
|
||||
self.hosts[name] = dict(state=status)
|
||||
elif states.index(self.hosts[name]["state"]) < states.index(status):
|
||||
self.hosts[name]["state"] = status
|
||||
|
||||
# Store delegated hostname, if needed
|
||||
delegated_vars = result._result.get("_ansible_delegated_vars", None)
|
||||
if delegated_vars:
|
||||
self.hosts[name]["delegate"] = delegated_vars["ansible_host"]
|
||||
|
||||
# Print progress bar
|
||||
self._display_progress(result)
|
||||
|
||||
# # Ensure that tasks with changes/failures stay on-screen, and during diff-mode
|
||||
# if status in ['changed', 'failed', 'unreachable'] or (result.get('_diff_mode', False) and result._resultget('diff', False)):
|
||||
# Ensure that tasks with changes/failures stay on-screen
|
||||
if status in ["changed", "failed", "unreachable"]:
|
||||
self.keep = True
|
||||
|
||||
if self._display.verbosity == 1:
|
||||
# Print task title, if needed
|
||||
self._display_task_banner()
|
||||
self._display_results(result, status)
|
||||
|
||||
def _clean_results(self, result):
|
||||
# Remove non-essential attributes
|
||||
for attr in self.removed_attributes:
|
||||
if attr in result:
|
||||
del result[attr]
|
||||
|
||||
# Remove empty attributes (list, dict, str)
|
||||
for attr in result.copy():
|
||||
if isinstance(result[attr], (MutableSequence, MutableMapping, bytes, str)):
|
||||
if not result[attr]:
|
||||
del result[attr]
|
||||
|
||||
def _handle_exceptions(self, result):
|
||||
if "exception" in result:
|
||||
# Remove the exception from the result so it is not shown every time
|
||||
del result["exception"]
|
||||
|
||||
if self._display.verbosity == 1:
|
||||
return "An exception occurred during task execution. To see the full traceback, use -vvv."
|
||||
|
||||
def _display_progress(self, result=None):
|
||||
# Always rewrite the complete line
|
||||
sys.stdout.write(vt100.restore + vt100.reset + vt100.clearline + vt100.nolinewrap + vt100.underline)
|
||||
sys.stdout.write(f"{self.type} {self.count[self.type]}:")
|
||||
sys.stdout.write(vt100.reset)
|
||||
sys.stdout.flush()
|
||||
|
||||
# Print out each host in its own status-color
|
||||
for name in self.hosts:
|
||||
sys.stdout.write(" ")
|
||||
if self.hosts[name].get("delegate", None):
|
||||
sys.stdout.write(f"{self.hosts[name]['delegate']}>")
|
||||
sys.stdout.write(colors[self.hosts[name]["state"]] + name + vt100.reset)
|
||||
sys.stdout.flush()
|
||||
|
||||
sys.stdout.write(vt100.linewrap)
|
||||
|
||||
def _display_task_banner(self):
|
||||
if not self.shown_title:
|
||||
self.shown_title = True
|
||||
sys.stdout.write(vt100.restore + vt100.reset + vt100.clearline + vt100.underline)
|
||||
sys.stdout.write(f"{self.type} {self.count[self.type]}: {self.task.get_name().strip()}")
|
||||
sys.stdout.write(f"{vt100.restore}{vt100.reset}\n{vt100.save}{vt100.clearline}")
|
||||
sys.stdout.flush()
|
||||
else:
|
||||
sys.stdout.write(vt100.restore + vt100.reset + vt100.clearline)
|
||||
self.keep = False
|
||||
|
||||
def _display_results(self, result, status):
|
||||
# Leave the previous task on screen (as it has changes/errors)
|
||||
if self._display.verbosity == 0 and self.keep:
|
||||
sys.stdout.write(f"{vt100.restore}{vt100.reset}\n{vt100.save}{vt100.clearline}")
|
||||
else:
|
||||
sys.stdout.write(vt100.restore + vt100.reset + vt100.clearline)
|
||||
self.keep = False
|
||||
|
||||
self._clean_results(result._result)
|
||||
|
||||
dump = ""
|
||||
if result._task.action == "include":
|
||||
return
|
||||
elif status == "ok":
|
||||
return
|
||||
elif status == "ignored":
|
||||
dump = self._handle_exceptions(result._result)
|
||||
elif status == "failed":
|
||||
dump = self._handle_exceptions(result._result)
|
||||
elif status == "unreachable":
|
||||
dump = result._result["msg"]
|
||||
|
||||
if not dump:
|
||||
dump = self._dump_results(result._result)
|
||||
|
||||
if result._task.loop and "results" in result._result:
|
||||
self._process_items(result)
|
||||
else:
|
||||
sys.stdout.write(f"{colors[status] + status}: ")
|
||||
|
||||
delegated_vars = result._result.get("_ansible_delegated_vars", None)
|
||||
if delegated_vars:
|
||||
sys.stdout.write(
|
||||
f"{vt100.reset}{result._host.get_name()}>{colors[status]}{delegated_vars['ansible_host']}"
|
||||
)
|
||||
else:
|
||||
sys.stdout.write(result._host.get_name())
|
||||
|
||||
sys.stdout.write(f": {dump}\n")
|
||||
sys.stdout.write(f"{vt100.reset}{vt100.save}{vt100.clearline}")
|
||||
sys.stdout.flush()
|
||||
|
||||
if status == "changed":
|
||||
self._handle_warnings(result._result)
|
||||
|
||||
def v2_playbook_on_play_start(self, play):
|
||||
# Leave the previous task on screen (as it has changes/errors)
|
||||
if self._display.verbosity == 0 and self.keep:
|
||||
sys.stdout.write(f"{vt100.restore}{vt100.reset}\n{vt100.save}{vt100.clearline}{vt100.bold}")
|
||||
else:
|
||||
sys.stdout.write(vt100.restore + vt100.reset + vt100.clearline + vt100.bold)
|
||||
|
||||
# Reset at the start of each play
|
||||
self.keep = False
|
||||
self.count.update(dict(handler=0, task=0))
|
||||
self.count["play"] += 1
|
||||
self.play = play
|
||||
|
||||
# Write the next play on screen IN UPPERCASE, and make it permanent
|
||||
name = play.get_name().strip()
|
||||
if not name:
|
||||
name = "unnamed"
|
||||
sys.stdout.write(f"PLAY {self.count['play']}: {name.upper()}")
|
||||
sys.stdout.write(f"{vt100.restore}{vt100.reset}\n{vt100.save}{vt100.clearline}")
|
||||
sys.stdout.flush()
|
||||
|
||||
def v2_playbook_on_task_start(self, task, is_conditional):
|
||||
# Leave the previous task on screen (as it has changes/errors)
|
||||
if self._display.verbosity == 0 and self.keep:
|
||||
sys.stdout.write(f"{vt100.restore}{vt100.reset}\n{vt100.save}{vt100.clearline}{vt100.underline}")
|
||||
else:
|
||||
# Do not clear line, since we want to retain the previous output
|
||||
sys.stdout.write(vt100.restore + vt100.reset + vt100.underline)
|
||||
|
||||
# Reset at the start of each task
|
||||
self.keep = False
|
||||
self.shown_title = False
|
||||
self.hosts = OrderedDict()
|
||||
self.task = task
|
||||
self.type = "task"
|
||||
|
||||
# Enumerate task if not setup (task names are too long for dense output)
|
||||
if task.get_name() != "setup":
|
||||
self.count["task"] += 1
|
||||
|
||||
# Write the next task on screen (behind the prompt is the previous output)
|
||||
sys.stdout.write(f"{self.type} {self.count[self.type]}.")
|
||||
sys.stdout.write(vt100.reset)
|
||||
sys.stdout.flush()
|
||||
|
||||
def v2_playbook_on_handler_task_start(self, task):
|
||||
# Leave the previous task on screen (as it has changes/errors)
|
||||
if self._display.verbosity == 0 and self.keep:
|
||||
sys.stdout.write(f"{vt100.restore}{vt100.reset}\n{vt100.save}{vt100.clearline}{vt100.underline}")
|
||||
else:
|
||||
sys.stdout.write(vt100.restore + vt100.reset + vt100.clearline + vt100.underline)
|
||||
|
||||
# Reset at the start of each handler
|
||||
self.keep = False
|
||||
self.shown_title = False
|
||||
self.hosts = OrderedDict()
|
||||
self.task = task
|
||||
self.type = "handler"
|
||||
|
||||
# Enumerate handler if not setup (handler names may be too long for dense output)
|
||||
if task.get_name() != "setup":
|
||||
self.count[self.type] += 1
|
||||
|
||||
# Write the next task on screen (behind the prompt is the previous output)
|
||||
sys.stdout.write(f"{self.type} {self.count[self.type]}.")
|
||||
sys.stdout.write(vt100.reset)
|
||||
sys.stdout.flush()
|
||||
|
||||
def v2_playbook_on_cleanup_task_start(self, task):
|
||||
# TBD
|
||||
sys.stdout.write("cleanup.")
|
||||
sys.stdout.flush()
|
||||
|
||||
def v2_runner_on_failed(self, result, ignore_errors=False):
|
||||
self._add_host(result, "failed")
|
||||
|
||||
def v2_runner_on_ok(self, result):
|
||||
if result._result.get("changed", False):
|
||||
self._add_host(result, "changed")
|
||||
else:
|
||||
self._add_host(result, "ok")
|
||||
|
||||
def v2_runner_on_skipped(self, result):
|
||||
self._add_host(result, "skipped")
|
||||
|
||||
def v2_runner_on_unreachable(self, result):
|
||||
self._add_host(result, "unreachable")
|
||||
|
||||
def v2_runner_on_include(self, included_file):
|
||||
pass
|
||||
|
||||
def v2_runner_on_file_diff(self, result, diff):
|
||||
sys.stdout.write(vt100.bold)
|
||||
self.super_ref.v2_runner_on_file_diff(result, diff)
|
||||
sys.stdout.write(vt100.reset)
|
||||
|
||||
def v2_on_file_diff(self, result):
|
||||
sys.stdout.write(vt100.bold)
|
||||
self.super_ref.v2_on_file_diff(result)
|
||||
sys.stdout.write(vt100.reset)
|
||||
|
||||
# Old definition in v2.0
|
||||
def v2_playbook_item_on_ok(self, result):
|
||||
self.v2_runner_item_on_ok(result)
|
||||
|
||||
def v2_runner_item_on_ok(self, result):
|
||||
if result._result.get("changed", False):
|
||||
self._add_host(result, "changed")
|
||||
else:
|
||||
self._add_host(result, "ok")
|
||||
|
||||
# Old definition in v2.0
|
||||
def v2_playbook_item_on_failed(self, result):
|
||||
self.v2_runner_item_on_failed(result)
|
||||
|
||||
def v2_runner_item_on_failed(self, result):
|
||||
self._add_host(result, "failed")
|
||||
|
||||
# Old definition in v2.0
|
||||
def v2_playbook_item_on_skipped(self, result):
|
||||
self.v2_runner_item_on_skipped(result)
|
||||
|
||||
def v2_runner_item_on_skipped(self, result):
|
||||
self._add_host(result, "skipped")
|
||||
|
||||
def v2_playbook_on_no_hosts_remaining(self):
|
||||
if self._display.verbosity == 0 and self.keep:
|
||||
sys.stdout.write(f"{vt100.restore}{vt100.reset}\n{vt100.save}{vt100.clearline}")
|
||||
else:
|
||||
sys.stdout.write(vt100.restore + vt100.reset + vt100.clearline)
|
||||
self.keep = False
|
||||
|
||||
sys.stdout.write(f"{vt100.white + vt100.redbg}NO MORE HOSTS LEFT")
|
||||
sys.stdout.write(f"{vt100.restore}{vt100.reset}\n{vt100.save}{vt100.clearline}")
|
||||
sys.stdout.flush()
|
||||
|
||||
def v2_playbook_on_include(self, included_file):
|
||||
pass
|
||||
|
||||
def v2_playbook_on_stats(self, stats):
|
||||
if self._display.verbosity == 0 and self.keep:
|
||||
sys.stdout.write(f"{vt100.restore}{vt100.reset}\n{vt100.save}{vt100.clearline}")
|
||||
else:
|
||||
sys.stdout.write(vt100.restore + vt100.reset + vt100.clearline)
|
||||
|
||||
# In normal mode screen output should be sufficient, summary is redundant
|
||||
if self._display.verbosity == 0:
|
||||
return
|
||||
|
||||
sys.stdout.write(vt100.bold + vt100.underline)
|
||||
sys.stdout.write("SUMMARY")
|
||||
|
||||
sys.stdout.write(f"{vt100.restore}{vt100.reset}\n{vt100.save}{vt100.clearline}")
|
||||
sys.stdout.flush()
|
||||
|
||||
hosts = sorted(stats.processed.keys())
|
||||
for h in hosts:
|
||||
t = stats.summarize(h)
|
||||
self._display.display(
|
||||
f"{hostcolor(h, t)} : {colorize('ok', t['ok'], C.COLOR_OK)} {colorize('changed', t['changed'], C.COLOR_CHANGED)} "
|
||||
f"{colorize('unreachable', t['unreachable'], C.COLOR_UNREACHABLE)} {colorize('failed', t['failures'], C.COLOR_ERROR)} "
|
||||
f"{colorize('rescued', t['rescued'], C.COLOR_OK)} {colorize('ignored', t['ignored'], C.COLOR_WARN)}",
|
||||
screen_only=True,
|
||||
)
|
||||
|
||||
|
||||
# When using -vv or higher, simply do the default action
|
||||
if display.verbosity >= 2 or not HAS_OD:
|
||||
CallbackModule = CallbackModule_default # type: ignore
|
||||
File diff suppressed because it is too large
Load Diff
+411
@@ -0,0 +1,411 @@
|
||||
# Copyright (c) 2021, Victor Martinez <VictorMartinezRubio@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
|
||||
|
||||
DOCUMENTATION = r"""
|
||||
author: Victor Martinez (@v1v) <VictorMartinezRubio@gmail.com>
|
||||
name: elastic
|
||||
type: notification
|
||||
short_description: Create distributed traces for each Ansible task in Elastic APM
|
||||
version_added: 3.8.0
|
||||
description:
|
||||
- This callback creates distributed traces for each Ansible task in Elastic APM.
|
||||
- You can configure the plugin with environment variables.
|
||||
- See U(https://www.elastic.co/guide/en/apm/agent/python/current/configuration.html).
|
||||
options:
|
||||
hide_task_arguments:
|
||||
default: false
|
||||
type: bool
|
||||
description:
|
||||
- Hide the arguments for a task.
|
||||
env:
|
||||
- name: ANSIBLE_OPENTELEMETRY_HIDE_TASK_ARGUMENTS
|
||||
apm_service_name:
|
||||
default: ansible
|
||||
type: str
|
||||
description:
|
||||
- The service name resource attribute.
|
||||
env:
|
||||
- name: ELASTIC_APM_SERVICE_NAME
|
||||
apm_server_url:
|
||||
type: str
|
||||
description:
|
||||
- Use the APM server and its environment variables.
|
||||
env:
|
||||
- name: ELASTIC_APM_SERVER_URL
|
||||
apm_secret_token:
|
||||
type: str
|
||||
description:
|
||||
- Use the APM server token.
|
||||
env:
|
||||
- name: ELASTIC_APM_SECRET_TOKEN
|
||||
secret: true
|
||||
apm_api_key:
|
||||
type: str
|
||||
description:
|
||||
- Use the APM API key.
|
||||
env:
|
||||
- name: ELASTIC_APM_API_KEY
|
||||
secret: true
|
||||
apm_verify_server_cert:
|
||||
default: true
|
||||
type: bool
|
||||
description:
|
||||
- Verifies the SSL certificate if an HTTPS connection.
|
||||
env:
|
||||
- name: ELASTIC_APM_VERIFY_SERVER_CERT
|
||||
traceparent:
|
||||
type: str
|
||||
description:
|
||||
- The L(W3C Trace Context header traceparent,https://www.w3.org/TR/trace-context-1/#traceparent-header).
|
||||
env:
|
||||
- name: TRACEPARENT
|
||||
requirements:
|
||||
- elastic-apm (Python library)
|
||||
"""
|
||||
|
||||
|
||||
EXAMPLES = r"""
|
||||
examples: |-
|
||||
Enable the plugin in ansible.cfg:
|
||||
[defaults]
|
||||
callbacks_enabled = community.general.elastic
|
||||
|
||||
Set the environment variable:
|
||||
export ELASTIC_APM_SERVER_URL=<your APM server URL)>
|
||||
export ELASTIC_APM_SERVICE_NAME=your_service_name
|
||||
export ELASTIC_APM_API_KEY=your_APM_API_KEY
|
||||
"""
|
||||
|
||||
import getpass
|
||||
import socket
|
||||
import time
|
||||
import uuid
|
||||
from collections import OrderedDict
|
||||
from contextlib import closing
|
||||
from os.path import basename
|
||||
|
||||
from ansible.errors import AnsibleError, AnsibleRuntimeError
|
||||
from ansible.module_utils.ansible_release import __version__ as ansible_version
|
||||
from ansible.plugins.callback import CallbackBase
|
||||
|
||||
from ansible_collections.community.general.plugins.module_utils._secrets import mask_secret_values, mask_secrets
|
||||
|
||||
ELASTIC_LIBRARY_IMPORT_ERROR: ImportError | None
|
||||
try:
|
||||
from elasticapm import Client, capture_span, instrument, label, trace_parent_from_string
|
||||
except ImportError as imp_exc:
|
||||
ELASTIC_LIBRARY_IMPORT_ERROR = imp_exc
|
||||
else:
|
||||
ELASTIC_LIBRARY_IMPORT_ERROR = None
|
||||
|
||||
|
||||
class TaskData:
|
||||
"""
|
||||
Data about an individual task.
|
||||
"""
|
||||
|
||||
def __init__(self, uuid: str, name: str, path: str, play: str, action: str, args) -> None:
|
||||
self.uuid = uuid
|
||||
self.name = name
|
||||
self.path = path
|
||||
self.play = play
|
||||
self.host_data: dict[str, HostData] = OrderedDict()
|
||||
self.start = time.time()
|
||||
self.action = action
|
||||
self.args = args
|
||||
|
||||
def add_host(self, host: HostData) -> None:
|
||||
if host.uuid in self.host_data:
|
||||
if host.status == "included":
|
||||
# concatenate task include output from multiple items
|
||||
host.result = f"{self.host_data[host.uuid].result}\n{host.result}"
|
||||
else:
|
||||
return
|
||||
|
||||
self.host_data[host.uuid] = host
|
||||
|
||||
|
||||
class HostData:
|
||||
"""
|
||||
Data about an individual host.
|
||||
"""
|
||||
|
||||
def __init__(self, uuid: str, name: str, status: str, result) -> None:
|
||||
self.uuid = uuid
|
||||
self.name = name
|
||||
self.status = status
|
||||
self.result = result
|
||||
self.finish = time.time()
|
||||
|
||||
|
||||
class ElasticSource:
|
||||
def __init__(self, display) -> None:
|
||||
self.ansible_playbook = ""
|
||||
self.session = str(uuid.uuid4())
|
||||
self.host = socket.gethostname()
|
||||
try:
|
||||
self.ip_address: str | None = socket.gethostbyname(socket.gethostname())
|
||||
except Exception:
|
||||
self.ip_address = None
|
||||
self.user = getpass.getuser()
|
||||
|
||||
self._display = display
|
||||
|
||||
def start_task(self, tasks_data: dict[str, TaskData], hide_task_arguments: bool, play_name: str, task) -> None:
|
||||
"""record the start of a task for one or more hosts"""
|
||||
|
||||
uuid = task._uuid
|
||||
|
||||
if uuid in tasks_data:
|
||||
return
|
||||
|
||||
name = task.get_name().strip()
|
||||
path = task.get_path()
|
||||
action = task.action
|
||||
args = None
|
||||
|
||||
if not task.no_log and not hide_task_arguments:
|
||||
args = ", ".join((f"{k}={v}" for k, v in task.args.items()))
|
||||
|
||||
tasks_data[uuid] = TaskData(uuid, name, path, play_name, action, args)
|
||||
|
||||
def finish_task(self, tasks_data: dict[str, TaskData], status: str, result) -> None:
|
||||
"""record the results of a task for a single host"""
|
||||
|
||||
task_uuid = result._task._uuid
|
||||
|
||||
if hasattr(result, "_host") and result._host is not None:
|
||||
host_uuid = result._host._uuid
|
||||
host_name = result._host.name
|
||||
else:
|
||||
host_uuid = "include"
|
||||
host_name = "include"
|
||||
|
||||
task = tasks_data[task_uuid]
|
||||
|
||||
task.add_host(HostData(host_uuid, host_name, status, result))
|
||||
|
||||
def generate_distributed_traces(
|
||||
self,
|
||||
tasks_data: dict[str, TaskData],
|
||||
status: str,
|
||||
end_time,
|
||||
traceparent: str | None,
|
||||
apm_service_name: str,
|
||||
apm_server_url: str | None,
|
||||
apm_verify_server_cert: bool,
|
||||
apm_secret_token: str | None,
|
||||
apm_api_key: str | None,
|
||||
) -> None:
|
||||
"""generate distributed traces from the collected TaskData and HostData"""
|
||||
|
||||
tasks = []
|
||||
parent_start_time = None
|
||||
for task in tasks_data.values():
|
||||
if parent_start_time is None:
|
||||
parent_start_time = task.start
|
||||
tasks.append(task)
|
||||
|
||||
apm_cli = self.init_apm_client(
|
||||
apm_server_url, apm_service_name, apm_verify_server_cert, apm_secret_token, apm_api_key
|
||||
)
|
||||
if apm_cli:
|
||||
with closing(apm_cli):
|
||||
instrument() # Only call this once, as early as possible.
|
||||
if traceparent:
|
||||
parent = trace_parent_from_string(traceparent)
|
||||
apm_cli.begin_transaction("Session", trace_parent=parent, start=parent_start_time)
|
||||
else:
|
||||
apm_cli.begin_transaction("Session", start=parent_start_time)
|
||||
# Populate trace metadata attributes
|
||||
label(ansible_version=ansible_version)
|
||||
label(ansible_session=self.session, ansible_host_name=self.host, ansible_host_user=self.user)
|
||||
if self.ip_address is not None:
|
||||
label(ansible_host_ip=self.ip_address)
|
||||
|
||||
for task_data in tasks:
|
||||
for host_data in task_data.host_data.values():
|
||||
self.create_span_data(apm_cli, task_data, host_data)
|
||||
|
||||
apm_cli.end_transaction(name=__name__, result=status, duration=end_time - parent_start_time)
|
||||
|
||||
def create_span_data(self, apm_cli: Client, task_data: TaskData, host_data: HostData):
|
||||
"""create the span with the given TaskData and HostData"""
|
||||
|
||||
name = f"[{host_data.name}] {mask_secrets(task_data.play)}: {mask_secrets(task_data.name)}"
|
||||
|
||||
message = "success"
|
||||
status = "success"
|
||||
enriched_error_message = None
|
||||
if host_data.status == "included":
|
||||
rc = 0
|
||||
else:
|
||||
res = host_data.result._result
|
||||
rc = res.get("rc", 0)
|
||||
if host_data.status == "failed":
|
||||
message = self.get_error_message(res)
|
||||
enriched_error_message = self.enrich_error_message(res)
|
||||
status = "failure"
|
||||
elif host_data.status == "skipped":
|
||||
if "skip_reason" in res:
|
||||
message = res["skip_reason"]
|
||||
else:
|
||||
message = "skipped"
|
||||
status = "unknown"
|
||||
|
||||
with capture_span(
|
||||
mask_secrets(task_data.name),
|
||||
start=task_data.start,
|
||||
span_type="ansible.task.run",
|
||||
duration=host_data.finish - task_data.start,
|
||||
labels={
|
||||
"ansible.task.args": mask_secret_values(task_data.args),
|
||||
"ansible.task.message": message,
|
||||
"ansible.task.module": task_data.action,
|
||||
"ansible.task.name": name,
|
||||
"ansible.task.result": rc,
|
||||
"ansible.task.host.name": host_data.name,
|
||||
"ansible.task.host.status": host_data.status,
|
||||
},
|
||||
) as span:
|
||||
span.outcome = status # type: ignore[union-attr]
|
||||
if "failure" in status:
|
||||
exception = AnsibleRuntimeError(
|
||||
message=f"{task_data.action}: {name} failed with error message {enriched_error_message}"
|
||||
)
|
||||
apm_cli.capture_exception(exc_info=(type(exception), exception, exception.__traceback__), handled=True)
|
||||
|
||||
def init_apm_client(
|
||||
self,
|
||||
apm_server_url: str | None,
|
||||
apm_service_name: str,
|
||||
apm_verify_server_cert: bool,
|
||||
apm_secret_token: str | None,
|
||||
apm_api_key: str | None,
|
||||
) -> Client | None:
|
||||
if apm_server_url:
|
||||
return Client(
|
||||
service_name=apm_service_name,
|
||||
server_url=apm_server_url,
|
||||
verify_server_cert=False,
|
||||
secret_token=apm_secret_token,
|
||||
api_key=apm_api_key,
|
||||
use_elastic_traceparent_header=True,
|
||||
debug=True,
|
||||
)
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def get_error_message(result):
|
||||
if result.get("exception") is not None:
|
||||
return ElasticSource._last_line(result["exception"])
|
||||
return result.get("msg", "failed")
|
||||
|
||||
@staticmethod
|
||||
def _last_line(text: str) -> str:
|
||||
lines = text.strip().split("\n")
|
||||
return lines[-1]
|
||||
|
||||
@staticmethod
|
||||
def enrich_error_message(result) -> str:
|
||||
message = result.get("msg", "failed")
|
||||
exception = result.get("exception")
|
||||
stderr = result.get("stderr")
|
||||
return f'message: "{message}"\nexception: "{exception}"\nstderr: "{stderr}"'
|
||||
|
||||
|
||||
class CallbackModule(CallbackBase):
|
||||
"""
|
||||
This callback creates distributed traces with Elastic APM.
|
||||
"""
|
||||
|
||||
CALLBACK_VERSION = 2.0
|
||||
CALLBACK_TYPE = "notification"
|
||||
CALLBACK_NAME = "community.general.elastic"
|
||||
CALLBACK_NEEDS_ENABLED = True
|
||||
|
||||
def __init__(self, display=None) -> None:
|
||||
super().__init__(display=display)
|
||||
self.hide_task_arguments = False
|
||||
self.apm_service_name: str = ""
|
||||
self.ansible_playbook = None
|
||||
self.traceparent: str | None = None
|
||||
self.play_name = None
|
||||
self.errors = 0
|
||||
self.disabled = False
|
||||
|
||||
if ELASTIC_LIBRARY_IMPORT_ERROR:
|
||||
raise AnsibleError(
|
||||
"The `elastic-apm` must be installed to use this plugin"
|
||||
) from ELASTIC_LIBRARY_IMPORT_ERROR
|
||||
|
||||
self.tasks_data: dict[str, TaskData] = OrderedDict()
|
||||
|
||||
self.elastic = ElasticSource(display=self._display)
|
||||
|
||||
def set_options(self, task_keys=None, var_options=None, direct=None) -> None:
|
||||
super().set_options(task_keys=task_keys, var_options=var_options, direct=direct)
|
||||
|
||||
self.hide_task_arguments = self.get_option("hide_task_arguments")
|
||||
|
||||
self.apm_service_name = self.get_option("apm_service_name") or "ansible"
|
||||
|
||||
self.apm_server_url: str | None = self.get_option("apm_server_url")
|
||||
self.apm_secret_token: str | None = self.get_option("apm_secret_token")
|
||||
self.apm_api_key: str | None = self.get_option("apm_api_key")
|
||||
self.apm_verify_server_cert: bool = self.get_option("apm_verify_server_cert")
|
||||
self.traceparent = self.get_option("traceparent")
|
||||
|
||||
def v2_playbook_on_start(self, playbook):
|
||||
self.ansible_playbook = basename(playbook._file_name)
|
||||
|
||||
def v2_playbook_on_play_start(self, play):
|
||||
self.play_name = play.get_name()
|
||||
|
||||
def v2_runner_on_no_hosts(self, task):
|
||||
self.elastic.start_task(self.tasks_data, self.hide_task_arguments, self.play_name, task)
|
||||
|
||||
def v2_playbook_on_task_start(self, task, is_conditional):
|
||||
self.elastic.start_task(self.tasks_data, self.hide_task_arguments, self.play_name, task)
|
||||
|
||||
def v2_playbook_on_cleanup_task_start(self, task):
|
||||
self.elastic.start_task(self.tasks_data, self.hide_task_arguments, self.play_name, task)
|
||||
|
||||
def v2_playbook_on_handler_task_start(self, task):
|
||||
self.elastic.start_task(self.tasks_data, self.hide_task_arguments, self.play_name, task)
|
||||
|
||||
def v2_runner_on_failed(self, result, ignore_errors=False):
|
||||
self.errors += 1
|
||||
self.elastic.finish_task(self.tasks_data, "failed", result)
|
||||
|
||||
def v2_runner_on_ok(self, result):
|
||||
self.elastic.finish_task(self.tasks_data, "ok", result)
|
||||
|
||||
def v2_runner_on_skipped(self, result):
|
||||
self.elastic.finish_task(self.tasks_data, "skipped", result)
|
||||
|
||||
def v2_playbook_on_include(self, included_file):
|
||||
self.elastic.finish_task(self.tasks_data, "included", included_file)
|
||||
|
||||
def v2_playbook_on_stats(self, stats):
|
||||
if self.errors == 0:
|
||||
status = "success"
|
||||
else:
|
||||
status = "failure"
|
||||
self.elastic.generate_distributed_traces(
|
||||
self.tasks_data,
|
||||
status,
|
||||
time.time(),
|
||||
self.traceparent,
|
||||
self.apm_service_name,
|
||||
self.apm_server_url,
|
||||
self.apm_verify_server_cert,
|
||||
self.apm_secret_token,
|
||||
self.apm_api_key,
|
||||
)
|
||||
|
||||
def v2_runner_on_async_failed(self, result, **kwargs):
|
||||
self.errors += 1
|
||||
+127
@@ -0,0 +1,127 @@
|
||||
# Copyright (C) 2016 maxn nikolaev.makc@gmail.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: Unknown (!UNKNOWN)
|
||||
name: jabber
|
||||
type: notification
|
||||
short_description: Post task events to a Jabber server
|
||||
description:
|
||||
- The chatty part of ChatOps with a Hipchat server as a target.
|
||||
- This callback plugin sends status updates to a HipChat channel during playbook execution.
|
||||
requirements:
|
||||
- xmpp (Python library U(https://github.com/ArchipelProject/xmpppy))
|
||||
options:
|
||||
server:
|
||||
description: Connection info to Jabber server.
|
||||
type: str
|
||||
required: true
|
||||
env:
|
||||
- name: JABBER_SERV
|
||||
user:
|
||||
description: Jabber user to authenticate as.
|
||||
type: str
|
||||
required: true
|
||||
env:
|
||||
- name: JABBER_USER
|
||||
password:
|
||||
description: Password for the user to the Jabber server.
|
||||
type: str
|
||||
required: true
|
||||
env:
|
||||
- name: JABBER_PASS
|
||||
secret: true
|
||||
to:
|
||||
description: Chat identifier that receives the message.
|
||||
type: str
|
||||
required: true
|
||||
env:
|
||||
- name: JABBER_TO
|
||||
"""
|
||||
|
||||
import os
|
||||
|
||||
HAS_XMPP = True
|
||||
try:
|
||||
import xmpp
|
||||
except ImportError:
|
||||
HAS_XMPP = False
|
||||
|
||||
from ansible.plugins.callback import CallbackBase
|
||||
|
||||
from ansible_collections.community.general.plugins.module_utils._secrets import mask_secrets
|
||||
|
||||
|
||||
class CallbackModule(CallbackBase):
|
||||
CALLBACK_VERSION = 2.0
|
||||
CALLBACK_TYPE = "notification"
|
||||
CALLBACK_NAME = "community.general.jabber"
|
||||
CALLBACK_NEEDS_WHITELIST = True
|
||||
|
||||
def __init__(self, display=None):
|
||||
super().__init__(display=display)
|
||||
|
||||
if not HAS_XMPP:
|
||||
self._display.warning(
|
||||
"The required python xmpp library (xmpppy) is not installed. "
|
||||
"pip install git+https://github.com/ArchipelProject/xmpppy"
|
||||
)
|
||||
self.disabled = True
|
||||
|
||||
self.serv = os.getenv("JABBER_SERV")
|
||||
self.j_user = os.getenv("JABBER_USER")
|
||||
self.j_pass = os.getenv("JABBER_PASS")
|
||||
self.j_to = os.getenv("JABBER_TO")
|
||||
|
||||
if (self.j_user or self.j_pass or self.serv or self.j_to) is None:
|
||||
self.disabled = True
|
||||
self._display.warning(
|
||||
"Jabber CallBack wants the JABBER_SERV, JABBER_USER, JABBER_PASS and JABBER_TO environment variables"
|
||||
)
|
||||
|
||||
def send_msg(self, msg):
|
||||
"""Send message"""
|
||||
jid = xmpp.JID(self.j_user)
|
||||
client = xmpp.Client(self.serv, debug=[])
|
||||
client.connect(server=(self.serv, 5222))
|
||||
client.auth(jid.getNode(), self.j_pass, resource=jid.getResource())
|
||||
message = xmpp.Message(self.j_to, mask_secrets(msg))
|
||||
message.setAttr("type", "chat")
|
||||
client.send(message)
|
||||
client.disconnect()
|
||||
|
||||
def v2_runner_on_ok(self, result):
|
||||
self._clean_results(result._result, result._task.action)
|
||||
self.debug = self._dump_results(result._result)
|
||||
|
||||
def v2_playbook_on_task_start(self, task, is_conditional):
|
||||
self.task = task
|
||||
|
||||
def v2_playbook_on_play_start(self, play):
|
||||
"""Display Playbook and play start messages"""
|
||||
self.play = play
|
||||
name = play.name
|
||||
self.send_msg(f"Ansible starting play: {name}")
|
||||
|
||||
def playbook_on_stats(self, stats):
|
||||
name = self.play
|
||||
hosts = sorted(stats.processed.keys())
|
||||
failures = False
|
||||
unreachable = False
|
||||
for h in hosts:
|
||||
s = stats.summarize(h)
|
||||
if s["failures"] > 0:
|
||||
failures = True
|
||||
if s["unreachable"] > 0:
|
||||
unreachable = True
|
||||
|
||||
if failures or unreachable:
|
||||
out = self.debug
|
||||
self.send_msg(f"{name}: Failures detected \n{self.task} \nHost: {h}\n Failed at:\n{out}")
|
||||
else:
|
||||
out = self.debug
|
||||
self.send_msg(f"Great! \n Playbook {name} completed:\n{s} \n Last task debug:\n {out}")
|
||||
+120
@@ -0,0 +1,120 @@
|
||||
# Copyright (c) 2012, Michael DeHaan, <michael.dehaan@gmail.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: Unknown (!UNKNOWN)
|
||||
name: log_plays
|
||||
type: notification
|
||||
short_description: Write playbook output to log file
|
||||
description:
|
||||
- This callback writes playbook output to a file per host in the C(/var/log/ansible/hosts) directory.
|
||||
requirements:
|
||||
- Whitelist in configuration
|
||||
- A writeable C(/var/log/ansible/hosts) directory by the user executing Ansible on the controller
|
||||
options:
|
||||
log_folder:
|
||||
default: /var/log/ansible/hosts
|
||||
description: The folder where log files are created.
|
||||
type: path
|
||||
env:
|
||||
- name: ANSIBLE_LOG_FOLDER
|
||||
ini:
|
||||
- section: callback_log_plays
|
||||
key: log_folder
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
from collections.abc import MutableMapping
|
||||
|
||||
from ansible.module_utils.common.text.converters import to_bytes
|
||||
from ansible.parsing.ajson import AnsibleJSONEncoder
|
||||
from ansible.plugins.callback import CallbackBase
|
||||
from ansible.utils.path import makedirs_safe
|
||||
|
||||
from ansible_collections.community.general.plugins.module_utils._secrets import mask_secrets
|
||||
|
||||
# NOTE: in Ansible 1.2 or later general logging is available without
|
||||
# this plugin, just set ANSIBLE_LOG_PATH as an environment variable
|
||||
# or log_path in the DEFAULTS section of your ansible configuration
|
||||
# file. This callback is an example of per hosts logging for those
|
||||
# that want it.
|
||||
|
||||
|
||||
class CallbackModule(CallbackBase):
|
||||
"""
|
||||
logs playbook results, per host, in /var/log/ansible/hosts
|
||||
"""
|
||||
|
||||
CALLBACK_VERSION = 2.0
|
||||
CALLBACK_TYPE = "notification"
|
||||
CALLBACK_NAME = "community.general.log_plays"
|
||||
CALLBACK_NEEDS_WHITELIST = True
|
||||
|
||||
TIME_FORMAT = "%b %d %Y %H:%M:%S"
|
||||
|
||||
@staticmethod
|
||||
def _make_msg(now, playbook, task_name, task_action, category, data):
|
||||
return f"{now} - {playbook} - {mask_secrets(task_name)} - {task_action} - {category} - {data}\n\n"
|
||||
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
|
||||
def set_options(self, task_keys=None, var_options=None, direct=None):
|
||||
super().set_options(task_keys=task_keys, var_options=var_options, direct=direct)
|
||||
|
||||
self.log_folder = self.get_option("log_folder")
|
||||
|
||||
if not os.path.exists(self.log_folder):
|
||||
makedirs_safe(self.log_folder)
|
||||
|
||||
def log(self, result, category):
|
||||
data = result._result
|
||||
if isinstance(data, MutableMapping):
|
||||
if "_ansible_verbose_override" in data:
|
||||
# avoid logging extraneous data
|
||||
data = "omitted"
|
||||
else:
|
||||
data = data.copy()
|
||||
invocation = data.pop("invocation", None)
|
||||
data = json.dumps(data, cls=AnsibleJSONEncoder)
|
||||
if invocation is not None:
|
||||
data = f"{json.dumps(invocation)} => {data} "
|
||||
|
||||
path = os.path.join(self.log_folder, result._host.get_name())
|
||||
now = time.strftime(self.TIME_FORMAT, time.localtime())
|
||||
|
||||
msg = to_bytes(self._make_msg(now, self.playbook, result._task.name, result._task.action, category, data))
|
||||
with open(path, "ab") as fd:
|
||||
fd.write(msg)
|
||||
|
||||
def v2_runner_on_failed(self, result, ignore_errors=False):
|
||||
self.log(result, "FAILED")
|
||||
|
||||
def v2_runner_on_ok(self, result):
|
||||
self.log(result, "OK")
|
||||
|
||||
def v2_runner_on_skipped(self, result):
|
||||
self.log(result, "SKIPPED")
|
||||
|
||||
def v2_runner_on_unreachable(self, result):
|
||||
self.log(result, "UNREACHABLE")
|
||||
|
||||
def v2_runner_on_async_failed(self, result):
|
||||
self.log(result, "ASYNC_FAILED")
|
||||
|
||||
def v2_playbook_on_start(self, playbook):
|
||||
self.playbook = playbook._file_name
|
||||
|
||||
def v2_playbook_on_import_for_host(self, result, imported_file):
|
||||
# TODO: passing more parameters than allowed!
|
||||
self.log(result, "IMPORTED", mask_secrets(imported_file))
|
||||
|
||||
def v2_playbook_on_not_import_for_host(self, result, missing_file):
|
||||
# TODO: passing more parameters than allowed!
|
||||
self.log(result, "NOTIMPORTED", mask_secrets(missing_file))
|
||||
+348
@@ -0,0 +1,348 @@
|
||||
#!/usr/bin/env python
|
||||
# Copyright (c) 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 = """
|
||||
name: loganalytics_ingestion
|
||||
type: notification
|
||||
short_description: Posts task results to an Azure Log Analytics workspace using the new Logs Ingestion API
|
||||
author:
|
||||
- Wade Cline (@wtcline-intc) <wade.cline@intel.com>
|
||||
- Sriramoju Vishal Bharath (@vsh47) <sriramoju.vishal.bharath@intel.com>
|
||||
- Cyrus Li (@zhcli) <cyrus1006@gmail.com>
|
||||
description:
|
||||
- This callback plugin will post task results in JSON format to an Azure Log Analytics workspace using the new Logs Ingestion API.
|
||||
version_added: "12.4.0"
|
||||
requirements:
|
||||
- The callback plugin has been enabled.
|
||||
- An Azure Log Analytics workspace has been established.
|
||||
- A Data Collection Rule (DCR) and custom table are created.
|
||||
options:
|
||||
dce_url:
|
||||
description: URL of the Data Collection Endpoint (DCE) for Azure Logs Ingestion API.
|
||||
type: str
|
||||
required: true
|
||||
env:
|
||||
- name: ANSIBLE_LOGANALYTICS_DCE_URL
|
||||
ini:
|
||||
- section: callback_loganalytics
|
||||
key: dce_url
|
||||
dcr_id:
|
||||
description: Data Collection Rule (DCR) ID for the Azure Log Ingestion API.
|
||||
type: str
|
||||
required: true
|
||||
env:
|
||||
- name: ANSIBLE_LOGANALYTICS_DCR_ID
|
||||
ini:
|
||||
- section: callback_loganalytics
|
||||
key: dcr_id
|
||||
disable_attempts:
|
||||
description:
|
||||
- When O(disable_on_failure=true), number of plugin failures that must occur before the plugin is disabled.
|
||||
- This helps prevent outright plugin failure from a single, transient network issue.
|
||||
type: int
|
||||
default: 3
|
||||
env:
|
||||
- name: ANSIBLE_LOGANALYTICS_DISABLE_ATTEMPTS
|
||||
ini:
|
||||
- section: callback_loganalytics
|
||||
key: disable_attempts
|
||||
disable_on_failure:
|
||||
description: Stop trying to send data on plugin failure.
|
||||
type: bool
|
||||
default: true
|
||||
env:
|
||||
- name: ANSIBLE_LOGANALYTICS_DISABLE_ON_FAILURE
|
||||
ini:
|
||||
- section: callback_loganalytics
|
||||
key: disable_on_failure
|
||||
client_id:
|
||||
description: Client ID of the Azure App registration for OAuth2 authentication ("Modern Authentication").
|
||||
type: str
|
||||
required: true
|
||||
env:
|
||||
- name: ANSIBLE_LOGANALYTICS_CLIENT_ID
|
||||
ini:
|
||||
- section: callback_loganalytics
|
||||
key: client_id
|
||||
client_secret:
|
||||
description: Client Secret of the Azure App registration.
|
||||
type: str
|
||||
required: true
|
||||
env:
|
||||
- name: ANSIBLE_LOGANALYTICS_CLIENT_SECRET
|
||||
ini:
|
||||
- section: callback_loganalytics
|
||||
key: client_secret
|
||||
secret: true
|
||||
include_content:
|
||||
description: Send the content to the Azure Log Analytics workspace.
|
||||
type: bool
|
||||
default: false
|
||||
env:
|
||||
- name: ANSIBLE_LOGANALYTICS_INCLUDE_CONTENT
|
||||
ini:
|
||||
- section: callback_loganalytics
|
||||
key: include_content
|
||||
include_task_args:
|
||||
description: Send the task args to the Azure Log Analytics workspace.
|
||||
type: bool
|
||||
default: false
|
||||
env:
|
||||
- name: ANSIBLE_LOGANALYTICS_INCLUDE_TASK_ARGS
|
||||
ini:
|
||||
- section: callback_loganalytics
|
||||
key: include_task_args
|
||||
stream_name:
|
||||
description: The name of the stream used to send the logs to the Azure Log Analytics workspace.
|
||||
type: str
|
||||
required: true
|
||||
env:
|
||||
- name: ANSIBLE_LOGANALYTICS_STREAM_NAME
|
||||
ini:
|
||||
- section: callback_loganalytics
|
||||
key: stream_name
|
||||
tenant_id:
|
||||
description: Tenant ID for the Azure Active Directory.
|
||||
type: str
|
||||
required: true
|
||||
env:
|
||||
- name: ANSIBLE_LOGANALYTICS_TENANT_ID
|
||||
ini:
|
||||
- section: callback_loganalytics
|
||||
key: tenant_id
|
||||
timeout:
|
||||
description: Timeout for the HTTP requests to the Azure Log Analytics API.
|
||||
type: int
|
||||
default: 2
|
||||
env:
|
||||
- name: ANSIBLE_LOGANALYTICS_TIMEOUT
|
||||
ini:
|
||||
- section: callback_loganalytics
|
||||
key: timeout
|
||||
seealso:
|
||||
- name: Logs Ingestion API
|
||||
description: Overview of Logs Ingestion API in Azure Monitor
|
||||
link: https://learn.microsoft.com/en-us/azure/azure-monitor/logs/logs-ingestion-api-overview
|
||||
notes:
|
||||
- Triple verbosity logging (C(-vvv)) can be used to generate JSON sample data for creating the table schema in Azure Log Analytics.
|
||||
Search for the string C(Event Data:) in the output in order to locate the data sample.
|
||||
"""
|
||||
|
||||
EXAMPLES = """
|
||||
examples: |
|
||||
Enable the plugin in ansible.cfg:
|
||||
[defaults]
|
||||
callback_enabled = community.general.loganalytics_ingestion
|
||||
Set the environment variables:
|
||||
export ANSIBLE_LOGANALYTICS_DCE_URL=https://my-dce.ingest.monitor.azure.com
|
||||
export ANSIBLE_LOGANALYTICS_DCR_ID=dcr-xxxxxx
|
||||
export ANSIBLE_LOGANALYTICS_CLIENT_ID=xxxxxxxx
|
||||
export ANSIBLE_LOGANALYTICS_CLIENT_SECRET=xxxxxxxx
|
||||
export ANSIBLE_LOGANALYTICS_TENANT_ID=xxxxxxxx
|
||||
export ANSIBLE_LOGANALYTICS_STREAM_NAME=Custom-MyTable
|
||||
"""
|
||||
|
||||
import getpass
|
||||
import json
|
||||
import socket
|
||||
import uuid
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from os.path import basename
|
||||
from urllib.parse import urlencode
|
||||
|
||||
from ansible.module_utils.urls import open_url
|
||||
from ansible.plugins.callback import CallbackBase
|
||||
from ansible.utils.display import Display
|
||||
|
||||
from ansible_collections.community.general.plugins.module_utils._secrets import mark_as_secret, mask_secret_values
|
||||
|
||||
display = Display()
|
||||
|
||||
|
||||
class AzureLogAnalyticsIngestionSource:
|
||||
def __init__(
|
||||
self,
|
||||
dce_url,
|
||||
dcr_id,
|
||||
disable_attempts,
|
||||
disable_on_failure,
|
||||
client_id,
|
||||
client_secret,
|
||||
tenant_id,
|
||||
stream_name,
|
||||
include_task_args,
|
||||
include_content,
|
||||
timeout,
|
||||
fqcn,
|
||||
):
|
||||
self.dce_url = dce_url
|
||||
self.dcr_id = dcr_id
|
||||
self.disabled = False
|
||||
self.disable_attempts = disable_attempts
|
||||
self.disable_on_failure = disable_on_failure
|
||||
self.client_id = client_id
|
||||
self.client_secret = client_secret
|
||||
self.failures = 0
|
||||
self.tenant_id = tenant_id
|
||||
self.stream_name = stream_name
|
||||
self.include_task_args = include_task_args
|
||||
self.include_content = include_content
|
||||
self.token_expiration_time = None
|
||||
self.session = str(uuid.uuid4())
|
||||
self.host = socket.gethostname()
|
||||
self.user = getpass.getuser()
|
||||
self.timeout = timeout
|
||||
self.fqcn = fqcn
|
||||
|
||||
self.bearer_token = self.get_bearer_token()
|
||||
|
||||
# OAuth2 authentication method to get a Bearer token
|
||||
# This replaces the shared_key authentication mechanism
|
||||
def get_bearer_token(self):
|
||||
url = f"https://login.microsoftonline.com/{self.tenant_id}/oauth2/v2.0/token"
|
||||
headers = {"Content-Type": "application/x-www-form-urlencoded"}
|
||||
data = urlencode(
|
||||
{
|
||||
"grant_type": "client_credentials",
|
||||
"client_id": self.client_id,
|
||||
"client_secret": self.client_secret,
|
||||
# The scope value comes from https://learn.microsoft.com/en-us/azure/azure-monitor/logs/logs-ingestion-api-overview#headers
|
||||
# and https://learn.microsoft.com/en-us/entra/identity-platform/scopes-oidc#the-default-scope
|
||||
"scope": "https://monitor.azure.com/.default",
|
||||
}
|
||||
)
|
||||
response = open_url(url, data=data, force=True, headers=headers, method="POST", timeout=self.timeout)
|
||||
j = json.loads(response.read().decode("utf-8"))
|
||||
access_token = mark_as_secret(j["access_token"])
|
||||
|
||||
self.token_expiration_time = datetime.now() + timedelta(seconds=j.get("expires_in"))
|
||||
|
||||
return access_token
|
||||
|
||||
def is_token_valid(self):
|
||||
return datetime.now() + timedelta(seconds=10) < self.token_expiration_time
|
||||
|
||||
# Method to send event data to the Azure Logs Ingestion API
|
||||
# This replaces the legacy API call and now uses the Logs Ingestion API endpoint
|
||||
def send_event(self, event_data):
|
||||
if not self.is_token_valid():
|
||||
self.bearer_token = self.get_bearer_token()
|
||||
ingestion_url = (
|
||||
f"{self.dce_url}/dataCollectionRules/{self.dcr_id}/streams/{self.stream_name}?api-version=2023-01-01"
|
||||
)
|
||||
headers = {"Authorization": f"Bearer {self.bearer_token}", "Content-Type": "application/json"}
|
||||
open_url(ingestion_url, data=json.dumps(event_data), headers=headers, method="POST", timeout=self.timeout)
|
||||
|
||||
def _rfc1123date(self):
|
||||
return datetime.now(UTC).strftime("%a, %d %b %Y %H:%M:%S GMT")
|
||||
|
||||
# This method wraps the private method with the appropriate error handling.
|
||||
def send_to_loganalytics(self, playbook_name, result, state):
|
||||
if self.disabled:
|
||||
return
|
||||
try:
|
||||
self._send_to_loganalytics(playbook_name, result, state)
|
||||
except Exception as e:
|
||||
display.warning(f"{self.fqcn} callback plugin failure: {e}.")
|
||||
if self.disable_on_failure:
|
||||
self.failures += 1
|
||||
if self.failures >= self.disable_attempts:
|
||||
display.warning(
|
||||
f"{self.fqcn} callback plugin failures exceed maximum of '{self.disable_attempts}'! Disabling plugin!"
|
||||
)
|
||||
self.disabled = True
|
||||
else:
|
||||
display.v(f"{self.fqcn} callback plugin failure {self.failures}/{self.disable_attempts}")
|
||||
|
||||
def _send_to_loganalytics(self, playbook_name, result, state):
|
||||
ansible_role = str(result._task._role) if result._task._role else None
|
||||
|
||||
# Include/Exclude task args
|
||||
if not self.include_task_args:
|
||||
result._task_fields.pop("args", None)
|
||||
|
||||
# Include/Exclude content
|
||||
if not self.include_content:
|
||||
result._result.pop("content", None)
|
||||
|
||||
# Build the event data
|
||||
event_data = [
|
||||
{
|
||||
"TimeGenerated": self._rfc1123date(),
|
||||
"Host": result._host.name,
|
||||
"User": self.user,
|
||||
"Playbook": playbook_name,
|
||||
"Role": ansible_role,
|
||||
"TaskName": mask_secret_values(result._task.get_name()),
|
||||
"Task": mask_secret_values(result._task_fields),
|
||||
"Action": result._task_fields["action"],
|
||||
"State": state,
|
||||
"Result": result._result,
|
||||
"Session": self.session,
|
||||
}
|
||||
]
|
||||
|
||||
# The data displayed here can be used as a sample file in order to create the table's schema.
|
||||
display.vvv(f"Event Data: {json.dumps(event_data)}")
|
||||
|
||||
self.send_event(event_data)
|
||||
|
||||
|
||||
class CallbackModule(CallbackBase):
|
||||
CALLBACK_VERSION = 2.0
|
||||
CALLBACK_TYPE = "notification"
|
||||
CALLBACK_NAME = "loganalytics_ingestion"
|
||||
CALLBACK_NEEDS_ENABLED = True
|
||||
|
||||
def __init__(self, display=None):
|
||||
super().__init__(display=display)
|
||||
self.start_datetimes = {}
|
||||
self.playbook_name = None
|
||||
self.azure_loganalytics = None
|
||||
self.fqcn = f"community.general.{self.CALLBACK_NAME}"
|
||||
|
||||
def set_options(self, task_keys=None, var_options=None, direct=None):
|
||||
super().set_options(task_keys=task_keys, var_options=var_options, direct=direct)
|
||||
|
||||
# Set options for the new Azure Logs Ingestion API configuration
|
||||
self.client_id = self.get_option("client_id")
|
||||
self.client_secret = self.get_option("client_secret")
|
||||
self.dce_url = self.get_option("dce_url")
|
||||
self.dcr_id = self.get_option("dcr_id")
|
||||
self.disable_attempts = self.get_option("disable_attempts")
|
||||
self.disable_on_failure = self.get_option("disable_on_failure")
|
||||
self.include_content = self.get_option("include_content")
|
||||
self.include_task_args = self.get_option("include_task_args")
|
||||
self.stream_name = self.get_option("stream_name")
|
||||
self.tenant_id = self.get_option("tenant_id")
|
||||
self.timeout = self.get_option("timeout")
|
||||
|
||||
# Initialize the AzureLogAnalyticsIngestionSource with the new settings
|
||||
self.azure_loganalytics = AzureLogAnalyticsIngestionSource(
|
||||
self.dce_url,
|
||||
self.dcr_id,
|
||||
self.disable_attempts,
|
||||
self.disable_on_failure,
|
||||
self.client_id,
|
||||
self.client_secret,
|
||||
self.tenant_id,
|
||||
self.stream_name,
|
||||
self.include_task_args,
|
||||
self.include_content,
|
||||
self.timeout,
|
||||
self.fqcn,
|
||||
)
|
||||
|
||||
def v2_playbook_on_start(self, playbook):
|
||||
self.playbook_name = basename(playbook._file_name)
|
||||
|
||||
# Build event data and send it to the Logs Ingestion API
|
||||
def v2_runner_on_failed(self, result, **kwargs):
|
||||
self.azure_loganalytics.send_to_loganalytics(self.playbook_name, result, "FAILED")
|
||||
|
||||
def v2_runner_on_ok(self, result, **kwargs):
|
||||
self.azure_loganalytics.send_to_loganalytics(self.playbook_name, result, "OK")
|
||||
+210
@@ -0,0 +1,210 @@
|
||||
# Copyright (c) 2018, Samir Musali <samir.musali@logdna.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
|
||||
|
||||
DOCUMENTATION = r"""
|
||||
author: Unknown (!UNKNOWN)
|
||||
name: logdna
|
||||
type: notification
|
||||
short_description: Sends playbook logs to LogDNA
|
||||
description:
|
||||
- This callback reports logs from playbook actions, tasks, and events to LogDNA (U(https://app.logdna.com)).
|
||||
requirements:
|
||||
- LogDNA Python Library (U(https://github.com/logdna/python))
|
||||
- whitelisting in configuration
|
||||
options:
|
||||
conf_key:
|
||||
required: true
|
||||
description: LogDNA Ingestion Key.
|
||||
type: string
|
||||
env:
|
||||
- name: LOGDNA_INGESTION_KEY
|
||||
ini:
|
||||
- section: callback_logdna
|
||||
key: conf_key
|
||||
secret: true
|
||||
plugin_ignore_errors:
|
||||
required: false
|
||||
description: Whether to ignore errors on failing or not.
|
||||
type: boolean
|
||||
env:
|
||||
- name: ANSIBLE_IGNORE_ERRORS
|
||||
ini:
|
||||
- section: callback_logdna
|
||||
key: plugin_ignore_errors
|
||||
default: false
|
||||
conf_hostname:
|
||||
required: false
|
||||
description: Alternative Host Name; the current host name by default.
|
||||
type: string
|
||||
env:
|
||||
- name: LOGDNA_HOSTNAME
|
||||
ini:
|
||||
- section: callback_logdna
|
||||
key: conf_hostname
|
||||
conf_tags:
|
||||
required: false
|
||||
description: Tags.
|
||||
type: string
|
||||
env:
|
||||
- name: LOGDNA_TAGS
|
||||
ini:
|
||||
- section: callback_logdna
|
||||
key: conf_tags
|
||||
default: ansible
|
||||
"""
|
||||
|
||||
import json
|
||||
import logging
|
||||
import socket
|
||||
from uuid import getnode
|
||||
|
||||
from ansible.parsing.ajson import AnsibleJSONEncoder
|
||||
from ansible.plugins.callback import CallbackBase
|
||||
|
||||
try:
|
||||
from logdna import LogDNAHandler
|
||||
|
||||
HAS_LOGDNA = True
|
||||
except ImportError:
|
||||
HAS_LOGDNA = False
|
||||
|
||||
|
||||
# Getting MAC Address of system:
|
||||
def get_mac():
|
||||
mac = f"{getnode():012x}"
|
||||
return ":".join(map(lambda index: mac[index : index + 2], range(int(len(mac) / 2))))
|
||||
|
||||
|
||||
# Getting hostname of system:
|
||||
def get_hostname():
|
||||
return str(socket.gethostname()).split(".local", 1)[0]
|
||||
|
||||
|
||||
# Getting IP of system:
|
||||
def get_ip():
|
||||
try:
|
||||
return socket.gethostbyname(get_hostname())
|
||||
except Exception:
|
||||
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
try:
|
||||
s.connect(("10.255.255.255", 1))
|
||||
IP = s.getsockname()[0]
|
||||
except Exception:
|
||||
IP = "127.0.0.1"
|
||||
finally:
|
||||
s.close()
|
||||
return IP
|
||||
|
||||
|
||||
# Is it JSON?
|
||||
def isJSONable(obj):
|
||||
try:
|
||||
json.dumps(obj, sort_keys=True, cls=AnsibleJSONEncoder)
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
# LogDNA Callback Module:
|
||||
class CallbackModule(CallbackBase):
|
||||
CALLBACK_VERSION = 0.1
|
||||
CALLBACK_TYPE = "notification"
|
||||
CALLBACK_NAME = "community.general.logdna"
|
||||
CALLBACK_NEEDS_WHITELIST = True
|
||||
|
||||
def __init__(self, display=None):
|
||||
super().__init__(display=display)
|
||||
|
||||
self.disabled = True
|
||||
self.playbook_name = None
|
||||
self.playbook = None
|
||||
self.conf_key = None
|
||||
self.plugin_ignore_errors = None
|
||||
self.conf_hostname = None
|
||||
self.conf_tags = None
|
||||
|
||||
def set_options(self, task_keys=None, var_options=None, direct=None):
|
||||
super().set_options(task_keys=task_keys, var_options=var_options, direct=direct)
|
||||
|
||||
self.conf_key = self.get_option("conf_key")
|
||||
self.plugin_ignore_errors = self.get_option("plugin_ignore_errors")
|
||||
self.conf_hostname = self.get_option("conf_hostname")
|
||||
self.conf_tags = self.get_option("conf_tags")
|
||||
self.mac = get_mac()
|
||||
self.ip = get_ip()
|
||||
|
||||
if self.conf_hostname is None:
|
||||
self.conf_hostname = get_hostname()
|
||||
|
||||
self.conf_tags = self.conf_tags.split(",")
|
||||
|
||||
if HAS_LOGDNA:
|
||||
self.log = logging.getLogger("logdna")
|
||||
self.log.setLevel(logging.INFO)
|
||||
self.options = {"hostname": self.conf_hostname, "mac": self.mac, "index_meta": True}
|
||||
self.log.addHandler(LogDNAHandler(self.conf_key, self.options))
|
||||
self.disabled = False
|
||||
else:
|
||||
self.disabled = True
|
||||
self._display.warning("WARNING:\nPlease, install LogDNA Python Package: `pip install logdna`")
|
||||
|
||||
def metaIndexing(self, meta):
|
||||
invalidKeys = []
|
||||
ninvalidKeys = 0
|
||||
for key, value in meta.items():
|
||||
if not isJSONable(value):
|
||||
invalidKeys.append(key)
|
||||
ninvalidKeys += 1
|
||||
if ninvalidKeys > 0:
|
||||
for key in invalidKeys:
|
||||
del meta[key]
|
||||
meta["__errors"] = f"These keys have been sanitized: {', '.join(invalidKeys)}"
|
||||
return meta
|
||||
|
||||
def sanitizeJSON(self, data):
|
||||
try:
|
||||
return json.loads(json.dumps(data, sort_keys=True, cls=AnsibleJSONEncoder))
|
||||
except Exception:
|
||||
return {"warnings": ["JSON Formatting Issue", json.dumps(data, sort_keys=True, cls=AnsibleJSONEncoder)]}
|
||||
|
||||
def flush(self, log, options):
|
||||
if HAS_LOGDNA:
|
||||
self.log.info(json.dumps(log), options)
|
||||
|
||||
def sendLog(self, host, category, logdata):
|
||||
options = {"app": "ansible", "meta": {"playbook": self.playbook_name, "host": host, "category": category}}
|
||||
logdata["info"].pop("invocation", None)
|
||||
warnings = logdata["info"].pop("warnings", None)
|
||||
if warnings is not None:
|
||||
self.flush({"warn": warnings}, options)
|
||||
self.flush(logdata, options)
|
||||
|
||||
def v2_playbook_on_start(self, playbook):
|
||||
self.playbook = playbook
|
||||
self.playbook_name = playbook._file_name
|
||||
|
||||
def v2_playbook_on_stats(self, stats):
|
||||
result = dict()
|
||||
for host in stats.processed.keys():
|
||||
result[host] = stats.summarize(host)
|
||||
self.sendLog(self.conf_hostname, "STATS", {"info": self.sanitizeJSON(result)})
|
||||
|
||||
def runner_on_failed(self, host, res, ignore_errors=False):
|
||||
if self.plugin_ignore_errors:
|
||||
ignore_errors = self.plugin_ignore_errors
|
||||
self.sendLog(host, "FAILED", {"info": self.sanitizeJSON(res), "ignore_errors": ignore_errors})
|
||||
|
||||
def runner_on_ok(self, host, res):
|
||||
self.sendLog(host, "OK", {"info": self.sanitizeJSON(res)})
|
||||
|
||||
def runner_on_unreachable(self, host, res):
|
||||
self.sendLog(host, "UNREACHABLE", {"info": self.sanitizeJSON(res)})
|
||||
|
||||
def runner_on_async_failed(self, host, res, jid):
|
||||
self.sendLog(host, "ASYNC_FAILED", {"info": self.sanitizeJSON(res), "job_id": jid})
|
||||
|
||||
def runner_on_async_ok(self, host, res, jid):
|
||||
self.sendLog(host, "ASYNC_OK", {"info": self.sanitizeJSON(res), "job_id": jid})
|
||||
+340
@@ -0,0 +1,340 @@
|
||||
# Copyright (c) 2015, Logentries.com, Jimmy Tang <jimmy.tang@logentries.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: Unknown (!UNKNOWN)
|
||||
name: logentries
|
||||
type: notification
|
||||
short_description: Sends events to Logentries
|
||||
description:
|
||||
- This callback plugin generates JSON objects and send them to Logentries using TCP for auditing/debugging purposes.
|
||||
requirements:
|
||||
- whitelisting in configuration
|
||||
- certifi (Python library)
|
||||
- flatdict (Python library), if you want to use the O(flatten) option
|
||||
options:
|
||||
api:
|
||||
description: URI to the Logentries API.
|
||||
type: str
|
||||
env:
|
||||
- name: LOGENTRIES_API
|
||||
default: data.logentries.com
|
||||
ini:
|
||||
- section: callback_logentries
|
||||
key: api
|
||||
port:
|
||||
description: HTTP port to use when connecting to the API.
|
||||
type: int
|
||||
env:
|
||||
- name: LOGENTRIES_PORT
|
||||
default: 80
|
||||
ini:
|
||||
- section: callback_logentries
|
||||
key: port
|
||||
tls_port:
|
||||
description: Port to use when connecting to the API when TLS is enabled.
|
||||
type: int
|
||||
env:
|
||||
- name: LOGENTRIES_TLS_PORT
|
||||
default: 443
|
||||
ini:
|
||||
- section: callback_logentries
|
||||
key: tls_port
|
||||
token:
|
||||
description: The logentries C(TCP token).
|
||||
type: str
|
||||
env:
|
||||
- name: LOGENTRIES_ANSIBLE_TOKEN
|
||||
required: true
|
||||
ini:
|
||||
- section: callback_logentries
|
||||
key: token
|
||||
secret: true
|
||||
use_tls:
|
||||
description:
|
||||
- Toggle to decide whether to use TLS to encrypt the communications with the API server.
|
||||
env:
|
||||
- name: LOGENTRIES_USE_TLS
|
||||
default: false
|
||||
type: boolean
|
||||
ini:
|
||||
- section: callback_logentries
|
||||
key: use_tls
|
||||
flatten:
|
||||
description: Flatten complex data structures into a single dictionary with complex keys.
|
||||
type: boolean
|
||||
default: false
|
||||
env:
|
||||
- name: LOGENTRIES_FLATTEN
|
||||
ini:
|
||||
- section: callback_logentries
|
||||
key: flatten
|
||||
"""
|
||||
|
||||
EXAMPLES = r"""
|
||||
examples: >-
|
||||
To enable, add this to your ansible.cfg file in the defaults block
|
||||
|
||||
[defaults]
|
||||
callback_whitelist = community.general.logentries
|
||||
|
||||
Either set the environment variables
|
||||
export LOGENTRIES_API=data.logentries.com
|
||||
export LOGENTRIES_PORT=10000
|
||||
export LOGENTRIES_ANSIBLE_TOKEN=dd21fc88-f00a-43ff-b977-e3a4233c53af
|
||||
|
||||
Or in the main Ansible config file
|
||||
[callback_logentries]
|
||||
api = data.logentries.com
|
||||
port = 10000
|
||||
tls_port = 20000
|
||||
use_tls = true
|
||||
token = dd21fc88-f00a-43ff-b977-e3a4233c53af
|
||||
flatten = false
|
||||
"""
|
||||
|
||||
import os
|
||||
import random
|
||||
import socket
|
||||
import time
|
||||
import uuid
|
||||
|
||||
try:
|
||||
import certifi
|
||||
|
||||
HAS_CERTIFI = True
|
||||
except ImportError:
|
||||
HAS_CERTIFI = False
|
||||
|
||||
try:
|
||||
import flatdict
|
||||
|
||||
HAS_FLATDICT = True
|
||||
except ImportError:
|
||||
HAS_FLATDICT = False
|
||||
|
||||
from ansible.module_utils.common.text.converters import to_bytes, to_text
|
||||
from ansible.plugins.callback import CallbackBase
|
||||
|
||||
# Todo:
|
||||
# * Better formatting of output before sending out to logentries data/api nodes.
|
||||
|
||||
|
||||
class PlainTextSocketAppender:
|
||||
def __init__(self, display, LE_API="data.logentries.com", LE_PORT=80, LE_TLS_PORT=443):
|
||||
self.LE_API = LE_API
|
||||
self.LE_PORT = LE_PORT
|
||||
self.LE_TLS_PORT = LE_TLS_PORT
|
||||
self.MIN_DELAY = 0.1
|
||||
self.MAX_DELAY = 10
|
||||
# Error message displayed when an incorrect Token has been detected
|
||||
self.INVALID_TOKEN = "\n\nIt appears the LOGENTRIES_TOKEN parameter you entered is incorrect!\n\n"
|
||||
# Unicode Line separator character \u2028
|
||||
self.LINE_SEP = "\u2028"
|
||||
|
||||
self._display = display
|
||||
self._conn = None
|
||||
|
||||
def open_connection(self):
|
||||
self._conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
self._conn.connect((self.LE_API, self.LE_PORT))
|
||||
|
||||
def reopen_connection(self):
|
||||
self.close_connection()
|
||||
|
||||
root_delay = self.MIN_DELAY
|
||||
while True:
|
||||
try:
|
||||
self.open_connection()
|
||||
return
|
||||
except Exception as e:
|
||||
self._display.vvvv(f"Unable to connect to Logentries: {e}")
|
||||
|
||||
root_delay *= 2
|
||||
if root_delay > self.MAX_DELAY:
|
||||
root_delay = self.MAX_DELAY
|
||||
|
||||
wait_for = root_delay + random.uniform(0, root_delay)
|
||||
|
||||
try:
|
||||
self._display.vvvv(f"sleeping {wait_for} before retry")
|
||||
time.sleep(wait_for)
|
||||
except KeyboardInterrupt:
|
||||
raise
|
||||
|
||||
def close_connection(self):
|
||||
if self._conn is not None:
|
||||
self._conn.close()
|
||||
|
||||
def put(self, data):
|
||||
# Replace newlines with Unicode line separator
|
||||
# for multi-line events
|
||||
data = to_text(data, errors="surrogate_or_strict")
|
||||
multiline = data.replace("\n", self.LINE_SEP)
|
||||
multiline += "\n"
|
||||
# Send data, reconnect if needed
|
||||
while True:
|
||||
try:
|
||||
self._conn.send(to_bytes(multiline, errors="surrogate_or_strict"))
|
||||
except OSError:
|
||||
self.reopen_connection()
|
||||
continue
|
||||
break
|
||||
|
||||
self.close_connection()
|
||||
|
||||
|
||||
try:
|
||||
import ssl
|
||||
|
||||
HAS_SSL = True
|
||||
except ImportError: # for systems without TLS support.
|
||||
SocketAppender = PlainTextSocketAppender
|
||||
HAS_SSL = False
|
||||
else:
|
||||
|
||||
class TLSSocketAppender(PlainTextSocketAppender):
|
||||
def open_connection(self):
|
||||
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
context = ssl.create_default_context(
|
||||
purpose=ssl.Purpose.SERVER_AUTH,
|
||||
cafile=certifi.where(),
|
||||
)
|
||||
sock = context.wrap_socket(
|
||||
sock=sock,
|
||||
do_handshake_on_connect=True,
|
||||
suppress_ragged_eofs=True,
|
||||
)
|
||||
sock.connect((self.LE_API, self.LE_TLS_PORT))
|
||||
self._conn = sock
|
||||
|
||||
SocketAppender = TLSSocketAppender # type: ignore
|
||||
|
||||
|
||||
class CallbackModule(CallbackBase):
|
||||
CALLBACK_VERSION = 2.0
|
||||
CALLBACK_TYPE = "notification"
|
||||
CALLBACK_NAME = "community.general.logentries"
|
||||
CALLBACK_NEEDS_WHITELIST = True
|
||||
|
||||
def __init__(self):
|
||||
# TODO: allow for alternate posting methods (REST/UDP/agent/etc)
|
||||
super().__init__()
|
||||
|
||||
# verify dependencies
|
||||
if not HAS_SSL:
|
||||
self._display.warning("Unable to import ssl module. Will send over port 80.")
|
||||
|
||||
if not HAS_CERTIFI:
|
||||
self.disabled = True
|
||||
self._display.warning(
|
||||
"The `certifi` python module is not installed.\nDisabling the Logentries callback plugin."
|
||||
)
|
||||
|
||||
self.le_jobid = str(uuid.uuid4())
|
||||
|
||||
# FIXME: make configurable, move to options
|
||||
self.timeout = 10
|
||||
|
||||
def set_options(self, task_keys=None, var_options=None, direct=None):
|
||||
super().set_options(task_keys=task_keys, var_options=var_options, direct=direct)
|
||||
|
||||
# get options
|
||||
try:
|
||||
self.api_url = self.get_option("api")
|
||||
self.api_port = self.get_option("port")
|
||||
self.api_tls_port = self.get_option("tls_port")
|
||||
self.use_tls = self.get_option("use_tls")
|
||||
self.flatten = self.get_option("flatten")
|
||||
except KeyError as e:
|
||||
self._display.warning(f"Missing option for Logentries callback plugin: {e}")
|
||||
self.disabled = True
|
||||
|
||||
try:
|
||||
self.token = self.get_option("token")
|
||||
except KeyError:
|
||||
self._display.warning(
|
||||
"Logentries token was not provided, this is required for this callback to operate, disabling"
|
||||
)
|
||||
self.disabled = True
|
||||
|
||||
if self.flatten and not HAS_FLATDICT:
|
||||
self.disabled = True
|
||||
self._display.warning(
|
||||
"You have chosen to flatten and the `flatdict` python module is not installed.\nDisabling the Logentries callback plugin."
|
||||
)
|
||||
|
||||
self._initialize_connections()
|
||||
|
||||
def _initialize_connections(self):
|
||||
if not self.disabled:
|
||||
if self.use_tls:
|
||||
self._display.vvvv(f"Connecting to {self.api_url}:{self.api_tls_port} with TLS")
|
||||
self._appender = TLSSocketAppender(
|
||||
display=self._display, LE_API=self.api_url, LE_TLS_PORT=self.api_tls_port
|
||||
)
|
||||
else:
|
||||
self._display.vvvv(f"Connecting to {self.api_url}:{self.api_port}")
|
||||
self._appender = PlainTextSocketAppender(
|
||||
display=self._display, LE_API=self.api_url, LE_PORT=self.api_port
|
||||
)
|
||||
self._appender.reopen_connection()
|
||||
|
||||
def emit_formatted(self, record):
|
||||
if self.flatten:
|
||||
results = flatdict.FlatDict(record)
|
||||
self.emit(self._dump_results(results))
|
||||
else:
|
||||
self.emit(self._dump_results(record))
|
||||
|
||||
def emit(self, record):
|
||||
msg = record.rstrip("\n")
|
||||
msg = f"{self.token} {msg}"
|
||||
self._appender.put(msg)
|
||||
self._display.vvvv("Sent event to logentries")
|
||||
|
||||
def _set_info(self, host, res):
|
||||
return {"le_jobid": self.le_jobid, "hostname": host, "results": res}
|
||||
|
||||
def runner_on_ok(self, host, res):
|
||||
results = self._set_info(host, res)
|
||||
results["status"] = "OK"
|
||||
self.emit_formatted(results)
|
||||
|
||||
def runner_on_failed(self, host, res, ignore_errors=False):
|
||||
results = self._set_info(host, res)
|
||||
results["status"] = "FAILED"
|
||||
self.emit_formatted(results)
|
||||
|
||||
def runner_on_skipped(self, host, item=None):
|
||||
results = self._set_info(host, item)
|
||||
del results["results"]
|
||||
results["status"] = "SKIPPED"
|
||||
self.emit_formatted(results)
|
||||
|
||||
def runner_on_unreachable(self, host, res):
|
||||
results = self._set_info(host, res)
|
||||
results["status"] = "UNREACHABLE"
|
||||
self.emit_formatted(results)
|
||||
|
||||
def runner_on_async_failed(self, host, res, jid):
|
||||
results = self._set_info(host, res)
|
||||
results["jid"] = jid
|
||||
results["status"] = "ASYNC_FAILED"
|
||||
self.emit_formatted(results)
|
||||
|
||||
def v2_playbook_on_play_start(self, play):
|
||||
results = {}
|
||||
results["le_jobid"] = self.le_jobid
|
||||
results["started_by"] = os.getlogin()
|
||||
if play.name:
|
||||
results["play"] = play.name
|
||||
results["hosts"] = play.hosts
|
||||
self.emit_formatted(results)
|
||||
|
||||
def playbook_on_stats(self, stats):
|
||||
"""close connection"""
|
||||
self._appender.close_connection()
|
||||
+710
@@ -0,0 +1,710 @@
|
||||
# Copyright (c) 2020, Yevhen Khmelenko <ujenmr@gmail.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: Yevhen Khmelenko (@ujenmr)
|
||||
name: logstash
|
||||
type: notification
|
||||
short_description: Sends events to Logstash
|
||||
description:
|
||||
- This callback reports facts and task events to Logstash U(https://www.elastic.co/products/logstash).
|
||||
requirements:
|
||||
- whitelisting in configuration
|
||||
- logstash (Python library)
|
||||
options:
|
||||
server:
|
||||
description: Address of the Logstash server. Used with all O(protocol) choices.
|
||||
type: str
|
||||
env:
|
||||
- name: LOGSTASH_SERVER
|
||||
- name: ANSIBLE_CALLBACK_LOGSTASH_SERVER
|
||||
version_added: 14.0.0
|
||||
ini:
|
||||
- section: callback_logstash
|
||||
key: server
|
||||
version_added: 1.0.0
|
||||
vars:
|
||||
- name: ansible_callback_logstash_server
|
||||
version_added: 14.0.0
|
||||
default: localhost
|
||||
port:
|
||||
description: Port on which Logstash is listening. Used with all O(protocol) choices.
|
||||
type: int
|
||||
env:
|
||||
- name: LOGSTASH_PORT
|
||||
- name: ANSIBLE_CALLBACK_LOGSTASH_PORT
|
||||
version_added: 14.0.0
|
||||
ini:
|
||||
- section: callback_logstash
|
||||
key: port
|
||||
version_added: 1.0.0
|
||||
vars:
|
||||
- name: ansible_callback_logstash_port
|
||||
version_added: 14.0.0
|
||||
default: 5000
|
||||
protocol:
|
||||
description: Transport protocol to use when sending events to Logstash.
|
||||
type: str
|
||||
choices:
|
||||
- tcp
|
||||
- http
|
||||
- https
|
||||
env:
|
||||
- name: ANSIBLE_CALLBACK_LOGSTASH_PROTOCOL
|
||||
ini:
|
||||
- section: callback_logstash
|
||||
key: protocol
|
||||
vars:
|
||||
- name: ansible_callback_logstash_protocol
|
||||
default: tcp
|
||||
version_added: 14.0.0
|
||||
http_path:
|
||||
description: >-
|
||||
HTTP request path, for example when sending events through a reverse proxy. This option is used only with
|
||||
O(protocol=http) or O(protocol=https).
|
||||
type: str
|
||||
env:
|
||||
- name: ANSIBLE_CALLBACK_LOGSTASH_HTTP_PATH
|
||||
ini:
|
||||
- section: callback_logstash
|
||||
key: http_path
|
||||
vars:
|
||||
- name: ansible_callback_logstash_http_path
|
||||
default: /
|
||||
version_added: 14.0.0
|
||||
username:
|
||||
description: >-
|
||||
Username for HTTP Basic authentication. This option is used only with O(protocol=http) or O(protocol=https),
|
||||
and must be set together with O(password).
|
||||
type: str
|
||||
env:
|
||||
- name: ANSIBLE_CALLBACK_LOGSTASH_USERNAME
|
||||
ini:
|
||||
- section: callback_logstash
|
||||
key: username
|
||||
vars:
|
||||
- name: ansible_callback_logstash_username
|
||||
version_added: 14.0.0
|
||||
password:
|
||||
description: >-
|
||||
Password for HTTP Basic authentication. This option is used only with O(protocol=http) or O(protocol=https),
|
||||
and must be set together with O(username). Use HTTPS to protect credentials and events in transit.
|
||||
type: str
|
||||
secret: true
|
||||
env:
|
||||
- name: ANSIBLE_CALLBACK_LOGSTASH_PASSWORD
|
||||
ini:
|
||||
- section: callback_logstash
|
||||
key: password
|
||||
vars:
|
||||
- name: ansible_callback_logstash_password
|
||||
version_added: 14.0.0
|
||||
validate_certs:
|
||||
description: Whether to validate the TLS certificate of the Logstash server. This option is used only with O(protocol=https).
|
||||
type: bool
|
||||
default: true
|
||||
env:
|
||||
- name: ANSIBLE_CALLBACK_LOGSTASH_VALIDATE_CERTS
|
||||
ini:
|
||||
- section: callback_logstash
|
||||
key: validate_certs
|
||||
vars:
|
||||
- name: ansible_callback_logstash_validate_certs
|
||||
version_added: 14.0.0
|
||||
ca_path:
|
||||
description: PEM-formatted file containing the CA certificate used to validate the Logstash server. This option is used only with O(protocol=https).
|
||||
type: path
|
||||
env:
|
||||
- name: ANSIBLE_CALLBACK_LOGSTASH_CA_PATH
|
||||
ini:
|
||||
- section: callback_logstash
|
||||
key: ca_path
|
||||
vars:
|
||||
- name: ansible_callback_logstash_ca_path
|
||||
version_added: 14.0.0
|
||||
client_cert:
|
||||
description: PEM-formatted certificate chain file for TLS client authentication. This option is used only with O(protocol=https).
|
||||
type: path
|
||||
env:
|
||||
- name: ANSIBLE_CALLBACK_LOGSTASH_CLIENT_CERT
|
||||
ini:
|
||||
- section: callback_logstash
|
||||
key: client_cert
|
||||
vars:
|
||||
- name: ansible_callback_logstash_client_cert
|
||||
version_added: 14.0.0
|
||||
client_key:
|
||||
description: >-
|
||||
PEM-formatted private key file for TLS client authentication. The key can also be included in O(client_cert).
|
||||
This option is used only with O(protocol=https).
|
||||
type: path
|
||||
env:
|
||||
- name: ANSIBLE_CALLBACK_LOGSTASH_CLIENT_KEY
|
||||
ini:
|
||||
- section: callback_logstash
|
||||
key: client_key
|
||||
vars:
|
||||
- name: ansible_callback_logstash_client_key
|
||||
version_added: 14.0.0
|
||||
timeout:
|
||||
description: Maximum time in seconds to wait for an HTTP request to complete. This option is used only with O(protocol=http) or O(protocol=https).
|
||||
type: int
|
||||
default: 10
|
||||
env:
|
||||
- name: ANSIBLE_CALLBACK_LOGSTASH_TIMEOUT
|
||||
ini:
|
||||
- section: callback_logstash
|
||||
key: timeout
|
||||
vars:
|
||||
- name: ansible_callback_logstash_timeout
|
||||
version_added: 14.0.0
|
||||
retries:
|
||||
description: >-
|
||||
Number of retries for HTTP 429 (Too Many Requests) responses. Uses exponential backoff with jitter between attempts. This
|
||||
option is used only with O(protocol=http) or O(protocol=https).
|
||||
type: int
|
||||
default: 3
|
||||
env:
|
||||
- name: ANSIBLE_CALLBACK_LOGSTASH_RETRIES
|
||||
ini:
|
||||
- section: callback_logstash
|
||||
key: retries
|
||||
vars:
|
||||
- name: ansible_callback_logstash_retries
|
||||
version_added: 14.0.0
|
||||
type:
|
||||
description: Message type. Used with all O(protocol) choices.
|
||||
type: str
|
||||
env:
|
||||
- name: LOGSTASH_TYPE
|
||||
- name: ANSIBLE_CALLBACK_LOGSTASH_TYPE
|
||||
version_added: 14.0.0
|
||||
ini:
|
||||
- section: callback_logstash
|
||||
key: type
|
||||
version_added: 1.0.0
|
||||
vars:
|
||||
- name: ansible_callback_logstash_type
|
||||
version_added: 14.0.0
|
||||
default: ansible
|
||||
pre_command:
|
||||
description: Executes command before run and adds its result to the C(ansible_pre_command_output) Logstash field. Used with all O(protocol) choices.
|
||||
type: str
|
||||
version_added: 2.0.0
|
||||
ini:
|
||||
- section: callback_logstash
|
||||
key: pre_command
|
||||
env:
|
||||
- name: LOGSTASH_PRE_COMMAND
|
||||
- name: ANSIBLE_CALLBACK_LOGSTASH_PRE_COMMAND
|
||||
version_added: 14.0.0
|
||||
vars:
|
||||
- name: ansible_callback_logstash_pre_command
|
||||
version_added: 14.0.0
|
||||
format_version:
|
||||
description: Logging format. Used with all O(protocol) choices.
|
||||
type: str
|
||||
version_added: 2.0.0
|
||||
ini:
|
||||
- section: callback_logstash
|
||||
key: format_version
|
||||
env:
|
||||
- name: LOGSTASH_FORMAT_VERSION
|
||||
- name: ANSIBLE_CALLBACK_LOGSTASH_FORMAT_VERSION
|
||||
version_added: 14.0.0
|
||||
vars:
|
||||
- name: ansible_callback_logstash_format_version
|
||||
version_added: 14.0.0
|
||||
default: v1
|
||||
choices:
|
||||
- v1
|
||||
- v2
|
||||
"""
|
||||
|
||||
EXAMPLES = r"""
|
||||
ansible.cfg: |
|
||||
# Enable Callback plugin
|
||||
[defaults]
|
||||
callback_whitelist = community.general.logstash
|
||||
|
||||
[callback_logstash]
|
||||
server = logstash.example.com
|
||||
port = 5000
|
||||
protocol = tcp
|
||||
pre_command = git rev-parse HEAD
|
||||
type = ansible
|
||||
|
||||
ansible.cfg (HTTPS with Basic authentication): |
|
||||
# Store the password in ANSIBLE_CALLBACK_LOGSTASH_PASSWORD or a secrets manager, not in this file
|
||||
[defaults]
|
||||
callbacks_enabled = community.general.logstash
|
||||
|
||||
[callback_logstash]
|
||||
protocol = https
|
||||
server = logstash.example.com
|
||||
port = 8080
|
||||
http_path = /
|
||||
username = ansible
|
||||
|
||||
11-input-http.conf: |-
|
||||
# Enable Logstash HTTP Input
|
||||
input {
|
||||
http {
|
||||
port => 8080
|
||||
user => "${LOGSTASH_HTTP_USER}"
|
||||
password => "${LOGSTASH_HTTP_PASSWORD}"
|
||||
ssl_enabled => true
|
||||
ssl_certificate => "/etc/logstash/server.crt"
|
||||
ssl_key => "/etc/logstash/server.pkcs8.key"
|
||||
}
|
||||
}
|
||||
|
||||
11-input-tcp.conf: |-
|
||||
# Enable Logstash TCP Input
|
||||
input {
|
||||
tcp {
|
||||
port => 5000
|
||||
codec => json
|
||||
add_field => { "[@metadata][beat]" => "notify" }
|
||||
add_field => { "[@metadata][type]" => "ansible" }
|
||||
}
|
||||
}
|
||||
"""
|
||||
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import random
|
||||
import socket
|
||||
import time
|
||||
import uuid
|
||||
from urllib.error import HTTPError
|
||||
|
||||
from ansible import context
|
||||
from ansible.errors import AnsibleError
|
||||
from ansible.module_utils.urls import open_url
|
||||
from ansible.utils.display import Display
|
||||
|
||||
try:
|
||||
import logstash
|
||||
from logstash.formatter import LogstashFormatterVersion1
|
||||
|
||||
HAS_LOGSTASH = True
|
||||
except ImportError:
|
||||
HAS_LOGSTASH = False
|
||||
LogstashFormatterVersion1 = None
|
||||
|
||||
from ansible.plugins.callback import CallbackBase
|
||||
|
||||
from ansible_collections.community.general.plugins.module_utils._datetime import (
|
||||
now,
|
||||
)
|
||||
from ansible_collections.community.general.plugins.module_utils._secrets import mask_secrets
|
||||
|
||||
|
||||
class LogstashHTTPHandler(logging.Handler):
|
||||
def __init__(
|
||||
self,
|
||||
url,
|
||||
formatter,
|
||||
username=None,
|
||||
password=None,
|
||||
validate_certs=True,
|
||||
ca_path=None,
|
||||
client_cert=None,
|
||||
client_key=None,
|
||||
timeout=10,
|
||||
retries=3,
|
||||
display=None,
|
||||
):
|
||||
super().__init__()
|
||||
self.url = url
|
||||
self.formatter = formatter
|
||||
self.username = username
|
||||
self.password = password
|
||||
self.validate_certs = validate_certs
|
||||
self.ca_path = ca_path
|
||||
self.client_cert = client_cert
|
||||
self.client_key = client_key
|
||||
self.timeout = timeout
|
||||
self.retries = retries
|
||||
self._display = display or Display()
|
||||
|
||||
def emit(self, record):
|
||||
try:
|
||||
data = self.formatter.format(record)
|
||||
except Exception as error:
|
||||
raise AnsibleError("Could not format event for Logstash HTTP delivery.") from error
|
||||
kwargs = {
|
||||
"data": data,
|
||||
"headers": {"Content-Type": "application/json"},
|
||||
"method": "POST",
|
||||
"timeout": self.timeout,
|
||||
"validate_certs": self.validate_certs,
|
||||
"use_netrc": False,
|
||||
"follow_redirects": "none",
|
||||
}
|
||||
if self.username and self.password:
|
||||
kwargs.update(
|
||||
url_username=self.username,
|
||||
url_password=self.password,
|
||||
force_basic_auth=True,
|
||||
)
|
||||
if self.ca_path is not None:
|
||||
kwargs["ca_path"] = self.ca_path
|
||||
if self.client_cert is not None:
|
||||
kwargs["client_cert"] = self.client_cert
|
||||
if self.client_key is not None:
|
||||
kwargs["client_key"] = self.client_key
|
||||
|
||||
status = None
|
||||
for attempt in range(self.retries + 1):
|
||||
response = None
|
||||
try:
|
||||
try:
|
||||
response = open_url(self.url, **kwargs)
|
||||
except HTTPError as error:
|
||||
response = error
|
||||
status = error.code
|
||||
except Exception as error:
|
||||
raise AnsibleError("Could not send event to Logstash over HTTP.") from error
|
||||
else:
|
||||
status = response.getcode()
|
||||
finally:
|
||||
if response is not None:
|
||||
response.close()
|
||||
|
||||
if status in (200, 201, 202, 204):
|
||||
return
|
||||
if status != 429 or attempt == self.retries:
|
||||
break
|
||||
time.sleep(0.5 * 2**attempt + random.uniform(0, 0.25))
|
||||
|
||||
raise AnsibleError(f"Logstash HTTP request failed with status code {status}.")
|
||||
|
||||
|
||||
class CallbackModule(CallbackBase):
|
||||
CALLBACK_VERSION = 2.0
|
||||
CALLBACK_TYPE = "notification"
|
||||
CALLBACK_NAME = "community.general.logstash"
|
||||
CALLBACK_NEEDS_WHITELIST = True
|
||||
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
|
||||
if not HAS_LOGSTASH:
|
||||
self.disabled = True
|
||||
self._display.warning("The required python3-logstash is not installed.")
|
||||
|
||||
self.start_time = now()
|
||||
|
||||
def _init_plugin(self):
|
||||
if not self.disabled:
|
||||
self.logger = logging.getLogger("python-logstash-logger")
|
||||
self.logger.setLevel(logging.DEBUG)
|
||||
|
||||
if self.ls_protocol == "tcp":
|
||||
self.handler = logstash.TCPLogstashHandler(
|
||||
self.ls_server, self.ls_port, version=1, message_type=self.ls_type
|
||||
)
|
||||
else:
|
||||
server = self.ls_server
|
||||
if ":" in server and not server.startswith("["):
|
||||
server = f"[{server}]"
|
||||
path = self.ls_http_path or "/"
|
||||
if not path.startswith("/"):
|
||||
path = f"/{path}"
|
||||
url = f"{self.ls_protocol}://{server}:{self.ls_port}{path}"
|
||||
formatter = LogstashFormatterVersion1(message_type=self.ls_type)
|
||||
self.handler = LogstashHTTPHandler(
|
||||
url=url,
|
||||
formatter=formatter,
|
||||
username=self.ls_username,
|
||||
password=self.ls_password,
|
||||
validate_certs=self.ls_validate_certs,
|
||||
ca_path=self.ls_ca_path,
|
||||
client_cert=self.ls_client_cert,
|
||||
client_key=self.ls_client_key,
|
||||
timeout=self.ls_timeout,
|
||||
retries=self.ls_retries,
|
||||
display=self._display,
|
||||
)
|
||||
|
||||
self.logger.addHandler(self.handler)
|
||||
self.hostname = socket.gethostname()
|
||||
self.session = str(uuid.uuid4())
|
||||
self.errors = 0
|
||||
|
||||
self.base_data = {"session": self.session, "host": self.hostname}
|
||||
|
||||
if self.ls_pre_command is not None:
|
||||
self.base_data["ansible_pre_command_output"] = os.popen(self.ls_pre_command).read()
|
||||
|
||||
if context.CLIARGS is not None:
|
||||
self.base_data["ansible_checkmode"] = context.CLIARGS.get("check")
|
||||
self.base_data["ansible_tags"] = context.CLIARGS.get("tags")
|
||||
self.base_data["ansible_skip_tags"] = context.CLIARGS.get("skip_tags")
|
||||
self.base_data["inventory"] = context.CLIARGS.get("inventory")
|
||||
|
||||
def set_options(self, task_keys=None, var_options=None, direct=None):
|
||||
super().set_options(task_keys=task_keys, var_options=var_options, direct=direct)
|
||||
|
||||
self.ls_server = self.get_option("server")
|
||||
self.ls_port = int(self.get_option("port"))
|
||||
self.ls_protocol = self.get_option("protocol")
|
||||
self.ls_http_path = self.get_option("http_path")
|
||||
self.ls_username = self.get_option("username")
|
||||
self.ls_password = self.get_option("password")
|
||||
self.ls_validate_certs = self.get_option("validate_certs")
|
||||
self.ls_ca_path = self.get_option("ca_path")
|
||||
self.ls_client_cert = self.get_option("client_cert")
|
||||
self.ls_client_key = self.get_option("client_key")
|
||||
self.ls_timeout = self.get_option("timeout")
|
||||
self.ls_retries = self.get_option("retries")
|
||||
self.ls_type = self.get_option("type")
|
||||
self.ls_pre_command = self.get_option("pre_command")
|
||||
self.ls_format_version = self.get_option("format_version")
|
||||
|
||||
if self.ls_protocol != "tcp":
|
||||
if bool(self.ls_username) != bool(self.ls_password):
|
||||
raise AnsibleError("Both Logstash HTTP username and password must be configured.")
|
||||
if self.ls_timeout <= 0:
|
||||
raise AnsibleError("Logstash HTTP timeout must be greater than zero.")
|
||||
if self.ls_retries < 0:
|
||||
raise AnsibleError("Logstash HTTP retries must be zero or greater.")
|
||||
if self.ls_protocol != "https" and (self.ls_ca_path or self.ls_client_cert or self.ls_client_key):
|
||||
raise AnsibleError("Logstash TLS certificate options can only be used with HTTPS.")
|
||||
if self.ls_client_key and not self.ls_client_cert:
|
||||
raise AnsibleError("Logstash client_key requires client_cert.")
|
||||
|
||||
self._init_plugin()
|
||||
|
||||
def v2_playbook_on_start(self, playbook):
|
||||
data = self.base_data.copy()
|
||||
data["ansible_type"] = "start"
|
||||
data["status"] = "OK"
|
||||
data["ansible_playbook"] = playbook._file_name
|
||||
|
||||
if self.ls_format_version == "v2":
|
||||
self.logger.info("START PLAYBOOK | %s", data["ansible_playbook"], extra=data)
|
||||
else:
|
||||
self.logger.info("ansible start", extra=data)
|
||||
|
||||
def v2_playbook_on_stats(self, stats):
|
||||
end_time = now()
|
||||
runtime = end_time - self.start_time
|
||||
summarize_stat = {}
|
||||
for host in stats.processed.keys():
|
||||
summarize_stat[host] = stats.summarize(host)
|
||||
|
||||
if self.errors == 0:
|
||||
status = "OK"
|
||||
else:
|
||||
status = "FAILED"
|
||||
|
||||
data = self.base_data.copy()
|
||||
data["ansible_type"] = "finish"
|
||||
data["status"] = status
|
||||
data["ansible_playbook_duration"] = runtime.total_seconds()
|
||||
data["ansible_result"] = json.dumps(summarize_stat) # deprecated field
|
||||
|
||||
if self.ls_format_version == "v2":
|
||||
self.logger.info("FINISH PLAYBOOK | %s", json.dumps(summarize_stat), extra=data)
|
||||
else:
|
||||
self.logger.info("ansible stats", extra=data)
|
||||
|
||||
def v2_playbook_on_play_start(self, play):
|
||||
self.play_id = str(play._uuid)
|
||||
|
||||
if play.name:
|
||||
self.play_name = play.name
|
||||
|
||||
data = self.base_data.copy()
|
||||
data["ansible_type"] = "start"
|
||||
data["status"] = "OK"
|
||||
data["ansible_play_id"] = self.play_id
|
||||
data["ansible_play_name"] = mask_secrets(self.play_name)
|
||||
|
||||
if self.ls_format_version == "v2":
|
||||
self.logger.info("START PLAY | %s", mask_secrets(self.play_name), extra=data)
|
||||
else:
|
||||
self.logger.info("ansible play", extra=data)
|
||||
|
||||
def v2_playbook_on_task_start(self, task, is_conditional):
|
||||
self.task_id = str(task._uuid)
|
||||
|
||||
"""
|
||||
Tasks and handler tasks are dealt with here
|
||||
"""
|
||||
|
||||
def v2_runner_on_ok(self, result, **kwargs):
|
||||
task_name = str(result._task).replace("TASK: ", "").replace("HANDLER: ", "")
|
||||
|
||||
data = self.base_data.copy()
|
||||
if task_name == "setup":
|
||||
data["ansible_type"] = "setup"
|
||||
data["status"] = "OK"
|
||||
data["ansible_host"] = result._host.name
|
||||
data["ansible_play_id"] = self.play_id
|
||||
data["ansible_play_name"] = mask_secrets(self.play_name)
|
||||
data["ansible_task"] = mask_secrets(task_name)
|
||||
data["ansible_facts"] = self._dump_results(result._result)
|
||||
|
||||
if self.ls_format_version == "v2":
|
||||
self.logger.info("SETUP FACTS | %s", self._dump_results(result._result), extra=data)
|
||||
else:
|
||||
self.logger.info("ansible facts", extra=data)
|
||||
else:
|
||||
if "changed" in result._result.keys():
|
||||
data["ansible_changed"] = result._result["changed"]
|
||||
else:
|
||||
data["ansible_changed"] = False
|
||||
|
||||
data["ansible_type"] = "task"
|
||||
data["status"] = "OK"
|
||||
data["ansible_host"] = result._host.name
|
||||
data["ansible_play_id"] = self.play_id
|
||||
data["ansible_play_name"] = mask_secrets(self.play_name)
|
||||
data["ansible_task"] = mask_secrets(task_name)
|
||||
data["ansible_task_id"] = self.task_id
|
||||
data["ansible_result"] = self._dump_results(result._result)
|
||||
|
||||
if self.ls_format_version == "v2":
|
||||
self.logger.info(
|
||||
"TASK OK | %s | RESULT | %s",
|
||||
mask_secrets(task_name),
|
||||
self._dump_results(result._result),
|
||||
extra=data,
|
||||
)
|
||||
else:
|
||||
self.logger.info("ansible ok", extra=data)
|
||||
|
||||
def v2_runner_on_skipped(self, result, **kwargs):
|
||||
task_name = str(result._task).replace("TASK: ", "").replace("HANDLER: ", "")
|
||||
|
||||
data = self.base_data.copy()
|
||||
data["ansible_type"] = "task"
|
||||
data["status"] = "SKIPPED"
|
||||
data["ansible_host"] = result._host.name
|
||||
data["ansible_play_id"] = self.play_id
|
||||
data["ansible_play_name"] = mask_secrets(self.play_name)
|
||||
data["ansible_task"] = mask_secrets(task_name)
|
||||
data["ansible_task_id"] = self.task_id
|
||||
data["ansible_result"] = self._dump_results(result._result)
|
||||
|
||||
if self.ls_format_version == "v2":
|
||||
self.logger.info("TASK SKIPPED | %s", mask_secrets(task_name), extra=data)
|
||||
else:
|
||||
self.logger.info("ansible skipped", extra=data)
|
||||
|
||||
def v2_playbook_on_import_for_host(self, result, imported_file):
|
||||
data = self.base_data.copy()
|
||||
data["ansible_type"] = "import"
|
||||
data["status"] = "IMPORTED"
|
||||
data["ansible_host"] = result._host.name
|
||||
data["ansible_play_id"] = self.play_id
|
||||
data["ansible_play_name"] = mask_secrets(self.play_name)
|
||||
data["imported_file"] = mask_secrets(imported_file)
|
||||
|
||||
if self.ls_format_version == "v2":
|
||||
self.logger.info("IMPORT | %s", mask_secrets(imported_file), extra=data)
|
||||
else:
|
||||
self.logger.info("ansible import", extra=data)
|
||||
|
||||
def v2_playbook_on_not_import_for_host(self, result, missing_file):
|
||||
data = self.base_data.copy()
|
||||
data["ansible_type"] = "import"
|
||||
data["status"] = "NOT IMPORTED"
|
||||
data["ansible_host"] = result._host.name
|
||||
data["ansible_play_id"] = self.play_id
|
||||
data["ansible_play_name"] = mask_secrets(self.play_name)
|
||||
data["imported_file"] = mask_secrets(missing_file)
|
||||
|
||||
if self.ls_format_version == "v2":
|
||||
self.logger.info("NOT IMPORTED | %s", mask_secrets(missing_file), extra=data)
|
||||
else:
|
||||
self.logger.info("ansible import", extra=data)
|
||||
|
||||
def v2_runner_on_failed(self, result, **kwargs):
|
||||
task_name = str(result._task).replace("TASK: ", "").replace("HANDLER: ", "")
|
||||
|
||||
data = self.base_data.copy()
|
||||
if "changed" in result._result.keys():
|
||||
data["ansible_changed"] = result._result["changed"]
|
||||
else:
|
||||
data["ansible_changed"] = False
|
||||
|
||||
data["ansible_type"] = "task"
|
||||
data["status"] = "FAILED"
|
||||
data["ansible_host"] = result._host.name
|
||||
data["ansible_play_id"] = self.play_id
|
||||
data["ansible_play_name"] = mask_secrets(self.play_name)
|
||||
data["ansible_task"] = mask_secrets(task_name)
|
||||
data["ansible_task_id"] = self.task_id
|
||||
data["ansible_result"] = self._dump_results(result._result)
|
||||
|
||||
self.errors += 1
|
||||
if self.ls_format_version == "v2":
|
||||
self.logger.error(
|
||||
"TASK FAILED | %s | HOST | %s | RESULT | %s",
|
||||
mask_secrets(task_name),
|
||||
self.hostname,
|
||||
self._dump_results(result._result),
|
||||
extra=data,
|
||||
)
|
||||
else:
|
||||
self.logger.error("ansible failed", extra=data)
|
||||
|
||||
def v2_runner_on_unreachable(self, result, **kwargs):
|
||||
task_name = str(result._task).replace("TASK: ", "").replace("HANDLER: ", "")
|
||||
|
||||
data = self.base_data.copy()
|
||||
data["ansible_type"] = "task"
|
||||
data["status"] = "UNREACHABLE"
|
||||
data["ansible_host"] = result._host.name
|
||||
data["ansible_play_id"] = self.play_id
|
||||
data["ansible_play_name"] = mask_secrets(self.play_name)
|
||||
data["ansible_task"] = mask_secrets(task_name)
|
||||
data["ansible_task_id"] = self.task_id
|
||||
data["ansible_result"] = self._dump_results(result._result)
|
||||
|
||||
self.errors += 1
|
||||
if self.ls_format_version == "v2":
|
||||
self.logger.error(
|
||||
"UNREACHABLE | %s | HOST | %s | RESULT | %s",
|
||||
mask_secrets(task_name),
|
||||
self.hostname,
|
||||
self._dump_results(result._result),
|
||||
extra=data,
|
||||
)
|
||||
else:
|
||||
self.logger.error("ansible unreachable", extra=data)
|
||||
|
||||
def v2_runner_on_async_failed(self, result, **kwargs):
|
||||
task_name = str(result._task).replace("TASK: ", "").replace("HANDLER: ", "")
|
||||
|
||||
data = self.base_data.copy()
|
||||
data["ansible_type"] = "task"
|
||||
data["status"] = "FAILED"
|
||||
data["ansible_host"] = result._host.name
|
||||
data["ansible_play_id"] = self.play_id
|
||||
data["ansible_play_name"] = mask_secrets(self.play_name)
|
||||
data["ansible_task"] = mask_secrets(task_name)
|
||||
data["ansible_task_id"] = self.task_id
|
||||
data["ansible_result"] = self._dump_results(result._result)
|
||||
|
||||
self.errors += 1
|
||||
if self.ls_format_version == "v2":
|
||||
self.logger.error(
|
||||
"ASYNC FAILED | %s | HOST | %s | RESULT | %s",
|
||||
mask_secrets(task_name),
|
||||
self.hostname,
|
||||
self._dump_results(result._result),
|
||||
extra=data,
|
||||
)
|
||||
else:
|
||||
self.logger.error("ansible async", extra=data)
|
||||
@@ -0,0 +1,263 @@
|
||||
# Copyright (c) 2012, Dag Wieers <dag@wieers.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
|
||||
|
||||
DOCUMENTATION = r"""
|
||||
name: mail
|
||||
type: notification
|
||||
short_description: Sends failure events through email
|
||||
description:
|
||||
- This callback reports failures through email.
|
||||
author:
|
||||
- Dag Wieers (@dagwieers)
|
||||
requirements:
|
||||
- whitelisting in configuration
|
||||
options:
|
||||
mta:
|
||||
description:
|
||||
- Mail Transfer Agent, server that accepts SMTP.
|
||||
type: str
|
||||
env:
|
||||
- name: SMTPHOST
|
||||
ini:
|
||||
- section: callback_mail
|
||||
key: smtphost
|
||||
default: localhost
|
||||
mtaport:
|
||||
description:
|
||||
- Mail Transfer Agent Port.
|
||||
- Port at which server SMTP.
|
||||
type: int
|
||||
ini:
|
||||
- section: callback_mail
|
||||
key: smtpport
|
||||
default: 25
|
||||
to:
|
||||
description:
|
||||
- Mail recipient.
|
||||
type: list
|
||||
elements: str
|
||||
ini:
|
||||
- section: callback_mail
|
||||
key: to
|
||||
default: [root]
|
||||
sender:
|
||||
description:
|
||||
- Mail sender.
|
||||
- This is required since community.general 6.0.0.
|
||||
type: str
|
||||
required: true
|
||||
ini:
|
||||
- section: callback_mail
|
||||
key: sender
|
||||
cc:
|
||||
description:
|
||||
- CC'd recipients.
|
||||
type: list
|
||||
elements: str
|
||||
ini:
|
||||
- section: callback_mail
|
||||
key: cc
|
||||
bcc:
|
||||
description:
|
||||
- BCC'd recipients.
|
||||
type: list
|
||||
elements: str
|
||||
ini:
|
||||
- section: callback_mail
|
||||
key: bcc
|
||||
message_id_domain:
|
||||
description:
|
||||
- The domain name to use for the L(Message-ID header, https://en.wikipedia.org/wiki/Message-ID).
|
||||
- The default is the hostname of the control node.
|
||||
type: str
|
||||
ini:
|
||||
- section: callback_mail
|
||||
key: message_id_domain
|
||||
version_added: 8.2.0
|
||||
"""
|
||||
|
||||
import email.utils
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import smtplib
|
||||
|
||||
from ansible.module_utils.common.text.converters import to_bytes
|
||||
from ansible.parsing.ajson import AnsibleJSONEncoder
|
||||
from ansible.plugins.callback import CallbackBase
|
||||
|
||||
from ansible_collections.community.general.plugins.module_utils._secrets import mask_secret_values, mask_secrets
|
||||
|
||||
|
||||
class CallbackModule(CallbackBase):
|
||||
"""This Ansible callback plugin mails errors to interested parties."""
|
||||
|
||||
CALLBACK_VERSION = 2.0
|
||||
CALLBACK_TYPE = "notification"
|
||||
CALLBACK_NAME = "community.general.mail"
|
||||
CALLBACK_NEEDS_WHITELIST = True
|
||||
|
||||
def __init__(self, display=None):
|
||||
super().__init__(display=display)
|
||||
self.sender = None
|
||||
self.to = "root"
|
||||
self.smtphost = os.getenv("SMTPHOST", "localhost")
|
||||
self.smtpport = 25
|
||||
self.cc = None
|
||||
self.bcc = None
|
||||
|
||||
def set_options(self, task_keys=None, var_options=None, direct=None):
|
||||
super().set_options(task_keys=task_keys, var_options=var_options, direct=direct)
|
||||
|
||||
self.sender = self.get_option("sender")
|
||||
self.to = self.get_option("to")
|
||||
self.smtphost = self.get_option("mta")
|
||||
self.smtpport = self.get_option("mtaport")
|
||||
self.cc = self.get_option("cc")
|
||||
self.bcc = self.get_option("bcc")
|
||||
|
||||
def mail(self, subject="Ansible error mail", body=None):
|
||||
if body is None:
|
||||
body = subject
|
||||
|
||||
smtp = smtplib.SMTP(self.smtphost, port=self.smtpport)
|
||||
|
||||
sender_address = email.utils.parseaddr(self.sender)
|
||||
if self.to:
|
||||
to_addresses = email.utils.getaddresses(self.to)
|
||||
if self.cc:
|
||||
cc_addresses = email.utils.getaddresses(self.cc)
|
||||
if self.bcc:
|
||||
bcc_addresses = email.utils.getaddresses(self.bcc)
|
||||
|
||||
content = f"Date: {email.utils.formatdate()}\n"
|
||||
content += f"From: {email.utils.formataddr(sender_address)}\n"
|
||||
if self.to:
|
||||
content += f"To: {', '.join([email.utils.formataddr(pair) for pair in to_addresses])}\n"
|
||||
if self.cc:
|
||||
content += f"Cc: {', '.join([email.utils.formataddr(pair) for pair in cc_addresses])}\n"
|
||||
content += f"Message-ID: {email.utils.make_msgid(domain=self.get_option('message_id_domain'))}\n"
|
||||
content += f"Subject: {subject.strip()}\n\n"
|
||||
content += body
|
||||
|
||||
addresses = to_addresses
|
||||
if self.cc:
|
||||
addresses += cc_addresses
|
||||
if self.bcc:
|
||||
addresses += bcc_addresses
|
||||
|
||||
if not addresses:
|
||||
self._display.warning("No receiver has been specified for the mail callback plugin.")
|
||||
|
||||
smtp.sendmail(self.sender, [address for name, address in addresses], to_bytes(content))
|
||||
|
||||
smtp.quit()
|
||||
|
||||
def subject_msg(self, multiline, failtype, linenr):
|
||||
msg = multiline.strip("\r\n").splitlines()[linenr]
|
||||
return f"{failtype}: {msg}"
|
||||
|
||||
def indent(self, multiline, indent=8):
|
||||
return re.sub("^", " " * indent, multiline, flags=re.MULTILINE)
|
||||
|
||||
def body_blob(self, multiline, texttype):
|
||||
"""Turn some text output in a well-indented block for sending in a mail body"""
|
||||
intro = f"with the following {texttype}:\n\n"
|
||||
blob = "\n".join(multiline.strip("\r\n").splitlines())
|
||||
return f"{intro}{self.indent(blob)}\n"
|
||||
|
||||
def mail_result(self, result, failtype):
|
||||
host = result._host.get_name()
|
||||
if not self.sender:
|
||||
self.sender = f'"Ansible: {host}" <root>'
|
||||
|
||||
# Add subject
|
||||
if self.itembody:
|
||||
subject = self.itemsubject
|
||||
elif result._result.get("failed_when_result") is True:
|
||||
subject = "Failed due to 'failed_when' condition"
|
||||
elif result._result.get("msg"):
|
||||
subject = self.subject_msg(result._result["msg"], failtype, 0)
|
||||
elif result._result.get("stderr"):
|
||||
subject = self.subject_msg(result._result["stderr"], failtype, -1)
|
||||
elif result._result.get("stdout"):
|
||||
subject = self.subject_msg(result._result["stdout"], failtype, -1)
|
||||
elif result._result.get("exception"): # Unrelated exceptions are added to output :-/
|
||||
subject = self.subject_msg(result._result["exception"], failtype, -1)
|
||||
else:
|
||||
subject = f"{failtype}: {result._task.name or result._task.action}"
|
||||
|
||||
# Make playbook name visible (e.g. in Outlook/Gmail condensed view)
|
||||
body = f"Playbook: {os.path.basename(self.playbook._file_name)}\n"
|
||||
if result._task.name:
|
||||
body += f"Task: {mask_secrets(result._task.name)}\n"
|
||||
body += f"Module: {result._task.action}\n"
|
||||
body += f"Host: {host}\n"
|
||||
body += "\n"
|
||||
|
||||
# Add task information (as much as possible)
|
||||
body += "The following task failed:\n\n"
|
||||
if "invocation" in result._result:
|
||||
body += self.indent(
|
||||
f"{result._task.action}: {json.dumps(result._result['invocation']['module_args'], indent=4)}\n"
|
||||
)
|
||||
elif result._task.name:
|
||||
body += self.indent(f"{mask_secrets(result._task.name)} ({result._task.action})\n")
|
||||
else:
|
||||
body += self.indent(f"{result._task.action}\n")
|
||||
body += "\n"
|
||||
|
||||
# Add item / message
|
||||
if self.itembody:
|
||||
body += self.itembody
|
||||
elif result._result.get("failed_when_result") is True:
|
||||
fail_cond_list = "\n- ".join(mask_secret_values(result._task.failed_when))
|
||||
fail_cond = self.indent(f"failed_when:\n- {fail_cond_list}")
|
||||
body += f"due to the following condition:\n\n{fail_cond}\n\n"
|
||||
elif result._result.get("msg"):
|
||||
body += self.body_blob(result._result["msg"], "message")
|
||||
|
||||
# Add stdout / stderr / exception / warnings / deprecations
|
||||
if result._result.get("stdout"):
|
||||
body += self.body_blob(result._result["stdout"], "standard output")
|
||||
if result._result.get("stderr"):
|
||||
body += self.body_blob(result._result["stderr"], "error output")
|
||||
if result._result.get("exception"): # Unrelated exceptions are added to output :-/
|
||||
body += self.body_blob(result._result["exception"], "exception")
|
||||
if result._result.get("warnings"):
|
||||
for i in range(len(result._result.get("warnings"))):
|
||||
body += self.body_blob(result._result["warnings"][i], f"exception {i + 1}")
|
||||
if result._result.get("deprecations"):
|
||||
for i in range(len(result._result.get("deprecations"))):
|
||||
body += self.body_blob(result._result["deprecations"][i], f"exception {i + 1}")
|
||||
|
||||
body += "and a complete dump of the error:\n\n"
|
||||
body += self.indent(f"{failtype}: {json.dumps(result._result, cls=AnsibleJSONEncoder, indent=4)}")
|
||||
|
||||
self.mail(subject=subject, body=body)
|
||||
|
||||
def v2_playbook_on_start(self, playbook):
|
||||
self.playbook = playbook
|
||||
self.itembody = ""
|
||||
|
||||
def v2_runner_on_failed(self, result, ignore_errors=False):
|
||||
if ignore_errors:
|
||||
return
|
||||
|
||||
self.mail_result(result, "Failed")
|
||||
|
||||
def v2_runner_on_unreachable(self, result):
|
||||
self.mail_result(result, "Unreachable")
|
||||
|
||||
def v2_runner_on_async_failed(self, result):
|
||||
self.mail_result(result, "Async failure")
|
||||
|
||||
def v2_runner_item_on_failed(self, result):
|
||||
# Pass item information to task failure
|
||||
self.itemsubject = result._result["msg"]
|
||||
self.itembody += self.body_blob(
|
||||
json.dumps(result._result, cls=AnsibleJSONEncoder, indent=4), f"failed item dump '{result._result['item']}'"
|
||||
)
|
||||
@@ -0,0 +1,187 @@
|
||||
# Copyright (c) 2018 Remi Verchere <remi@verchere.fr>
|
||||
# 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"""
|
||||
name: nrdp
|
||||
type: notification
|
||||
author: "Remi VERCHERE (@rverchere)"
|
||||
short_description: Post task results to a Nagios server through nrdp
|
||||
description:
|
||||
- This callback send playbook result to Nagios.
|
||||
- Nagios shall use NRDP to receive passive events.
|
||||
- The passive check is sent to a dedicated host/service for Ansible.
|
||||
options:
|
||||
url:
|
||||
description: URL of the nrdp server.
|
||||
required: true
|
||||
env:
|
||||
- name: NRDP_URL
|
||||
ini:
|
||||
- section: callback_nrdp
|
||||
key: url
|
||||
type: string
|
||||
validate_certs:
|
||||
description: Validate the SSL certificate of the nrdp server. (Used for HTTPS URLs).
|
||||
env:
|
||||
- name: NRDP_VALIDATE_CERTS
|
||||
ini:
|
||||
- section: callback_nrdp
|
||||
key: validate_nrdp_certs
|
||||
- section: callback_nrdp
|
||||
key: validate_certs
|
||||
type: boolean
|
||||
default: false
|
||||
aliases: [validate_nrdp_certs]
|
||||
token:
|
||||
description: Token to be allowed to push nrdp events.
|
||||
required: true
|
||||
env:
|
||||
- name: NRDP_TOKEN
|
||||
ini:
|
||||
- section: callback_nrdp
|
||||
key: token
|
||||
type: string
|
||||
secret: true
|
||||
hostname:
|
||||
description: Hostname where the passive check is linked to.
|
||||
required: true
|
||||
env:
|
||||
- name: NRDP_HOSTNAME
|
||||
ini:
|
||||
- section: callback_nrdp
|
||||
key: hostname
|
||||
type: string
|
||||
servicename:
|
||||
description: Service where the passive check is linked to.
|
||||
required: true
|
||||
env:
|
||||
- name: NRDP_SERVICENAME
|
||||
ini:
|
||||
- section: callback_nrdp
|
||||
key: servicename
|
||||
type: string
|
||||
"""
|
||||
|
||||
from urllib.parse import urlencode
|
||||
|
||||
from ansible.module_utils.common.text.converters import to_bytes
|
||||
from ansible.module_utils.urls import open_url
|
||||
from ansible.plugins.callback import CallbackBase
|
||||
|
||||
from ansible_collections.community.general.plugins.module_utils._secrets import mask_secrets
|
||||
|
||||
|
||||
class CallbackModule(CallbackBase):
|
||||
"""
|
||||
send ansible-playbook to Nagios server using nrdp protocol
|
||||
"""
|
||||
|
||||
CALLBACK_VERSION = 2.0
|
||||
CALLBACK_TYPE = "notification"
|
||||
CALLBACK_NAME = "community.general.nrdp"
|
||||
CALLBACK_NEEDS_WHITELIST = True
|
||||
|
||||
# Nagios states
|
||||
OK = 0
|
||||
WARNING = 1
|
||||
CRITICAL = 2
|
||||
UNKNOWN = 3
|
||||
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
|
||||
self.printed_playbook = False
|
||||
self.playbook_name = None
|
||||
self.play = None
|
||||
|
||||
def set_options(self, task_keys=None, var_options=None, direct=None):
|
||||
super().set_options(task_keys=task_keys, var_options=var_options, direct=direct)
|
||||
|
||||
self.url = self.get_option("url")
|
||||
if not self.url.endswith("/"):
|
||||
self.url += "/"
|
||||
self.token = self.get_option("token")
|
||||
self.hostname = self.get_option("hostname")
|
||||
self.servicename = self.get_option("servicename")
|
||||
self.validate_nrdp_certs = self.get_option("validate_certs")
|
||||
|
||||
if (self.url or self.token or self.hostname or self.servicename) is None:
|
||||
self._display.warning(
|
||||
"NRDP callback wants the NRDP_URL,"
|
||||
" NRDP_TOKEN, NRDP_HOSTNAME,"
|
||||
" NRDP_SERVICENAME"
|
||||
" environment variables'."
|
||||
" The NRDP callback plugin is disabled."
|
||||
)
|
||||
self.disabled = True
|
||||
|
||||
def _send_nrdp(self, state, msg):
|
||||
"""
|
||||
nrpd service check send XMLDATA like this:
|
||||
<?xml version='1.0'?>
|
||||
<checkresults>
|
||||
<checkresult type='service'>
|
||||
<hostname>somehost</hostname>
|
||||
<servicename>someservice</servicename>
|
||||
<state>1</state>
|
||||
<output>WARNING: Danger Will Robinson!|perfdata</output>
|
||||
</checkresult>
|
||||
</checkresults>
|
||||
"""
|
||||
xmldata = "<?xml version='1.0'?>\n"
|
||||
xmldata += "<checkresults>\n"
|
||||
xmldata += "<checkresult type='service'>\n"
|
||||
xmldata += f"<hostname>{self.hostname}</hostname>\n"
|
||||
xmldata += f"<servicename>{self.servicename}</servicename>\n"
|
||||
xmldata += f"<state>{state}</state>\n"
|
||||
xmldata += f"<output>{msg}</output>\n"
|
||||
xmldata += "</checkresult>\n"
|
||||
xmldata += "</checkresults>\n"
|
||||
|
||||
body = {"cmd": "submitcheck", "token": self.token, "XMLDATA": to_bytes(xmldata)}
|
||||
|
||||
try:
|
||||
response = open_url(self.url, data=urlencode(body), method="POST", validate_certs=self.validate_nrdp_certs)
|
||||
return response.read()
|
||||
except Exception as ex:
|
||||
self._display.warning(f"NRDP callback cannot send result {ex}")
|
||||
|
||||
def v2_playbook_on_play_start(self, play):
|
||||
"""
|
||||
Display Playbook and play start messages
|
||||
"""
|
||||
self.play = play
|
||||
|
||||
def v2_playbook_on_stats(self, stats):
|
||||
"""
|
||||
Display info about playbook statistics
|
||||
"""
|
||||
name = mask_secrets(self.play.name)
|
||||
gstats = ""
|
||||
hosts = sorted(stats.processed.keys())
|
||||
critical = warning = 0
|
||||
for host in hosts:
|
||||
stat = stats.summarize(host)
|
||||
gstats += (
|
||||
f"'{host}_ok'={stat['ok']} '{host}_changed'={stat['changed']}"
|
||||
f" '{host}_unreachable'={stat['unreachable']} '{host}_failed'={stat['failures']} "
|
||||
)
|
||||
# Critical when failed tasks or unreachable host
|
||||
critical += stat["failures"]
|
||||
critical += stat["unreachable"]
|
||||
# Warning when changed tasks
|
||||
warning += stat["changed"]
|
||||
|
||||
msg = f"{name} | {gstats}"
|
||||
if critical:
|
||||
# Send Critical
|
||||
self._send_nrdp(self.CRITICAL, msg)
|
||||
elif warning:
|
||||
# Send Warning
|
||||
self._send_nrdp(self.WARNING, msg)
|
||||
else:
|
||||
# Send OK
|
||||
self._send_nrdp(self.OK, msg)
|
||||
@@ -0,0 +1,28 @@
|
||||
# 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: Unknown (!UNKNOWN)
|
||||
name: 'null'
|
||||
type: stdout
|
||||
requirements:
|
||||
- set as main display callback
|
||||
short_description: Do not display stuff to screen
|
||||
description:
|
||||
- This callback prevents outputting events to screen.
|
||||
"""
|
||||
|
||||
from ansible.plugins.callback import CallbackBase
|
||||
|
||||
|
||||
class CallbackModule(CallbackBase):
|
||||
"""
|
||||
This callback won't print messages to stdout when new callback events are received.
|
||||
"""
|
||||
|
||||
CALLBACK_VERSION = 2.0
|
||||
CALLBACK_TYPE = "stdout"
|
||||
CALLBACK_NAME = "community.general.null"
|
||||
+126
@@ -0,0 +1,126 @@
|
||||
# Copyright (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.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 = """
|
||||
name: oneline
|
||||
type: stdout
|
||||
short_description: One-line Ansible screen output
|
||||
version_added: 13.4.0
|
||||
description:
|
||||
- This is a copy of ansible-core's P(ansible.builtin.oneline#callback) callback plugin, which has been deprecated
|
||||
in ansible-core 2.19 and will be removed from ansible-core 2.23.
|
||||
"""
|
||||
|
||||
EXAMPLES = r"""
|
||||
---
|
||||
# Enable callback in ansible.cfg:
|
||||
ansible_config: |-
|
||||
[defaults]
|
||||
stdout_callback = community.general.oneline
|
||||
"""
|
||||
|
||||
import typing as t
|
||||
|
||||
from ansible import constants as C
|
||||
from ansible.plugins.callback import CallbackBase
|
||||
from ansible.template import Templar
|
||||
|
||||
if t.TYPE_CHECKING:
|
||||
from collections.abc import Mapping
|
||||
|
||||
from ansible.executor.task_result import CallbackTaskResult
|
||||
from ansible.inventory.host import Host
|
||||
from ansible.playbook.task import Task
|
||||
|
||||
COLOR_ERROR = C.COLOR_ERROR # type: ignore[attr-defined]
|
||||
COLOR_CHANGED = C.COLOR_CHANGED # type: ignore[attr-defined]
|
||||
COLOR_OK = C.COLOR_OK # type: ignore[attr-defined]
|
||||
COLOR_UNREACHABLE = C.COLOR_UNREACHABLE # type: ignore[attr-defined]
|
||||
COLOR_SKIP = C.COLOR_SKIP # type: ignore[attr-defined]
|
||||
|
||||
|
||||
def get_result(result: CallbackTaskResult) -> Mapping[str, t.Any]:
|
||||
return result.result
|
||||
|
||||
|
||||
def get_host(result: CallbackTaskResult) -> Host:
|
||||
return result.host
|
||||
|
||||
|
||||
def get_task(result: CallbackTaskResult) -> Task:
|
||||
return result.task
|
||||
|
||||
|
||||
class CallbackModule(CallbackBase):
|
||||
"""
|
||||
This is the default callback interface, which simply prints messages
|
||||
to stdout when new callback events are received.
|
||||
"""
|
||||
|
||||
CALLBACK_VERSION = 2.0
|
||||
CALLBACK_TYPE = "stdout"
|
||||
CALLBACK_NAME = "community.general.oneline"
|
||||
|
||||
def _command_generic_msg(self, hostname: str, result: Mapping[str, t.Any], caption: str) -> str:
|
||||
stdout = result.get("stdout", "").replace("\n", "\\n").replace("\r", "\\r")
|
||||
rc = result.get("rc", -1)
|
||||
if "stderr" in result and result["stderr"]:
|
||||
stderr = result.get("stderr", "").replace("\n", "\\n").replace("\r", "\\r")
|
||||
return f"{hostname} | {caption} | rc={rc} | (stdout) {stdout} (stderr) {stderr}"
|
||||
else:
|
||||
return f"{hostname} | {caption} | rc={rc} | (stdout) {stdout}"
|
||||
|
||||
def v2_runner_on_failed(self, result: CallbackTaskResult, ignore_errors: bool = False) -> None:
|
||||
if "exception" in get_result(result):
|
||||
error_text = get_result(result)["exception"]
|
||||
if not isinstance(error_text, str):
|
||||
error_text = Templar().template(get_result(result)["exception"]) # transform to a string
|
||||
if self._display.verbosity < 3:
|
||||
# extract just the actual error message from the exception text
|
||||
error = error_text.strip().split("\n")[-1]
|
||||
msg = f"An exception occurred during task execution. To see the full traceback, use -vvv. The error was: {error}"
|
||||
else:
|
||||
msg = "An exception occurred during task execution. The full traceback is:\n" + error_text.replace(
|
||||
"\n", ""
|
||||
)
|
||||
|
||||
if get_task(result).action in C.MODULE_NO_JSON and "module_stderr" not in get_result(result):
|
||||
self._display.display(
|
||||
self._command_generic_msg(get_host(result).get_name(), get_result(result), "FAILED"),
|
||||
color=COLOR_ERROR,
|
||||
)
|
||||
else:
|
||||
self._display.display(msg, color=COLOR_ERROR)
|
||||
|
||||
hostname = get_host(result).get_name()
|
||||
msg = self._dump_results(get_result(result), indent=0).replace("\n", "")
|
||||
self._display.display(f"{hostname} | FAILED! => {msg}", color=COLOR_ERROR)
|
||||
|
||||
def v2_runner_on_ok(self, result: CallbackTaskResult) -> None:
|
||||
|
||||
if get_result(result).get("changed", False):
|
||||
color = COLOR_CHANGED
|
||||
state = "CHANGED"
|
||||
else:
|
||||
color = COLOR_OK
|
||||
state = "SUCCESS"
|
||||
|
||||
hostname = get_host(result).get_name()
|
||||
if get_task(result).action in C.MODULE_NO_JSON and "ansible_job_id" not in get_result(result):
|
||||
self._display.display(self._command_generic_msg(hostname, get_result(result), state), color=color)
|
||||
else:
|
||||
msg = self._dump_results(get_result(result), indent=0).replace("\n", "")
|
||||
self._display.display(f"{hostname} | {state} => {msg}", color=color)
|
||||
|
||||
def v2_runner_on_unreachable(self, result: CallbackTaskResult) -> None:
|
||||
hostname = get_host(result).get_name()
|
||||
msg = get_result(result).get("msg", "")
|
||||
self._display.display(f"{hostname} | UNREACHABLE!: {msg}", color=COLOR_UNREACHABLE)
|
||||
|
||||
def v2_runner_on_skipped(self, result: CallbackTaskResult) -> None:
|
||||
hostname = get_host(result).get_name()
|
||||
self._display.display(f"{hostname} | SKIPPED", color=COLOR_SKIP)
|
||||
+637
@@ -0,0 +1,637 @@
|
||||
# Copyright (c) 2021, Victor Martinez <VictorMartinezRubio@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
|
||||
|
||||
DOCUMENTATION = r"""
|
||||
author: Victor Martinez (@v1v) <VictorMartinezRubio@gmail.com>
|
||||
name: opentelemetry
|
||||
type: notification
|
||||
short_description: Create distributed traces with OpenTelemetry
|
||||
version_added: 3.7.0
|
||||
description:
|
||||
- This callback creates distributed traces for each Ansible task with OpenTelemetry.
|
||||
- You can configure the OpenTelemetry exporter and SDK with environment variables.
|
||||
- See U(https://opentelemetry-python.readthedocs.io/en/latest/exporter/otlp/otlp.html).
|
||||
- See
|
||||
U(https://opentelemetry-python.readthedocs.io/en/latest/sdk/environment_variables.html#opentelemetry-sdk-environment-variables).
|
||||
options:
|
||||
hide_task_arguments:
|
||||
default: false
|
||||
type: bool
|
||||
description:
|
||||
- Hide the arguments for a task.
|
||||
env:
|
||||
- name: ANSIBLE_OPENTELEMETRY_HIDE_TASK_ARGUMENTS
|
||||
ini:
|
||||
- section: callback_opentelemetry
|
||||
key: hide_task_arguments
|
||||
version_added: 5.3.0
|
||||
enable_from_environment:
|
||||
type: str
|
||||
description:
|
||||
- Whether to enable this callback only if the given environment variable exists and it is set to V(true).
|
||||
- This is handy when you use Configuration as Code and want to send distributed traces if running in the CI rather when
|
||||
running Ansible locally.
|
||||
- For such, it evaluates the given O(enable_from_environment) value as environment variable and if set to V(true) this
|
||||
plugin is enabled.
|
||||
env:
|
||||
- name: ANSIBLE_OPENTELEMETRY_ENABLE_FROM_ENVIRONMENT
|
||||
ini:
|
||||
- section: callback_opentelemetry
|
||||
key: enable_from_environment
|
||||
version_added: 5.3.0
|
||||
version_added: 3.8.0
|
||||
otel_service_name:
|
||||
default: ansible
|
||||
type: str
|
||||
description:
|
||||
- The service name resource attribute.
|
||||
env:
|
||||
- name: OTEL_SERVICE_NAME
|
||||
ini:
|
||||
- section: callback_opentelemetry
|
||||
key: otel_service_name
|
||||
version_added: 5.3.0
|
||||
traceparent:
|
||||
default: None
|
||||
type: str
|
||||
description:
|
||||
- The L(W3C Trace Context header traceparent,https://www.w3.org/TR/trace-context-1/#traceparent-header).
|
||||
env:
|
||||
- name: TRACEPARENT
|
||||
disable_logs:
|
||||
default: false
|
||||
type: bool
|
||||
description:
|
||||
- Disable sending logs.
|
||||
env:
|
||||
- name: ANSIBLE_OPENTELEMETRY_DISABLE_LOGS
|
||||
ini:
|
||||
- section: callback_opentelemetry
|
||||
key: disable_logs
|
||||
version_added: 5.8.0
|
||||
disable_attributes_in_logs:
|
||||
default: false
|
||||
type: bool
|
||||
description:
|
||||
- Disable populating span attributes to the logs.
|
||||
env:
|
||||
- name: ANSIBLE_OPENTELEMETRY_DISABLE_ATTRIBUTES_IN_LOGS
|
||||
ini:
|
||||
- section: callback_opentelemetry
|
||||
key: disable_attributes_in_logs
|
||||
version_added: 7.1.0
|
||||
store_spans_in_file:
|
||||
type: str
|
||||
description:
|
||||
- It stores the exported spans in the given file.
|
||||
env:
|
||||
- name: ANSIBLE_OPENTELEMETRY_STORE_SPANS_IN_FILE
|
||||
ini:
|
||||
- section: callback_opentelemetry
|
||||
key: store_spans_in_file
|
||||
version_added: 9.0.0
|
||||
otel_exporter_otlp_traces_protocol:
|
||||
type: str
|
||||
description:
|
||||
- E(OTEL_EXPORTER_OTLP_TRACES_PROTOCOL) represents the transport protocol for spans.
|
||||
- See
|
||||
U(https://opentelemetry-python.readthedocs.io/en/latest/sdk/environment_variables.html#envvar-OTEL_EXPORTER_OTLP_TRACES_PROTOCOL).
|
||||
default: grpc
|
||||
choices:
|
||||
- grpc
|
||||
- http/protobuf
|
||||
env:
|
||||
- name: OTEL_EXPORTER_OTLP_TRACES_PROTOCOL
|
||||
ini:
|
||||
- section: callback_opentelemetry
|
||||
key: otel_exporter_otlp_traces_protocol
|
||||
version_added: 9.0.0
|
||||
requirements:
|
||||
- opentelemetry-api (Python library)
|
||||
- opentelemetry-exporter-otlp (Python library)
|
||||
- opentelemetry-sdk (Python library)
|
||||
"""
|
||||
|
||||
|
||||
EXAMPLES = r"""
|
||||
examples: |-
|
||||
Enable the plugin in ansible.cfg:
|
||||
[defaults]
|
||||
callbacks_enabled = community.general.opentelemetry
|
||||
[callback_opentelemetry]
|
||||
enable_from_environment = ANSIBLE_OPENTELEMETRY_ENABLED
|
||||
|
||||
Set the environment variable:
|
||||
export OTEL_EXPORTER_OTLP_ENDPOINT=<your endpoint (OTLP/HTTP)>
|
||||
export OTEL_EXPORTER_OTLP_HEADERS="authorization=Bearer your_otel_token"
|
||||
export OTEL_SERVICE_NAME=your_service_name
|
||||
export ANSIBLE_OPENTELEMETRY_ENABLED=true
|
||||
"""
|
||||
|
||||
import getpass
|
||||
import json
|
||||
import os
|
||||
import socket
|
||||
import uuid
|
||||
from collections import OrderedDict
|
||||
from os.path import basename
|
||||
from time import time_ns
|
||||
from urllib.parse import urlparse
|
||||
|
||||
from ansible.errors import AnsibleError
|
||||
from ansible.module_utils.ansible_release import __version__ as ansible_version
|
||||
from ansible.plugins.callback import CallbackBase
|
||||
|
||||
from ansible_collections.community.general.plugins.module_utils._secrets import mask_secret_values, mask_secrets
|
||||
|
||||
OTEL_LIBRARY_IMPORT_ERROR: ImportError | None
|
||||
try:
|
||||
from opentelemetry import trace
|
||||
from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter as GRPCOTLPSpanExporter
|
||||
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter as HTTPOTLPSpanExporter
|
||||
from opentelemetry.sdk.resources import SERVICE_NAME, Resource
|
||||
from opentelemetry.sdk.trace import TracerProvider
|
||||
from opentelemetry.sdk.trace.export import BatchSpanProcessor, SimpleSpanProcessor
|
||||
from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter
|
||||
from opentelemetry.trace import SpanKind
|
||||
from opentelemetry.trace.propagation.tracecontext import TraceContextTextMapPropagator
|
||||
from opentelemetry.trace.status import Status, StatusCode
|
||||
except ImportError as imp_exc:
|
||||
OTEL_LIBRARY_IMPORT_ERROR = imp_exc
|
||||
else:
|
||||
OTEL_LIBRARY_IMPORT_ERROR = None
|
||||
|
||||
|
||||
class TaskData:
|
||||
"""
|
||||
Data about an individual task.
|
||||
"""
|
||||
|
||||
def __init__(self, uuid: str, name: str, path: str, play: str, action: str, args) -> None:
|
||||
self.uuid = uuid
|
||||
self.name = name
|
||||
self.path = path
|
||||
self.play = play
|
||||
self.host_data: dict[str, HostData] = OrderedDict()
|
||||
self.start = time_ns()
|
||||
self.action = action
|
||||
self.args = args
|
||||
|
||||
def add_host(self, host: HostData) -> None:
|
||||
if host.uuid in self.host_data:
|
||||
if host.status == "included":
|
||||
# concatenate task include output from multiple items
|
||||
host.result = f"{self.host_data[host.uuid].result}\n{host.result}"
|
||||
else:
|
||||
self.host_data[host.uuid].update(host.status, host.result, host.dump)
|
||||
return
|
||||
|
||||
self.host_data[host.uuid] = host
|
||||
|
||||
|
||||
class HostData:
|
||||
"""
|
||||
Data about an individual host.
|
||||
"""
|
||||
|
||||
def __init__(self, uuid: str, name: str, status: str, result=None, dump: str = "") -> None:
|
||||
self.uuid = uuid
|
||||
self.name = name
|
||||
self.status = status
|
||||
self.result = result
|
||||
self.dump = dump
|
||||
self.finish: int | None = None
|
||||
self.start = time_ns()
|
||||
|
||||
def update(self, status: str, result, dump: str) -> None:
|
||||
self.status = status
|
||||
self.result = result
|
||||
self.dump = dump
|
||||
self.finish = time_ns()
|
||||
|
||||
|
||||
class OpenTelemetrySource:
|
||||
def __init__(self, display) -> None:
|
||||
self.ansible_playbook = ""
|
||||
self.session = str(uuid.uuid4())
|
||||
self.host = socket.gethostname()
|
||||
try:
|
||||
self.ip_address: str | None = socket.gethostbyname(socket.gethostname())
|
||||
except Exception:
|
||||
self.ip_address = None
|
||||
self.user = getpass.getuser()
|
||||
|
||||
self._display = display
|
||||
|
||||
def traceparent_context(self, traceparent: bool):
|
||||
carrier = dict()
|
||||
carrier["traceparent"] = traceparent
|
||||
return TraceContextTextMapPropagator().extract(carrier=carrier)
|
||||
|
||||
def start_task(
|
||||
self, tasks_data: dict[str, TaskData], hide_task_arguments: bool, play_name: str, task, host
|
||||
) -> None:
|
||||
"""record the start of a task for one or more hosts"""
|
||||
|
||||
uuid = task._uuid
|
||||
|
||||
if uuid in tasks_data:
|
||||
tasks_data[uuid].add_host(HostData(host._uuid, host.name, "started"))
|
||||
return
|
||||
|
||||
name = task.get_name().strip()
|
||||
path = task.get_path()
|
||||
action = task.action
|
||||
args = None
|
||||
|
||||
if not task.no_log and not hide_task_arguments:
|
||||
args = task.args
|
||||
|
||||
tasks_data[uuid] = TaskData(uuid, name, path, play_name, action, args)
|
||||
tasks_data[uuid].add_host(HostData(host._uuid, host.name, "started"))
|
||||
|
||||
def finish_task(self, tasks_data: dict[str, TaskData], status: str, result, dump) -> None:
|
||||
"""record the results of a task for a single host"""
|
||||
|
||||
task_uuid = result._task._uuid
|
||||
|
||||
if hasattr(result, "_host") and result._host is not None:
|
||||
host_uuid = result._host._uuid
|
||||
host_name = result._host.name
|
||||
else:
|
||||
host_uuid = "include"
|
||||
host_name = "include"
|
||||
|
||||
task = tasks_data[task_uuid]
|
||||
|
||||
task.add_host(HostData(host_uuid, host_name, status, result, dump))
|
||||
|
||||
def generate_distributed_traces(
|
||||
self,
|
||||
otel_service_name: str,
|
||||
ansible_playbook: str,
|
||||
tasks_data: dict[str, TaskData],
|
||||
status: Status,
|
||||
traceparent: bool,
|
||||
disable_logs: bool,
|
||||
disable_attributes_in_logs: bool,
|
||||
otel_exporter_otlp_traces_protocol: str,
|
||||
store_spans_in_file: str | None,
|
||||
) -> InMemorySpanExporter | GRPCOTLPSpanExporter | HTTPOTLPSpanExporter:
|
||||
"""generate distributed traces from the collected TaskData and HostData"""
|
||||
|
||||
tasks = []
|
||||
parent_start_time = None
|
||||
for task in tasks_data.values():
|
||||
if parent_start_time is None:
|
||||
parent_start_time = task.start
|
||||
tasks.append(task)
|
||||
|
||||
trace.set_tracer_provider(TracerProvider(resource=Resource.create({SERVICE_NAME: otel_service_name})))
|
||||
|
||||
otel_exporter = None
|
||||
if store_spans_in_file:
|
||||
otel_exporter = InMemorySpanExporter()
|
||||
processor = SimpleSpanProcessor(otel_exporter)
|
||||
else:
|
||||
if otel_exporter_otlp_traces_protocol == "grpc":
|
||||
otel_exporter = GRPCOTLPSpanExporter()
|
||||
else:
|
||||
otel_exporter = HTTPOTLPSpanExporter()
|
||||
processor = BatchSpanProcessor(otel_exporter)
|
||||
|
||||
trace.get_tracer_provider().add_span_processor(processor)
|
||||
|
||||
tracer = trace.get_tracer(__name__)
|
||||
|
||||
with tracer.start_as_current_span(
|
||||
ansible_playbook,
|
||||
context=self.traceparent_context(traceparent),
|
||||
start_time=parent_start_time,
|
||||
kind=SpanKind.SERVER,
|
||||
) as parent:
|
||||
parent.set_status(status)
|
||||
# Populate trace metadata attributes
|
||||
parent.set_attribute("ansible.version", ansible_version)
|
||||
parent.set_attribute("ansible.session", self.session)
|
||||
parent.set_attribute("ansible.host.name", self.host)
|
||||
if self.ip_address is not None:
|
||||
parent.set_attribute("ansible.host.ip", self.ip_address)
|
||||
parent.set_attribute("ansible.host.user", self.user)
|
||||
for task in tasks:
|
||||
for host_data in task.host_data.values():
|
||||
start = host_data.start or task.start
|
||||
with tracer.start_as_current_span(task.name, start_time=start, end_on_exit=False) as span:
|
||||
self.update_span_data(task, host_data, span, disable_logs, disable_attributes_in_logs)
|
||||
|
||||
return otel_exporter
|
||||
|
||||
def update_span_data(
|
||||
self, task_data: TaskData, host_data: HostData, span, disable_logs: bool, disable_attributes_in_logs: bool
|
||||
) -> None:
|
||||
"""update the span with the given TaskData and HostData"""
|
||||
|
||||
name = f"[{host_data.name}] {mask_secrets(task_data.play)}: {mask_secrets(task_data.name)}"
|
||||
|
||||
message = "success"
|
||||
res = {}
|
||||
rc = 0
|
||||
status = Status(status_code=StatusCode.OK)
|
||||
if host_data.status != "included":
|
||||
# Support loops
|
||||
enriched_error_message = None
|
||||
if host_data.result and "results" in host_data.result._result:
|
||||
if host_data.status == "failed":
|
||||
message = self.get_error_message_from_results(host_data.result._result["results"], task_data.action)
|
||||
enriched_error_message = self.enrich_error_message_from_results(
|
||||
host_data.result._result["results"], task_data.action
|
||||
)
|
||||
elif host_data.result:
|
||||
res = host_data.result._result
|
||||
rc = res.get("rc", 0)
|
||||
if host_data.status == "failed":
|
||||
message = self.get_error_message(res)
|
||||
enriched_error_message = self.enrich_error_message(res)
|
||||
|
||||
if host_data.status == "failed":
|
||||
status = Status(status_code=StatusCode.ERROR, description=message)
|
||||
# Record an exception with the task message
|
||||
span.record_exception(BaseException(enriched_error_message))
|
||||
elif host_data.status == "skipped":
|
||||
message = res["skip_reason"] if "skip_reason" in res else "skipped"
|
||||
status = Status(status_code=StatusCode.UNSET)
|
||||
elif host_data.status == "ignored":
|
||||
status = Status(status_code=StatusCode.UNSET)
|
||||
|
||||
span.set_status(status)
|
||||
|
||||
# Create the span and log attributes
|
||||
attributes = {
|
||||
"ansible.task.module": task_data.action,
|
||||
"ansible.task.message": message,
|
||||
"ansible.task.name": name,
|
||||
"ansible.task.result": rc,
|
||||
"ansible.task.host.name": host_data.name,
|
||||
"ansible.task.host.status": host_data.status,
|
||||
}
|
||||
if isinstance(task_data.args, dict) and "gather_facts" not in task_data.action:
|
||||
names = tuple(self.transform_ansible_unicode_to_str(mask_secrets(k)) for k in task_data.args.keys())
|
||||
values = tuple(
|
||||
self.transform_ansible_unicode_to_str(mask_secret_values(k)) for k in task_data.args.values()
|
||||
)
|
||||
attributes[("ansible.task.args.name")] = names
|
||||
attributes[("ansible.task.args.value")] = values
|
||||
|
||||
self.set_span_attributes(span, attributes)
|
||||
|
||||
# This will allow to enrich the service map
|
||||
self.add_attributes_for_service_map_if_possible(span, task_data)
|
||||
# Send logs
|
||||
if not disable_logs:
|
||||
# This will avoid populating span attributes to the logs
|
||||
span.add_event(host_data.dump, attributes={} if disable_attributes_in_logs else attributes)
|
||||
# Close span always
|
||||
span.end(end_time=host_data.finish)
|
||||
|
||||
def set_span_attributes(self, span, attributes) -> None:
|
||||
"""update the span attributes with the given attributes if not None"""
|
||||
|
||||
if span is None and self._display is not None:
|
||||
self._display.warning("span object is None. Please double check if that is expected.")
|
||||
else:
|
||||
if attributes is not None:
|
||||
span.set_attributes(attributes)
|
||||
|
||||
def add_attributes_for_service_map_if_possible(self, span, task_data: TaskData) -> None:
|
||||
"""Update the span attributes with the service that the task interacted with, if possible."""
|
||||
|
||||
redacted_url = mask_secret_values(self.parse_and_redact_url_if_possible(task_data.args))
|
||||
if redacted_url:
|
||||
span.set_attribute("http.url", redacted_url.geturl())
|
||||
|
||||
@staticmethod
|
||||
def parse_and_redact_url_if_possible(args):
|
||||
"""Parse and redact the url, if possible."""
|
||||
|
||||
try:
|
||||
parsed_url = urlparse(OpenTelemetrySource.url_from_args(args))
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
if OpenTelemetrySource.is_valid_url(parsed_url):
|
||||
return OpenTelemetrySource.redact_user_password(parsed_url)
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def url_from_args(args) -> str:
|
||||
# the order matters
|
||||
url_args = (
|
||||
"url",
|
||||
"api_url",
|
||||
"baseurl",
|
||||
"repo",
|
||||
"server_url",
|
||||
"chart_repo_url",
|
||||
"registry_url",
|
||||
"endpoint",
|
||||
"uri",
|
||||
"updates_url",
|
||||
)
|
||||
for arg in url_args:
|
||||
if args is not None and args.get(arg):
|
||||
return args.get(arg)
|
||||
return ""
|
||||
|
||||
@staticmethod
|
||||
def redact_user_password(url):
|
||||
return url._replace(netloc=url.hostname) if url.password else url
|
||||
|
||||
@staticmethod
|
||||
def is_valid_url(url):
|
||||
if all([url.scheme, url.netloc, url.hostname]):
|
||||
return "{{" not in url.hostname
|
||||
return False
|
||||
|
||||
@staticmethod
|
||||
def transform_ansible_unicode_to_str(value):
|
||||
parsed_url = urlparse(str(value))
|
||||
if OpenTelemetrySource.is_valid_url(parsed_url):
|
||||
return OpenTelemetrySource.redact_user_password(parsed_url).geturl()
|
||||
return str(value)
|
||||
|
||||
@staticmethod
|
||||
def get_error_message(result):
|
||||
if result.get("exception") is not None:
|
||||
return OpenTelemetrySource._last_line(result["exception"])
|
||||
return result.get("msg", "failed")
|
||||
|
||||
@staticmethod
|
||||
def get_error_message_from_results(results, action):
|
||||
for result in results:
|
||||
if result.get("failed", False):
|
||||
return f"{action}({result.get('item', 'none')}) - {OpenTelemetrySource.get_error_message(result)}"
|
||||
|
||||
@staticmethod
|
||||
def _last_line(text):
|
||||
lines = text.strip().split("\n")
|
||||
return lines[-1]
|
||||
|
||||
@staticmethod
|
||||
def enrich_error_message(result):
|
||||
message = result.get("msg", "failed")
|
||||
exception = result.get("exception")
|
||||
stderr = result.get("stderr")
|
||||
return f'message: "{message}"\nexception: "{exception}"\nstderr: "{stderr}"'
|
||||
|
||||
@staticmethod
|
||||
def enrich_error_message_from_results(results, action):
|
||||
message = ""
|
||||
for result in results:
|
||||
if result.get("failed", False):
|
||||
message = f"{action}({result.get('item', 'none')}) - {OpenTelemetrySource.enrich_error_message(result)}\n{message}"
|
||||
return message
|
||||
|
||||
|
||||
class CallbackModule(CallbackBase):
|
||||
"""
|
||||
This callback creates distributed traces.
|
||||
"""
|
||||
|
||||
CALLBACK_VERSION = 2.0
|
||||
CALLBACK_TYPE = "notification"
|
||||
CALLBACK_NAME = "community.general.opentelemetry"
|
||||
CALLBACK_NEEDS_ENABLED = True
|
||||
|
||||
def __init__(self, display=None) -> None:
|
||||
super().__init__(display=display)
|
||||
self.hide_task_arguments = False
|
||||
self.disable_attributes_in_logs = False
|
||||
self.disable_logs = False
|
||||
self.otel_service_name = ""
|
||||
self.ansible_playbook: str | None = None
|
||||
self.play_name: str | None = None
|
||||
self.errors = 0
|
||||
self.disabled = False
|
||||
self.traceparent = False
|
||||
self.store_spans_in_file: str | None = None
|
||||
self.otel_exporter_otlp_traces_protocol = ""
|
||||
|
||||
if OTEL_LIBRARY_IMPORT_ERROR:
|
||||
raise AnsibleError(
|
||||
"The `opentelemetry-api`, `opentelemetry-exporter-otlp` or `opentelemetry-sdk` must be installed to use this plugin"
|
||||
) from OTEL_LIBRARY_IMPORT_ERROR
|
||||
|
||||
self.tasks_data: dict[str, TaskData] = OrderedDict()
|
||||
|
||||
self.opentelemetry = OpenTelemetrySource(display=self._display)
|
||||
|
||||
def set_options(self, task_keys=None, var_options=None, direct=None):
|
||||
super().set_options(task_keys=task_keys, var_options=var_options, direct=direct)
|
||||
|
||||
environment_variable = self.get_option("enable_from_environment")
|
||||
if environment_variable is not None and os.environ.get(environment_variable, "false").lower() != "true":
|
||||
self.disabled = True
|
||||
self._display.warning(
|
||||
f"The `enable_from_environment` option has been set and {environment_variable} is not enabled. Disabling the `opentelemetry` callback plugin."
|
||||
)
|
||||
|
||||
self.hide_task_arguments = self.get_option("hide_task_arguments")
|
||||
|
||||
self.disable_attributes_in_logs = self.get_option("disable_attributes_in_logs")
|
||||
|
||||
self.disable_logs = self.get_option("disable_logs")
|
||||
|
||||
self.store_spans_in_file = self.get_option("store_spans_in_file")
|
||||
|
||||
self.otel_service_name = self.get_option("otel_service_name") or "ansible"
|
||||
|
||||
# See https://github.com/open-telemetry/opentelemetry-specification/issues/740
|
||||
self.traceparent = self.get_option("traceparent")
|
||||
|
||||
self.otel_exporter_otlp_traces_protocol = self.get_option("otel_exporter_otlp_traces_protocol")
|
||||
|
||||
def dump_results(self, task, result):
|
||||
"""dump the results if disable_logs is not enabled"""
|
||||
if self.disable_logs:
|
||||
return ""
|
||||
# ansible.builtin.uri contains the response in the json field
|
||||
save = dict(result._result)
|
||||
|
||||
if "json" in save and task.action in ("ansible.builtin.uri", "ansible.legacy.uri", "uri"):
|
||||
save.pop("json")
|
||||
# ansible.builtin.slurp contains the response in the content field
|
||||
if "content" in save and task.action in ("ansible.builtin.slurp", "ansible.legacy.slurp", "slurp"):
|
||||
save.pop("content")
|
||||
return self._dump_results(save)
|
||||
|
||||
def v2_playbook_on_start(self, playbook):
|
||||
self.ansible_playbook = basename(playbook._file_name)
|
||||
|
||||
def v2_playbook_on_play_start(self, play):
|
||||
self.play_name = play.get_name()
|
||||
|
||||
def v2_runner_on_start(self, host, task):
|
||||
self.opentelemetry.start_task(self.tasks_data, self.hide_task_arguments, self.play_name, task, host)
|
||||
|
||||
def v2_runner_on_failed(self, result, ignore_errors=False):
|
||||
if ignore_errors:
|
||||
status = "ignored"
|
||||
else:
|
||||
status = "failed"
|
||||
self.errors += 1
|
||||
|
||||
self.opentelemetry.finish_task(
|
||||
self.tasks_data, status, result, self.dump_results(self.tasks_data[result._task._uuid], result)
|
||||
)
|
||||
|
||||
def v2_runner_on_ok(self, result):
|
||||
self.opentelemetry.finish_task(
|
||||
self.tasks_data, "ok", result, self.dump_results(self.tasks_data[result._task._uuid], result)
|
||||
)
|
||||
|
||||
def v2_runner_on_skipped(self, result):
|
||||
if result._task._uuid not in self.tasks_data:
|
||||
# meta tasks skipped by a conditional do not trigger v2_runner_on_start
|
||||
self.opentelemetry.start_task(
|
||||
self.tasks_data, self.hide_task_arguments, self.play_name, result._task, result._host
|
||||
)
|
||||
self.opentelemetry.finish_task(
|
||||
self.tasks_data, "skipped", result, self.dump_results(self.tasks_data[result._task._uuid], result)
|
||||
)
|
||||
|
||||
def v2_runner_on_unreachable(self, result):
|
||||
self.errors += 1
|
||||
self.opentelemetry.finish_task(
|
||||
self.tasks_data, "failed", result, self.dump_results(self.tasks_data[result._task._uuid], result)
|
||||
)
|
||||
|
||||
def v2_playbook_on_include(self, included_file):
|
||||
self.opentelemetry.finish_task(self.tasks_data, "included", included_file, "")
|
||||
|
||||
def v2_playbook_on_stats(self, stats):
|
||||
if self.errors == 0:
|
||||
status = Status(status_code=StatusCode.OK)
|
||||
else:
|
||||
status = Status(status_code=StatusCode.ERROR)
|
||||
otel_exporter = self.opentelemetry.generate_distributed_traces(
|
||||
self.otel_service_name,
|
||||
self.ansible_playbook,
|
||||
self.tasks_data,
|
||||
status,
|
||||
self.traceparent,
|
||||
self.disable_logs,
|
||||
self.disable_attributes_in_logs,
|
||||
self.otel_exporter_otlp_traces_protocol,
|
||||
self.store_spans_in_file,
|
||||
)
|
||||
|
||||
if self.store_spans_in_file:
|
||||
spans = [json.loads(span.to_json()) for span in otel_exporter.get_finished_spans()]
|
||||
with open(self.store_spans_in_file, "w", encoding="utf-8") as output:
|
||||
json.dump({"spans": spans}, output, indent=4)
|
||||
|
||||
def v2_runner_on_async_failed(self, result, **kwargs):
|
||||
self.errors += 1
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
# Copyright (c) 2025, Max Mitschke <maxmitschke@fastmail.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
|
||||
|
||||
DOCUMENTATION = r"""
|
||||
name: print_task
|
||||
type: aggregate
|
||||
short_description: Prints playbook task snippet to job output
|
||||
description:
|
||||
- This plugin prints the currently executing playbook task to the job output.
|
||||
version_added: 10.7.0
|
||||
requirements:
|
||||
- enable in configuration
|
||||
"""
|
||||
|
||||
EXAMPLES = r"""
|
||||
ansible.cfg: |-
|
||||
# Enable plugin
|
||||
[defaults]
|
||||
callbacks_enabled=community.general.print_task
|
||||
"""
|
||||
|
||||
from yaml import dump, load
|
||||
|
||||
try:
|
||||
from yaml import CSafeDumper as SafeDumper
|
||||
from yaml import CSafeLoader as SafeLoader
|
||||
except ImportError:
|
||||
from yaml import SafeDumper, SafeLoader # type: ignore
|
||||
|
||||
from ansible.plugins.callback import CallbackBase
|
||||
|
||||
|
||||
class CallbackModule(CallbackBase):
|
||||
"""
|
||||
This callback module tells you how long your plays ran for.
|
||||
"""
|
||||
|
||||
CALLBACK_VERSION = 2.0
|
||||
CALLBACK_TYPE = "aggregate"
|
||||
CALLBACK_NAME = "community.general.print_task"
|
||||
|
||||
CALLBACK_NEEDS_ENABLED = True
|
||||
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self._printed_message = False
|
||||
|
||||
def _print_task(self, task):
|
||||
if hasattr(task, "_ds"):
|
||||
task_snippet = load(str([task._ds.copy()]), Loader=SafeLoader)
|
||||
task_yaml = dump(task_snippet, sort_keys=False, Dumper=SafeDumper)
|
||||
self._display.display(f"\n{task_yaml}\n")
|
||||
self._printed_message = True
|
||||
|
||||
def v2_playbook_on_task_start(self, task, is_conditional):
|
||||
self._printed_message = False
|
||||
|
||||
def v2_runner_on_start(self, host, task):
|
||||
if not self._printed_message:
|
||||
self._print_task(task)
|
||||
@@ -0,0 +1,120 @@
|
||||
# Copyright (c) 2012, Michael DeHaan, <michael.dehaan@gmail.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: Unknown (!UNKNOWN)
|
||||
name: say
|
||||
type: notification
|
||||
requirements:
|
||||
- whitelisting in configuration
|
||||
- the C(/usr/bin/say) command line program (standard on macOS) or C(espeak) command line program
|
||||
short_description: Notify using software speech synthesizer
|
||||
description:
|
||||
- This plugin uses C(say) or C(espeak) to "speak" about play events.
|
||||
"""
|
||||
|
||||
import os
|
||||
import platform
|
||||
import subprocess
|
||||
|
||||
from ansible.module_utils.common.process import get_bin_path
|
||||
from ansible.plugins.callback import CallbackBase
|
||||
|
||||
from ansible_collections.community.general.plugins.module_utils._secrets import mask_secrets
|
||||
|
||||
|
||||
class CallbackModule(CallbackBase):
|
||||
"""
|
||||
makes Ansible much more exciting.
|
||||
"""
|
||||
|
||||
CALLBACK_VERSION = 2.0
|
||||
CALLBACK_TYPE = "notification"
|
||||
CALLBACK_NAME = "community.general.say"
|
||||
CALLBACK_NEEDS_WHITELIST = True
|
||||
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
|
||||
self.FAILED_VOICE = None
|
||||
self.REGULAR_VOICE = None
|
||||
self.HAPPY_VOICE = None
|
||||
self.LASER_VOICE = None
|
||||
|
||||
try:
|
||||
self.synthesizer = get_bin_path("say")
|
||||
if platform.system() != "Darwin":
|
||||
# 'say' binary available, it might be GNUstep tool which doesn't support 'voice' parameter
|
||||
self._display.warning(
|
||||
f"'say' executable found but system is '{platform.system()}': ignoring voice parameter"
|
||||
)
|
||||
else:
|
||||
self.FAILED_VOICE = "Zarvox"
|
||||
self.REGULAR_VOICE = "Trinoids"
|
||||
self.HAPPY_VOICE = "Cellos"
|
||||
self.LASER_VOICE = "Princess"
|
||||
except ValueError:
|
||||
try:
|
||||
self.synthesizer = get_bin_path("espeak")
|
||||
self.FAILED_VOICE = "klatt"
|
||||
self.HAPPY_VOICE = "f5"
|
||||
self.LASER_VOICE = "whisper"
|
||||
except ValueError:
|
||||
self.synthesizer = None
|
||||
|
||||
# plugin disable itself if say is not present
|
||||
# ansible will not call any callback if disabled is set to True
|
||||
if not self.synthesizer:
|
||||
self.disabled = True
|
||||
self._display.warning(
|
||||
f"Unable to find either 'say' or 'espeak' executable, plugin {os.path.basename(__file__)} disabled"
|
||||
)
|
||||
|
||||
def say(self, msg, voice):
|
||||
cmd = [self.synthesizer, mask_secrets(msg)]
|
||||
if voice:
|
||||
cmd.extend(("-v", voice))
|
||||
subprocess.call(cmd)
|
||||
|
||||
def runner_on_failed(self, host, res, ignore_errors=False):
|
||||
self.say(f"Failure on host {host}", self.FAILED_VOICE)
|
||||
|
||||
def runner_on_ok(self, host, res):
|
||||
self.say("pew", self.LASER_VOICE)
|
||||
|
||||
def runner_on_skipped(self, host, item=None):
|
||||
self.say("pew", self.LASER_VOICE)
|
||||
|
||||
def runner_on_unreachable(self, host, res):
|
||||
self.say(f"Failure on host {host}", self.FAILED_VOICE)
|
||||
|
||||
def runner_on_async_ok(self, host, res, jid):
|
||||
self.say("pew", self.LASER_VOICE)
|
||||
|
||||
def runner_on_async_failed(self, host, res, jid):
|
||||
self.say(f"Failure on host {host}", self.FAILED_VOICE)
|
||||
|
||||
def playbook_on_start(self):
|
||||
self.say("Running Playbook", self.REGULAR_VOICE)
|
||||
|
||||
def playbook_on_notify(self, host, handler):
|
||||
self.say("pew", self.LASER_VOICE)
|
||||
|
||||
def playbook_on_task_start(self, name, is_conditional):
|
||||
if not is_conditional:
|
||||
self.say(f"Starting task: {name}", self.REGULAR_VOICE)
|
||||
else:
|
||||
self.say(f"Notifying task: {name}", self.REGULAR_VOICE)
|
||||
|
||||
def playbook_on_setup(self):
|
||||
self.say("Gathering facts", self.REGULAR_VOICE)
|
||||
|
||||
def playbook_on_play_start(self, name):
|
||||
self.say(f"Starting play: {name}", self.HAPPY_VOICE)
|
||||
|
||||
def playbook_on_stats(self, stats):
|
||||
self.say("Play complete", self.HAPPY_VOICE)
|
||||
+277
@@ -0,0 +1,277 @@
|
||||
# Copyright (c) Fastly, inc 2016
|
||||
# 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: Unknown (!UNKNOWN)
|
||||
name: selective
|
||||
type: stdout
|
||||
requirements:
|
||||
- set as main display callback
|
||||
short_description: Only print certain tasks
|
||||
description:
|
||||
- This callback only prints tasks that have been tagged with C(print_action) or that have failed. This allows operators
|
||||
to focus on the tasks that provide value only.
|
||||
- Tasks that are not printed are placed with a C(.).
|
||||
- If you increase verbosity all tasks are printed.
|
||||
options:
|
||||
nocolor:
|
||||
default: false
|
||||
description: This setting allows suppressing colorizing output.
|
||||
env:
|
||||
- name: ANSIBLE_NOCOLOR
|
||||
- name: ANSIBLE_SELECTIVE_DONT_COLORIZE
|
||||
ini:
|
||||
- section: defaults
|
||||
key: nocolor
|
||||
type: boolean
|
||||
"""
|
||||
|
||||
EXAMPLES = r"""
|
||||
- ansible.builtin.debug: msg="This will not be printed"
|
||||
- ansible.builtin.debug: msg="But this will"
|
||||
tags: [print_action]
|
||||
"""
|
||||
|
||||
import difflib
|
||||
|
||||
from ansible import constants as C
|
||||
from ansible.module_utils.common.text.converters import to_text
|
||||
from ansible.plugins.callback import CallbackBase
|
||||
|
||||
COLORS = {
|
||||
"normal": "\033[0m",
|
||||
"ok": f"\x1b[{C.COLOR_CODES[C.COLOR_OK]}m", # type: ignore
|
||||
"bold": "\033[1m",
|
||||
"not_so_bold": "\033[1m\033[34m",
|
||||
"changed": f"\x1b[{C.COLOR_CODES[C.COLOR_CHANGED]}m", # type: ignore
|
||||
"failed": f"\x1b[{C.COLOR_CODES[C.COLOR_ERROR]}m", # type: ignore
|
||||
"endc": "\033[0m",
|
||||
"skipped": f"\x1b[{C.COLOR_CODES[C.COLOR_SKIP]}m", # type: ignore
|
||||
}
|
||||
|
||||
|
||||
def dict_diff(prv, nxt):
|
||||
"""Return a dict of keys that differ with another config object."""
|
||||
keys = set(list(prv.keys()) + list(nxt.keys()))
|
||||
result = {}
|
||||
for k in keys:
|
||||
if prv.get(k) != nxt.get(k):
|
||||
result[k] = (prv.get(k), nxt.get(k))
|
||||
return result
|
||||
|
||||
|
||||
class CallbackModule(CallbackBase):
|
||||
"""selective.py callback plugin."""
|
||||
|
||||
CALLBACK_VERSION = 2.0
|
||||
CALLBACK_TYPE = "stdout"
|
||||
CALLBACK_NAME = "community.general.selective"
|
||||
|
||||
def __init__(self, display=None):
|
||||
"""selective.py callback plugin."""
|
||||
super().__init__(display)
|
||||
self.last_skipped = False
|
||||
self.last_task_name = None
|
||||
self.printed_last_task = False
|
||||
self.dont_colorize = False
|
||||
|
||||
def set_options(self, task_keys=None, var_options=None, direct=None):
|
||||
super().set_options(task_keys=task_keys, var_options=var_options, direct=direct)
|
||||
|
||||
self.dont_colorize = self.get_option("nocolor")
|
||||
|
||||
def colorize(self, msg, color):
|
||||
"""Given a string add necessary codes to format the string."""
|
||||
if self.dont_colorize:
|
||||
return msg
|
||||
else:
|
||||
return f"{COLORS[color]}{msg}{COLORS['endc']}"
|
||||
|
||||
def _print_task(self, task_name=None):
|
||||
if task_name is None:
|
||||
task_name = self.last_task_name
|
||||
|
||||
if not self.printed_last_task:
|
||||
self.printed_last_task = True
|
||||
line_length = 120
|
||||
if self.last_skipped:
|
||||
self._display.display("")
|
||||
line = f"# {task_name} "
|
||||
msg = self.colorize(f"{line}{'*' * (line_length - len(line))}", "bold")
|
||||
self._display.display(msg)
|
||||
|
||||
def _indent_text(self, text, indent_level):
|
||||
lines = text.splitlines()
|
||||
result_lines = []
|
||||
for l in lines:
|
||||
result_lines.append(f"{' ' * indent_level}{l}")
|
||||
return "\n".join(result_lines)
|
||||
|
||||
def _print_diff(self, diff, indent_level):
|
||||
if isinstance(diff, dict):
|
||||
try:
|
||||
diff = "\n".join(
|
||||
difflib.unified_diff(
|
||||
diff["before"].splitlines(),
|
||||
diff["after"].splitlines(),
|
||||
fromfile=diff.get("before_header", "new_file"),
|
||||
tofile=diff["after_header"],
|
||||
)
|
||||
)
|
||||
except AttributeError:
|
||||
diff = dict_diff(diff["before"], diff["after"])
|
||||
if diff:
|
||||
diff = self.colorize(str(diff), "changed")
|
||||
self._display.display(self._indent_text(diff, indent_level + 4))
|
||||
|
||||
def _print_host_or_item(self, host_or_item, changed, msg, diff, is_host, error, stdout, stderr):
|
||||
if is_host:
|
||||
indent_level = 0
|
||||
name = self.colorize(host_or_item.name, "not_so_bold")
|
||||
else:
|
||||
indent_level = 4
|
||||
if isinstance(host_or_item, dict):
|
||||
if "key" in host_or_item.keys():
|
||||
host_or_item = host_or_item["key"]
|
||||
name = self.colorize(to_text(host_or_item), "bold")
|
||||
|
||||
if error:
|
||||
color = "failed"
|
||||
change_string = self.colorize("FAILED!!!", color)
|
||||
else:
|
||||
color = "changed" if changed else "ok"
|
||||
change_string = self.colorize(f"changed={changed}", color)
|
||||
|
||||
msg = self.colorize(msg, color)
|
||||
|
||||
line_length = 120
|
||||
spaces = " " * (40 - len(name) - indent_level)
|
||||
line = f"{' ' * indent_level} * {name}{spaces}- {change_string}"
|
||||
|
||||
if len(msg) < 50:
|
||||
line += f" -- {msg}"
|
||||
self._display.display(f"{line} {'-' * (line_length - len(line))}---------")
|
||||
else:
|
||||
self._display.display(f"{line} {'-' * (line_length - len(line))}")
|
||||
self._display.display(self._indent_text(msg, indent_level + 4))
|
||||
|
||||
if diff:
|
||||
self._print_diff(diff, indent_level)
|
||||
if stdout:
|
||||
stdout = self.colorize(stdout, "failed")
|
||||
self._display.display(self._indent_text(stdout, indent_level + 4))
|
||||
if stderr:
|
||||
stderr = self.colorize(stderr, "failed")
|
||||
self._display.display(self._indent_text(stderr, indent_level + 4))
|
||||
|
||||
def v2_playbook_on_play_start(self, play):
|
||||
"""Run on start of the play."""
|
||||
pass
|
||||
|
||||
def v2_playbook_on_task_start(self, task, **kwargs):
|
||||
"""Run when a task starts."""
|
||||
self.last_task_name = task.get_name()
|
||||
self.printed_last_task = False
|
||||
|
||||
def _print_task_result(self, result, error=False, **kwargs):
|
||||
"""Run when a task finishes correctly."""
|
||||
|
||||
if "print_action" in result._task.tags or error or self._display.verbosity > 1:
|
||||
self._print_task()
|
||||
self.last_skipped = False
|
||||
msg = to_text(result._result.get("msg", "")) or to_text(result._result.get("reason", ""))
|
||||
|
||||
stderr = [result._result.get("exception", None), result._result.get("module_stderr", None)]
|
||||
stderr = "\n".join([e for e in stderr if e]).strip()
|
||||
|
||||
self._print_host_or_item(
|
||||
result._host,
|
||||
result._result.get("changed", False),
|
||||
msg,
|
||||
result._result.get("diff", None),
|
||||
is_host=True,
|
||||
error=error,
|
||||
stdout=result._result.get("module_stdout", None),
|
||||
stderr=stderr.strip(),
|
||||
)
|
||||
if "results" in result._result:
|
||||
for r in result._result["results"]:
|
||||
failed = "failed" in r and r["failed"]
|
||||
|
||||
stderr = [r.get("exception", None), r.get("module_stderr", None)]
|
||||
stderr = "\n".join([e for e in stderr if e]).strip()
|
||||
|
||||
self._print_host_or_item(
|
||||
r[r["ansible_loop_var"]],
|
||||
r.get("changed", False),
|
||||
to_text(r.get("msg", "")),
|
||||
r.get("diff", None),
|
||||
is_host=False,
|
||||
error=failed,
|
||||
stdout=r.get("module_stdout", None),
|
||||
stderr=stderr.strip(),
|
||||
)
|
||||
else:
|
||||
self.last_skipped = True
|
||||
print(".", end="")
|
||||
|
||||
def v2_playbook_on_stats(self, stats):
|
||||
"""Display info about playbook statistics."""
|
||||
self._display.display("")
|
||||
self.printed_last_task = False
|
||||
self._print_task("STATS")
|
||||
|
||||
hosts = sorted(stats.processed.keys())
|
||||
max_len = max((len(h) for h in hosts), default=0)
|
||||
for host in hosts:
|
||||
s = stats.summarize(host)
|
||||
|
||||
if s["failures"] or s["unreachable"]:
|
||||
color = "failed"
|
||||
elif s["changed"]:
|
||||
color = "changed"
|
||||
else:
|
||||
color = "ok"
|
||||
|
||||
msg = (
|
||||
f"{host.ljust(max_len)} : ok={s['ok']}\tchanged={s['changed']}\tfailed={s['failures']}\t"
|
||||
f"unreachable={s['unreachable']}\trescued={s['rescued']}\tignored={s['ignored']}"
|
||||
)
|
||||
self._display.display(self.colorize(msg, color))
|
||||
|
||||
def v2_runner_on_skipped(self, result, **kwargs):
|
||||
"""Run when a task is skipped."""
|
||||
if self._display.verbosity > 1:
|
||||
self._print_task()
|
||||
self.last_skipped = False
|
||||
|
||||
line_length = 120
|
||||
spaces = " " * (31 - len(result._host.name) - 4)
|
||||
|
||||
line = (
|
||||
f" * {self.colorize(result._host.name, 'not_so_bold')}{spaces}- {self.colorize('skipped', 'skipped')}"
|
||||
)
|
||||
|
||||
reason = result._result.get("skipped_reason", "") or result._result.get("skip_reason", "")
|
||||
if len(reason) < 50:
|
||||
line += f" -- {reason}"
|
||||
self._display.display(f"{line} {'-' * (line_length - len(line))}---------")
|
||||
else:
|
||||
self._display.display(f"{line} {'-' * (line_length - len(line))}")
|
||||
self._display.display(self._indent_text(reason, 8))
|
||||
self._display.display(reason)
|
||||
|
||||
def v2_runner_on_ok(self, result, **kwargs):
|
||||
self._print_task_result(result, error=False, **kwargs)
|
||||
|
||||
def v2_runner_on_failed(self, result, **kwargs):
|
||||
self._print_task_result(result, error=True, **kwargs)
|
||||
|
||||
def v2_runner_on_unreachable(self, result, **kwargs):
|
||||
self._print_task_result(result, error=True, **kwargs)
|
||||
|
||||
v2_playbook_on_handler_task_start = v2_playbook_on_task_start
|
||||
@@ -0,0 +1,248 @@
|
||||
# Copyright (c) 2014-2015, Matt Martz <matt@sivel.net>
|
||||
# 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: Unknown (!UNKNOWN)
|
||||
name: slack
|
||||
type: notification
|
||||
requirements:
|
||||
- whitelist in configuration
|
||||
- prettytable (python library)
|
||||
short_description: Sends play events to a Slack channel
|
||||
description:
|
||||
- This is an ansible callback plugin that sends status updates to a Slack channel during playbook execution.
|
||||
options:
|
||||
http_agent:
|
||||
description:
|
||||
- HTTP user agent to use for requests to Slack.
|
||||
type: string
|
||||
version_added: "10.5.0"
|
||||
webhook_url:
|
||||
required: true
|
||||
description: Slack Webhook URL.
|
||||
type: str
|
||||
env:
|
||||
- name: SLACK_WEBHOOK_URL
|
||||
ini:
|
||||
- section: callback_slack
|
||||
key: webhook_url
|
||||
channel:
|
||||
default: "#ansible"
|
||||
description: Slack room to post in.
|
||||
type: str
|
||||
env:
|
||||
- name: SLACK_CHANNEL
|
||||
ini:
|
||||
- section: callback_slack
|
||||
key: channel
|
||||
username:
|
||||
description: Username to post as.
|
||||
type: str
|
||||
env:
|
||||
- name: SLACK_USERNAME
|
||||
default: ansible
|
||||
ini:
|
||||
- section: callback_slack
|
||||
key: username
|
||||
validate_certs:
|
||||
description: Validate the SSL certificate of the Slack server for HTTPS URLs.
|
||||
env:
|
||||
- name: SLACK_VALIDATE_CERTS
|
||||
ini:
|
||||
- section: callback_slack
|
||||
key: validate_certs
|
||||
default: true
|
||||
type: bool
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import uuid
|
||||
|
||||
from ansible import context
|
||||
from ansible.module_utils.urls import open_url
|
||||
from ansible.plugins.callback import CallbackBase
|
||||
|
||||
from ansible_collections.community.general.plugins.module_utils._secrets import mask_secret_values
|
||||
|
||||
try:
|
||||
import prettytable
|
||||
|
||||
HAS_PRETTYTABLE = True
|
||||
except ImportError:
|
||||
HAS_PRETTYTABLE = False
|
||||
|
||||
|
||||
class CallbackModule(CallbackBase):
|
||||
"""This is an ansible callback plugin that sends status
|
||||
updates to a Slack channel during playbook execution.
|
||||
"""
|
||||
|
||||
CALLBACK_VERSION = 2.0
|
||||
CALLBACK_TYPE = "notification"
|
||||
CALLBACK_NAME = "community.general.slack"
|
||||
CALLBACK_NEEDS_WHITELIST = True
|
||||
|
||||
def __init__(self, display=None):
|
||||
super().__init__(display=display)
|
||||
|
||||
if not HAS_PRETTYTABLE:
|
||||
self.disabled = True
|
||||
self._display.warning(
|
||||
"The `prettytable` python module is not installed. Disabling the Slack callback plugin."
|
||||
)
|
||||
|
||||
self.playbook_name = None
|
||||
|
||||
# This is a 6 character identifier provided with each message
|
||||
# This makes it easier to correlate messages when there are more
|
||||
# than 1 simultaneous playbooks running
|
||||
self.guid = uuid.uuid4().hex[:6]
|
||||
|
||||
def set_options(self, task_keys=None, var_options=None, direct=None):
|
||||
super().set_options(task_keys=task_keys, var_options=var_options, direct=direct)
|
||||
|
||||
self.webhook_url = self.get_option("webhook_url")
|
||||
self.channel = self.get_option("channel")
|
||||
self.username = self.get_option("username")
|
||||
self.show_invocation = self._display.verbosity > 1
|
||||
self.validate_certs = self.get_option("validate_certs")
|
||||
self.http_agent = self.get_option("http_agent")
|
||||
if self.webhook_url is None:
|
||||
self.disabled = True
|
||||
self._display.warning(
|
||||
"Slack Webhook URL was not provided. The "
|
||||
"Slack Webhook URL can be provided using "
|
||||
"the `SLACK_WEBHOOK_URL` environment "
|
||||
"variable."
|
||||
)
|
||||
|
||||
def send_msg(self, attachments):
|
||||
headers = {
|
||||
"Content-type": "application/json",
|
||||
}
|
||||
|
||||
payload = {
|
||||
"channel": self.channel,
|
||||
"username": self.username,
|
||||
"attachments": attachments,
|
||||
"parse": "none",
|
||||
"icon_url": ("https://cdn2.hubspot.net/hub/330046/file-449187601-png/ansible_badge.png"),
|
||||
}
|
||||
|
||||
data = json.dumps(payload)
|
||||
self._display.debug(data)
|
||||
self._display.debug(self.webhook_url)
|
||||
try:
|
||||
response = open_url(
|
||||
self.webhook_url,
|
||||
data=data,
|
||||
validate_certs=self.validate_certs,
|
||||
headers=headers,
|
||||
http_agent=self.http_agent,
|
||||
)
|
||||
return response.read()
|
||||
except Exception as e:
|
||||
self._display.warning(f"Could not submit message to Slack: {e}")
|
||||
|
||||
def v2_playbook_on_start(self, playbook):
|
||||
self.playbook_name = os.path.basename(playbook._file_name)
|
||||
|
||||
title = [f"*Playbook initiated* (_{self.guid}_)"]
|
||||
|
||||
invocation_items = []
|
||||
if context.CLIARGS and self.show_invocation:
|
||||
tags = context.CLIARGS["tags"]
|
||||
skip_tags = context.CLIARGS["skip_tags"]
|
||||
extra_vars = context.CLIARGS["extra_vars"]
|
||||
subset = context.CLIARGS["subset"]
|
||||
inventory = [os.path.abspath(i) for i in context.CLIARGS["inventory"]]
|
||||
|
||||
invocation_items.append(f"Inventory: {', '.join(inventory)}")
|
||||
if tags and tags != ["all"]:
|
||||
invocation_items.append(f"Tags: {', '.join(tags)}")
|
||||
if skip_tags:
|
||||
invocation_items.append(f"Skip Tags: {', '.join(skip_tags)}")
|
||||
if subset:
|
||||
invocation_items.append(f"Limit: {subset}")
|
||||
if extra_vars:
|
||||
invocation_items.append(f"Extra Vars: {' '.join(mask_secret_values(extra_vars))}")
|
||||
|
||||
title.append(f"by *{context.CLIARGS['remote_user']}*")
|
||||
|
||||
title.append(f"\n\n*{self.playbook_name}*")
|
||||
msg_items = [" ".join(title)]
|
||||
if invocation_items:
|
||||
_inv_item = "\n".join(invocation_items)
|
||||
msg_items.append(f"```\n{_inv_item}\n```")
|
||||
|
||||
msg = "\n".join(msg_items)
|
||||
|
||||
attachments = [
|
||||
{
|
||||
"fallback": msg,
|
||||
"fields": [{"value": msg}],
|
||||
"color": "warning",
|
||||
"mrkdwn_in": ["text", "fallback", "fields"],
|
||||
}
|
||||
]
|
||||
|
||||
self.send_msg(attachments=attachments)
|
||||
|
||||
def v2_playbook_on_play_start(self, play):
|
||||
"""Display Play start messages"""
|
||||
|
||||
name = play.name or f"Play name not specified ({play._uuid})"
|
||||
msg = f"*Starting play* (_{self.guid}_)\n\n*{name}*"
|
||||
attachments = [
|
||||
{
|
||||
"fallback": msg,
|
||||
"text": msg,
|
||||
"color": "warning",
|
||||
"mrkdwn_in": ["text", "fallback", "fields"],
|
||||
}
|
||||
]
|
||||
self.send_msg(attachments=attachments)
|
||||
|
||||
def v2_playbook_on_stats(self, stats):
|
||||
"""Display info about playbook statistics"""
|
||||
|
||||
hosts = sorted(stats.processed.keys())
|
||||
|
||||
t = prettytable.PrettyTable(["Host", "Ok", "Changed", "Unreachable", "Failures", "Rescued", "Ignored"])
|
||||
|
||||
failures = False
|
||||
unreachable = False
|
||||
|
||||
for h in hosts:
|
||||
s = stats.summarize(h)
|
||||
|
||||
if s["failures"] > 0:
|
||||
failures = True
|
||||
if s["unreachable"] > 0:
|
||||
unreachable = True
|
||||
|
||||
t.add_row([h] + [s[k] for k in ["ok", "changed", "unreachable", "failures", "rescued", "ignored"]])
|
||||
|
||||
attachments = []
|
||||
msg_items = [f"*Playbook Complete* (_{self.guid}_)"]
|
||||
if failures or unreachable:
|
||||
color = "danger"
|
||||
msg_items.append("\n*Failed!*")
|
||||
else:
|
||||
color = "good"
|
||||
msg_items.append("\n*Success!*")
|
||||
|
||||
msg_items.append(f"```\n{t}\n```")
|
||||
|
||||
msg = "\n".join(msg_items)
|
||||
|
||||
attachments.append(
|
||||
{"fallback": msg, "fields": [{"value": msg}], "color": color, "mrkdwn_in": ["text", "fallback", "fields"]}
|
||||
)
|
||||
|
||||
self.send_msg(attachments=attachments)
|
||||
+279
@@ -0,0 +1,279 @@
|
||||
# Copyright (c) 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"""
|
||||
name: splunk
|
||||
type: notification
|
||||
short_description: Sends task result events to Splunk HTTP Event Collector
|
||||
author: "Stuart Hirst (!UNKNOWN) <support@convergingdata.com>"
|
||||
description:
|
||||
- This callback plugin sends task results as JSON formatted events to a Splunk HTTP collector.
|
||||
- The companion Splunk Monitoring & Diagnostics App is available here U(https://splunkbase.splunk.com/app/4023/).
|
||||
- Credit to "Ryan Currah (@ryancurrah)" for original source upon which this is based.
|
||||
requirements:
|
||||
- Whitelisting this callback plugin
|
||||
- 'Create a HTTP Event Collector in Splunk'
|
||||
- 'Define the URL and token in C(ansible.cfg)'
|
||||
options:
|
||||
url:
|
||||
description: URL to the Splunk HTTP collector source.
|
||||
type: str
|
||||
env:
|
||||
- name: SPLUNK_URL
|
||||
ini:
|
||||
- section: callback_splunk
|
||||
key: url
|
||||
authtoken:
|
||||
description: Token to authenticate the connection to the Splunk HTTP collector.
|
||||
type: str
|
||||
env:
|
||||
- name: SPLUNK_AUTHTOKEN
|
||||
ini:
|
||||
- section: callback_splunk
|
||||
key: authtoken
|
||||
secret: true
|
||||
validate_certs:
|
||||
description: Whether to validate certificates for connections to HEC. It is not recommended to set to V(false) except
|
||||
when you are sure that nobody can intercept the connection between this plugin and HEC, as setting it to V(false) allows
|
||||
man-in-the-middle attacks!
|
||||
env:
|
||||
- name: SPLUNK_VALIDATE_CERTS
|
||||
ini:
|
||||
- section: callback_splunk
|
||||
key: validate_certs
|
||||
type: bool
|
||||
default: true
|
||||
version_added: '1.0.0'
|
||||
include_milliseconds:
|
||||
description: Whether to include milliseconds as part of the generated timestamp field in the event sent to the Splunk
|
||||
HTTP collector.
|
||||
env:
|
||||
- name: SPLUNK_INCLUDE_MILLISECONDS
|
||||
ini:
|
||||
- section: callback_splunk
|
||||
key: include_milliseconds
|
||||
type: bool
|
||||
default: false
|
||||
version_added: 2.0.0
|
||||
batch:
|
||||
description:
|
||||
- Correlation ID which can be set across multiple playbook executions.
|
||||
env:
|
||||
- name: SPLUNK_BATCH
|
||||
ini:
|
||||
- section: callback_splunk
|
||||
key: batch
|
||||
type: str
|
||||
version_added: 3.3.0
|
||||
"""
|
||||
|
||||
EXAMPLES = r"""
|
||||
examples: >-
|
||||
To enable, add this to your ansible.cfg file in the defaults block
|
||||
[defaults]
|
||||
callback_whitelist = community.general.splunk
|
||||
Set the environment variable
|
||||
export SPLUNK_URL=http://mysplunkinstance.datapaas.io:8088/services/collector/event
|
||||
export SPLUNK_AUTHTOKEN=f23blad6-5965-4537-bf69-5b5a545blabla88
|
||||
Set the ansible.cfg variable in the callback_splunk block
|
||||
[callback_splunk]
|
||||
url = http://mysplunkinstance.datapaas.io:8088/services/collector/event
|
||||
authtoken = f23blad6-5965-4537-bf69-5b5a545blabla88
|
||||
"""
|
||||
|
||||
import getpass
|
||||
import json
|
||||
import socket
|
||||
import uuid
|
||||
from os.path import basename
|
||||
|
||||
from ansible.module_utils.ansible_release import __version__ as ansible_version
|
||||
from ansible.module_utils.urls import open_url
|
||||
from ansible.parsing.ajson import AnsibleJSONEncoder
|
||||
from ansible.plugins.callback import CallbackBase
|
||||
|
||||
from ansible_collections.community.general.plugins.module_utils._datetime import (
|
||||
now,
|
||||
)
|
||||
from ansible_collections.community.general.plugins.module_utils._secrets import mask_secret_values
|
||||
|
||||
|
||||
class SplunkHTTPCollectorSource:
|
||||
def __init__(self):
|
||||
self.ansible_playbook = ""
|
||||
self.session = str(uuid.uuid4())
|
||||
self.host = socket.gethostname()
|
||||
self.ip_address = socket.gethostbyname(socket.gethostname())
|
||||
self.user = getpass.getuser()
|
||||
|
||||
def send_event(self, url, authtoken, validate_certs, include_milliseconds, batch, state, result, runtime):
|
||||
ansible_check_mode = result._task_fields["args"].get("_ansible_check_mode") is True
|
||||
|
||||
if result._task._role:
|
||||
ansible_role = str(result._task._role)
|
||||
else:
|
||||
ansible_role = None
|
||||
|
||||
if "args" in result._task_fields:
|
||||
del result._task_fields["args"]
|
||||
|
||||
data = {}
|
||||
data["uuid"] = result._task._uuid
|
||||
data["session"] = self.session
|
||||
if batch is not None:
|
||||
data["batch"] = batch
|
||||
data["status"] = state
|
||||
|
||||
if include_milliseconds:
|
||||
time_format = "%Y-%m-%d %H:%M:%S.%f +0000"
|
||||
else:
|
||||
time_format = "%Y-%m-%d %H:%M:%S +0000"
|
||||
|
||||
data["timestamp"] = now().strftime(time_format)
|
||||
data["host"] = self.host
|
||||
data["ip_address"] = self.ip_address
|
||||
data["user"] = self.user
|
||||
data["runtime"] = runtime
|
||||
data["ansible_version"] = ansible_version
|
||||
data["ansible_check_mode"] = ansible_check_mode
|
||||
data["ansible_host"] = result._host.name
|
||||
data["ansible_playbook"] = self.ansible_playbook
|
||||
data["ansible_role"] = ansible_role
|
||||
data["ansible_task"] = mask_secret_values(result._task_fields)
|
||||
data["ansible_result"] = result._result
|
||||
|
||||
# This wraps the json payload in and outer json event needed by Splunk
|
||||
jsondata = json.dumps({"event": data}, cls=AnsibleJSONEncoder, sort_keys=True)
|
||||
|
||||
open_url(
|
||||
url,
|
||||
jsondata,
|
||||
headers={"Content-type": "application/json", "Authorization": f"Splunk {authtoken}"},
|
||||
method="POST",
|
||||
validate_certs=validate_certs,
|
||||
)
|
||||
|
||||
|
||||
class CallbackModule(CallbackBase):
|
||||
CALLBACK_VERSION = 2.0
|
||||
CALLBACK_TYPE = "notification"
|
||||
CALLBACK_NAME = "community.general.splunk"
|
||||
CALLBACK_NEEDS_WHITELIST = True
|
||||
|
||||
def __init__(self, display=None):
|
||||
super().__init__(display=display)
|
||||
self.start_datetimes = {} # Collect task start times
|
||||
self.url = None
|
||||
self.authtoken = None
|
||||
self.validate_certs = None
|
||||
self.include_milliseconds = None
|
||||
self.batch = None
|
||||
self.splunk = SplunkHTTPCollectorSource()
|
||||
|
||||
def _runtime(self, result):
|
||||
return (now() - self.start_datetimes[result._task._uuid]).total_seconds()
|
||||
|
||||
def set_options(self, task_keys=None, var_options=None, direct=None):
|
||||
super().set_options(task_keys=task_keys, var_options=var_options, direct=direct)
|
||||
|
||||
self.url = self.get_option("url")
|
||||
|
||||
if self.url is None:
|
||||
self.disabled = True
|
||||
self._display.warning(
|
||||
"Splunk HTTP collector source URL was "
|
||||
"not provided. The Splunk HTTP collector "
|
||||
"source URL can be provided using the "
|
||||
"`SPLUNK_URL` environment variable or "
|
||||
"in the ansible.cfg file."
|
||||
)
|
||||
|
||||
self.authtoken = self.get_option("authtoken")
|
||||
|
||||
if self.authtoken is None:
|
||||
self.disabled = True
|
||||
self._display.warning(
|
||||
"Splunk HTTP collector requires an authentication"
|
||||
"token. The Splunk HTTP collector "
|
||||
"authentication token can be provided using the "
|
||||
"`SPLUNK_AUTHTOKEN` environment variable or "
|
||||
"in the ansible.cfg file."
|
||||
)
|
||||
|
||||
self.validate_certs = self.get_option("validate_certs")
|
||||
|
||||
self.include_milliseconds = self.get_option("include_milliseconds")
|
||||
|
||||
self.batch = self.get_option("batch")
|
||||
|
||||
def v2_playbook_on_start(self, playbook):
|
||||
self.splunk.ansible_playbook = basename(playbook._file_name)
|
||||
|
||||
def v2_playbook_on_task_start(self, task, is_conditional):
|
||||
self.start_datetimes[task._uuid] = now()
|
||||
|
||||
def v2_playbook_on_handler_task_start(self, task):
|
||||
self.start_datetimes[task._uuid] = now()
|
||||
|
||||
def v2_runner_on_ok(self, result, **kwargs):
|
||||
self.splunk.send_event(
|
||||
self.url,
|
||||
self.authtoken,
|
||||
self.validate_certs,
|
||||
self.include_milliseconds,
|
||||
self.batch,
|
||||
"OK",
|
||||
result,
|
||||
self._runtime(result),
|
||||
)
|
||||
|
||||
def v2_runner_on_skipped(self, result, **kwargs):
|
||||
self.splunk.send_event(
|
||||
self.url,
|
||||
self.authtoken,
|
||||
self.validate_certs,
|
||||
self.include_milliseconds,
|
||||
self.batch,
|
||||
"SKIPPED",
|
||||
result,
|
||||
self._runtime(result),
|
||||
)
|
||||
|
||||
def v2_runner_on_failed(self, result, **kwargs):
|
||||
self.splunk.send_event(
|
||||
self.url,
|
||||
self.authtoken,
|
||||
self.validate_certs,
|
||||
self.include_milliseconds,
|
||||
self.batch,
|
||||
"FAILED",
|
||||
result,
|
||||
self._runtime(result),
|
||||
)
|
||||
|
||||
def v2_runner_on_async_failed(self, result, **kwargs):
|
||||
self.splunk.send_event(
|
||||
self.url,
|
||||
self.authtoken,
|
||||
self.validate_certs,
|
||||
self.include_milliseconds,
|
||||
self.batch,
|
||||
"FAILED",
|
||||
result,
|
||||
self._runtime(result),
|
||||
)
|
||||
|
||||
def v2_runner_on_unreachable(self, result, **kwargs):
|
||||
self.splunk.send_event(
|
||||
self.url,
|
||||
self.authtoken,
|
||||
self.validate_certs,
|
||||
self.include_milliseconds,
|
||||
self.batch,
|
||||
"UNREACHABLE",
|
||||
result,
|
||||
self._runtime(result),
|
||||
)
|
||||
+158
@@ -0,0 +1,158 @@
|
||||
# Copyright (c) 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"""
|
||||
name: sumologic
|
||||
type: notification
|
||||
short_description: Sends task result events to Sumologic
|
||||
author: "Ryan Currah (@ryancurrah)"
|
||||
description:
|
||||
- This callback plugin sends task results as JSON formatted events to a Sumologic HTTP collector source.
|
||||
requirements:
|
||||
- Whitelisting this callback plugin
|
||||
- 'Create a HTTP collector source in Sumologic and specify a custom timestamp format of V(yyyy-MM-dd HH:mm:ss ZZZZ) and
|
||||
a custom timestamp locator of V("timestamp": "(.*\)")'
|
||||
options:
|
||||
url:
|
||||
description: URL to the Sumologic HTTP collector source.
|
||||
type: str
|
||||
env:
|
||||
- name: SUMOLOGIC_URL
|
||||
ini:
|
||||
- section: callback_sumologic
|
||||
key: url
|
||||
"""
|
||||
|
||||
EXAMPLES = r"""
|
||||
examples: |-
|
||||
To enable, add this to your ansible.cfg file in the defaults block
|
||||
[defaults]
|
||||
callback_whitelist = community.general.sumologic
|
||||
|
||||
Set the environment variable
|
||||
export SUMOLOGIC_URL=https://endpoint1.collection.us2.sumologic.com/receiver/v1/http/R8moSv1d8EW9LAUFZJ6dbxCFxwLH6kfCdcBfddlfxCbLuL-BN5twcTpMk__pYy_cDmp==
|
||||
|
||||
Set the ansible.cfg variable in the callback_sumologic block
|
||||
[callback_sumologic]
|
||||
url = https://endpoint1.collection.us2.sumologic.com/receiver/v1/http/R8moSv1d8EW9LAUFZJ6dbxCFxwLH6kfCdcBfddlfxCbLuL-BN5twcTpMk__pYy_cDmp==
|
||||
"""
|
||||
|
||||
import getpass
|
||||
import json
|
||||
import socket
|
||||
import uuid
|
||||
from os.path import basename
|
||||
|
||||
from ansible.module_utils.ansible_release import __version__ as ansible_version
|
||||
from ansible.module_utils.urls import open_url
|
||||
from ansible.parsing.ajson import AnsibleJSONEncoder
|
||||
from ansible.plugins.callback import CallbackBase
|
||||
|
||||
from ansible_collections.community.general.plugins.module_utils._datetime import (
|
||||
now,
|
||||
)
|
||||
from ansible_collections.community.general.plugins.module_utils._secrets import mask_secret_values
|
||||
|
||||
|
||||
class SumologicHTTPCollectorSource:
|
||||
def __init__(self):
|
||||
self.ansible_check_mode = False
|
||||
self.ansible_playbook = ""
|
||||
self.session = str(uuid.uuid4())
|
||||
self.host = socket.gethostname()
|
||||
self.ip_address = socket.gethostbyname(socket.gethostname())
|
||||
self.user = getpass.getuser()
|
||||
|
||||
def send_event(self, url, state, result, runtime):
|
||||
if result._task_fields["args"].get("_ansible_check_mode") is True:
|
||||
self.ansible_check_mode = True
|
||||
|
||||
if result._task._role:
|
||||
ansible_role = str(result._task._role)
|
||||
else:
|
||||
ansible_role = None
|
||||
|
||||
if "args" in result._task_fields:
|
||||
del result._task_fields["args"]
|
||||
|
||||
data = {}
|
||||
data["uuid"] = result._task._uuid
|
||||
data["session"] = self.session
|
||||
data["status"] = state
|
||||
data["timestamp"] = now().strftime("%Y-%m-%d %H:%M:%S +0000")
|
||||
data["host"] = self.host
|
||||
data["ip_address"] = self.ip_address
|
||||
data["user"] = self.user
|
||||
data["runtime"] = runtime
|
||||
data["ansible_version"] = ansible_version
|
||||
data["ansible_check_mode"] = self.ansible_check_mode
|
||||
data["ansible_host"] = result._host.name
|
||||
data["ansible_playbook"] = self.ansible_playbook
|
||||
data["ansible_role"] = ansible_role
|
||||
data["ansible_task"] = mask_secret_values(result._task_fields)
|
||||
data["ansible_result"] = result._result
|
||||
|
||||
open_url(
|
||||
url,
|
||||
data=json.dumps(data, cls=AnsibleJSONEncoder, sort_keys=True),
|
||||
headers={"Content-type": "application/json", "X-Sumo-Host": data["ansible_host"]},
|
||||
method="POST",
|
||||
)
|
||||
|
||||
|
||||
class CallbackModule(CallbackBase):
|
||||
CALLBACK_VERSION = 2.0
|
||||
CALLBACK_TYPE = "notification"
|
||||
CALLBACK_NAME = "community.general.sumologic"
|
||||
CALLBACK_NEEDS_WHITELIST = True
|
||||
|
||||
def __init__(self, display=None):
|
||||
super().__init__(display=display)
|
||||
self.start_datetimes = {} # Collect task start times
|
||||
self.url = None
|
||||
self.sumologic = SumologicHTTPCollectorSource()
|
||||
|
||||
def _runtime(self, result):
|
||||
return (now() - self.start_datetimes[result._task._uuid]).total_seconds()
|
||||
|
||||
def set_options(self, task_keys=None, var_options=None, direct=None):
|
||||
super().set_options(task_keys=task_keys, var_options=var_options, direct=direct)
|
||||
|
||||
self.url = self.get_option("url")
|
||||
|
||||
if self.url is None:
|
||||
self.disabled = True
|
||||
self._display.warning(
|
||||
"Sumologic HTTP collector source URL was "
|
||||
"not provided. The Sumologic HTTP collector "
|
||||
"source URL can be provided using the "
|
||||
"`SUMOLOGIC_URL` environment variable or "
|
||||
"in the ansible.cfg file."
|
||||
)
|
||||
|
||||
def v2_playbook_on_start(self, playbook):
|
||||
self.sumologic.ansible_playbook = basename(playbook._file_name)
|
||||
|
||||
def v2_playbook_on_task_start(self, task, is_conditional):
|
||||
self.start_datetimes[task._uuid] = now()
|
||||
|
||||
def v2_playbook_on_handler_task_start(self, task):
|
||||
self.start_datetimes[task._uuid] = now()
|
||||
|
||||
def v2_runner_on_ok(self, result, **kwargs):
|
||||
self.sumologic.send_event(self.url, "OK", result, self._runtime(result))
|
||||
|
||||
def v2_runner_on_skipped(self, result, **kwargs):
|
||||
self.sumologic.send_event(self.url, "SKIPPED", result, self._runtime(result))
|
||||
|
||||
def v2_runner_on_failed(self, result, **kwargs):
|
||||
self.sumologic.send_event(self.url, "FAILED", result, self._runtime(result))
|
||||
|
||||
def runner_on_async_failed(self, result, **kwargs):
|
||||
self.sumologic.send_event(self.url, "FAILED", result, self._runtime(result))
|
||||
|
||||
def v2_runner_on_unreachable(self, result, **kwargs):
|
||||
self.sumologic.send_event(self.url, "UNREACHABLE", result, self._runtime(result))
|
||||
+159
@@ -0,0 +1,159 @@
|
||||
# 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: Unknown (!UNKNOWN)
|
||||
name: syslog_json
|
||||
type: notification
|
||||
requirements:
|
||||
- whitelist in configuration
|
||||
short_description: Sends JSON events to syslog
|
||||
description:
|
||||
- This plugin logs ansible-playbook and ansible runs to a syslog server in JSON format.
|
||||
options:
|
||||
server:
|
||||
description: Syslog server that receives the event.
|
||||
type: str
|
||||
env:
|
||||
- name: SYSLOG_SERVER
|
||||
default: localhost
|
||||
ini:
|
||||
- section: callback_syslog_json
|
||||
key: syslog_server
|
||||
port:
|
||||
description: Port on which the syslog server is listening.
|
||||
type: int
|
||||
env:
|
||||
- name: SYSLOG_PORT
|
||||
default: 514
|
||||
ini:
|
||||
- section: callback_syslog_json
|
||||
key: syslog_port
|
||||
facility:
|
||||
description: Syslog facility to log as.
|
||||
type: str
|
||||
env:
|
||||
- name: SYSLOG_FACILITY
|
||||
default: user
|
||||
ini:
|
||||
- section: callback_syslog_json
|
||||
key: syslog_facility
|
||||
setup:
|
||||
description: Log setup tasks.
|
||||
env:
|
||||
- name: ANSIBLE_SYSLOG_SETUP
|
||||
type: bool
|
||||
default: true
|
||||
ini:
|
||||
- section: callback_syslog_json
|
||||
key: syslog_setup
|
||||
version_added: 4.5.0
|
||||
"""
|
||||
|
||||
import logging
|
||||
import logging.handlers
|
||||
import socket
|
||||
|
||||
from ansible.plugins.callback import CallbackBase
|
||||
|
||||
from ansible_collections.community.general.plugins.module_utils._secrets import mask_secrets
|
||||
|
||||
|
||||
class CallbackModule(CallbackBase):
|
||||
"""
|
||||
logs ansible-playbook and ansible runs to a syslog server in json format
|
||||
"""
|
||||
|
||||
CALLBACK_VERSION = 2.0
|
||||
CALLBACK_TYPE = "notification"
|
||||
CALLBACK_NAME = "community.general.syslog_json"
|
||||
CALLBACK_NEEDS_WHITELIST = True
|
||||
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
|
||||
def set_options(self, task_keys=None, var_options=None, direct=None):
|
||||
super().set_options(task_keys=task_keys, var_options=var_options, direct=direct)
|
||||
|
||||
syslog_host = self.get_option("server")
|
||||
syslog_port = int(self.get_option("port"))
|
||||
syslog_facility = self.get_option("facility")
|
||||
|
||||
self.logger = logging.getLogger("ansible logger")
|
||||
self.logger.setLevel(logging.DEBUG)
|
||||
|
||||
self.handler = logging.handlers.SysLogHandler(address=(syslog_host, syslog_port), facility=syslog_facility)
|
||||
self.logger.addHandler(self.handler)
|
||||
self.hostname = socket.gethostname()
|
||||
|
||||
def v2_runner_on_failed(self, result, ignore_errors=False):
|
||||
res = result._result
|
||||
host = result._host.get_name()
|
||||
self.logger.error(
|
||||
"%s ansible-command: task execution FAILED; host: %s; message: %s",
|
||||
self.hostname,
|
||||
host,
|
||||
self._dump_results(res),
|
||||
)
|
||||
|
||||
def v2_runner_on_ok(self, result):
|
||||
res = result._result
|
||||
host = result._host.get_name()
|
||||
if result._task.action != "gather_facts" or self.get_option("setup"):
|
||||
self.logger.info(
|
||||
"%s ansible-command: task execution OK; host: %s; message: %s",
|
||||
self.hostname,
|
||||
host,
|
||||
self._dump_results(res),
|
||||
)
|
||||
|
||||
def v2_runner_on_skipped(self, result):
|
||||
host = result._host.get_name()
|
||||
self.logger.info(
|
||||
"%s ansible-command: task execution SKIPPED; host: %s; message: %s",
|
||||
self.hostname,
|
||||
host,
|
||||
"skipped",
|
||||
)
|
||||
|
||||
def v2_runner_on_unreachable(self, result):
|
||||
res = result._result
|
||||
host = result._host.get_name()
|
||||
self.logger.error(
|
||||
"%s ansible-command: task execution UNREACHABLE; host: %s; message: %s",
|
||||
self.hostname,
|
||||
host,
|
||||
self._dump_results(res),
|
||||
)
|
||||
|
||||
def v2_runner_on_async_failed(self, result):
|
||||
res = result._result
|
||||
host = result._host.get_name()
|
||||
# jid = result._result.get("ansible_job_id")
|
||||
self.logger.error(
|
||||
"%s ansible-command: task execution FAILED; host: %s; message: %s",
|
||||
self.hostname,
|
||||
host,
|
||||
self._dump_results(res),
|
||||
)
|
||||
|
||||
def v2_playbook_on_import_for_host(self, result, imported_file):
|
||||
host = result._host.get_name()
|
||||
self.logger.info(
|
||||
"%s ansible-command: playbook IMPORTED; host: %s; message: imported file %s",
|
||||
self.hostname,
|
||||
host,
|
||||
mask_secrets(imported_file),
|
||||
)
|
||||
|
||||
def v2_playbook_on_not_import_for_host(self, result, missing_file):
|
||||
host = result._host.get_name()
|
||||
self.logger.info(
|
||||
"%s ansible-command: playbook NOT IMPORTED; host: %s; message: missing file %s",
|
||||
self.hostname,
|
||||
host,
|
||||
mask_secrets(missing_file),
|
||||
)
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
# Copyright (c) 2025, Felix Fontein <felix@fontein.de>
|
||||
# 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: Felix Fontein (@felixfontein)
|
||||
name: tasks_only
|
||||
type: stdout
|
||||
version_added: 11.1.0
|
||||
short_description: Only show tasks
|
||||
description:
|
||||
- Removes play start and stats marker from P(ansible.builtin.default#callback)'s output.
|
||||
- Can be used to generate output for documentation examples.
|
||||
For this, the O(number_of_columns) option should be set to an explicit value.
|
||||
extends_documentation_fragment:
|
||||
- ansible.builtin.default_callback
|
||||
- ansible.builtin.result_format_callback
|
||||
options:
|
||||
number_of_columns:
|
||||
description:
|
||||
- Sets the number of columns for Ansible's display.
|
||||
type: int
|
||||
env:
|
||||
- name: ANSIBLE_COLLECTIONS_TASKS_ONLY_NUMBER_OF_COLUMNS
|
||||
result_format:
|
||||
# Part of the ansible.builtin.result_format_callback doc fragment
|
||||
version_added: 11.2.0
|
||||
pretty_results:
|
||||
# Part of the ansible.builtin.result_format_callback doc fragment
|
||||
version_added: 11.2.0
|
||||
"""
|
||||
|
||||
EXAMPLES = r"""
|
||||
---
|
||||
# Enable callback in ansible.cfg:
|
||||
ansible_config: |-
|
||||
[defaults]
|
||||
stdout_callback = community.general.tasks_only
|
||||
|
||||
---
|
||||
# Enable callback with environment variables:
|
||||
environment_variable: |-
|
||||
ANSIBLE_STDOUT_CALLBACK=community.general.tasks_only
|
||||
"""
|
||||
|
||||
from ansible.plugins.callback.default import CallbackModule as Default
|
||||
|
||||
|
||||
class CallbackModule(Default):
|
||||
CALLBACK_VERSION = 2.0
|
||||
CALLBACK_TYPE = "stdout"
|
||||
CALLBACK_NAME = "community.general.tasks_only"
|
||||
|
||||
def v2_playbook_on_play_start(self, play):
|
||||
pass
|
||||
|
||||
def v2_playbook_on_stats(self, stats):
|
||||
pass
|
||||
|
||||
def set_options(self, *args, **kwargs):
|
||||
result = super().set_options(*args, **kwargs)
|
||||
self.number_of_columns = self.get_option("number_of_columns")
|
||||
if self.number_of_columns is not None:
|
||||
self._display.columns = self.number_of_columns
|
||||
return result
|
||||
+123
@@ -0,0 +1,123 @@
|
||||
# Copyright (c) 2024, kurokobo <kurokobo@protonmail.com>
|
||||
# Copyright (c) 2014, Michael DeHaan <michael.dehaan@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
|
||||
|
||||
DOCUMENTATION = r"""
|
||||
name: timestamp
|
||||
type: stdout
|
||||
short_description: Adds simple timestamp for each header
|
||||
version_added: 9.0.0
|
||||
description:
|
||||
- This callback adds simple timestamp for each header.
|
||||
author: kurokobo (@kurokobo)
|
||||
options:
|
||||
timezone:
|
||||
description:
|
||||
- Timezone to use for the timestamp in IANA time zone format.
|
||||
- For example V(America/New_York), V(Asia/Tokyo)). Ignored on Python < 3.9.
|
||||
ini:
|
||||
- section: callback_timestamp
|
||||
key: timezone
|
||||
env:
|
||||
- name: ANSIBLE_CALLBACK_TIMESTAMP_TIMEZONE
|
||||
type: string
|
||||
format_string:
|
||||
description:
|
||||
- Format of the timestamp shown to user in 1989 C standard format.
|
||||
- Refer to L(the Python documentation,https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes)
|
||||
for the available format codes.
|
||||
ini:
|
||||
- section: callback_timestamp
|
||||
key: format_string
|
||||
env:
|
||||
- name: ANSIBLE_CALLBACK_TIMESTAMP_FORMAT_STRING
|
||||
default: "%H:%M:%S"
|
||||
type: string
|
||||
seealso:
|
||||
- plugin: ansible.posix.profile_tasks
|
||||
plugin_type: callback
|
||||
description: >-
|
||||
You can use P(ansible.posix.profile_tasks#callback) callback plugin to time individual tasks and overall execution time
|
||||
with detailed timestamps.
|
||||
extends_documentation_fragment:
|
||||
- ansible.builtin.default_callback
|
||||
- ansible.builtin.result_format_callback
|
||||
"""
|
||||
|
||||
|
||||
import sys
|
||||
import types
|
||||
from datetime import datetime
|
||||
|
||||
from ansible.module_utils.common.text.converters import to_text
|
||||
from ansible.plugins.callback.default import CallbackModule as Default
|
||||
from ansible.utils.display import get_text_width
|
||||
|
||||
# Store whether the zoneinfo module is available
|
||||
_ZONEINFO_AVAILABLE = sys.version_info >= (3, 9)
|
||||
|
||||
|
||||
def get_datetime_now(tz):
|
||||
"""
|
||||
Returns the current timestamp with the specified timezone
|
||||
"""
|
||||
return datetime.now(tz=tz)
|
||||
|
||||
|
||||
def banner(self, msg, color=None, cows=True):
|
||||
"""
|
||||
Prints a header-looking line with cowsay or stars with length depending on terminal width (3 minimum) with trailing timestamp
|
||||
|
||||
Based on the banner method of Display class from ansible.utils.display
|
||||
|
||||
https://github.com/ansible/ansible/blob/4403519afe89138042108e237aef317fd5f09c33/lib/ansible/utils/display.py#L511
|
||||
"""
|
||||
timestamp = get_datetime_now(self.timestamp_tzinfo).strftime(self.timestamp_format_string)
|
||||
timestamp_len = get_text_width(timestamp) + 1 # +1 for leading space
|
||||
|
||||
msg = to_text(msg)
|
||||
if self.b_cowsay and cows:
|
||||
try:
|
||||
self.banner_cowsay(f"{msg} @ {timestamp}")
|
||||
return
|
||||
except OSError:
|
||||
self.warning("somebody cleverly deleted cowsay or something during the PB run. heh.")
|
||||
|
||||
msg = msg.strip()
|
||||
try:
|
||||
star_len = self.columns - get_text_width(msg) - timestamp_len
|
||||
except OSError:
|
||||
star_len = self.columns - len(msg) - timestamp_len
|
||||
if star_len <= 3:
|
||||
star_len = 3
|
||||
stars = "*" * star_len
|
||||
self.display(f"\n{msg} {stars} {timestamp}", color=color)
|
||||
|
||||
|
||||
class CallbackModule(Default):
|
||||
CALLBACK_VERSION = 2.0
|
||||
CALLBACK_TYPE = "stdout"
|
||||
CALLBACK_NAME = "community.general.timestamp"
|
||||
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
|
||||
# Replace the banner method of the display object with the custom one
|
||||
self._display.banner = types.MethodType(banner, self._display)
|
||||
|
||||
def set_options(self, task_keys=None, var_options=None, direct=None):
|
||||
super().set_options(task_keys=task_keys, var_options=var_options, direct=direct)
|
||||
|
||||
# Store zoneinfo for specified timezone if available
|
||||
tzinfo = None
|
||||
if _ZONEINFO_AVAILABLE and self.get_option("timezone"):
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
tzinfo = ZoneInfo(self.get_option("timezone"))
|
||||
|
||||
# Inject options into the display object
|
||||
self._display.timestamp_tzinfo = tzinfo
|
||||
self._display.timestamp_format_string = self.get_option("format_string")
|
||||
@@ -0,0 +1,257 @@
|
||||
# Copyright (c) 2023, Al Bowles <@akatch>
|
||||
# Copyright (c) 2012-2014, Michael DeHaan <michael.dehaan@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
|
||||
|
||||
DOCUMENTATION = r"""
|
||||
name: unixy
|
||||
type: stdout
|
||||
author: Al Bowles (@akatch)
|
||||
short_description: Condensed Ansible output
|
||||
description:
|
||||
- Consolidated Ansible output in the style of LINUX/UNIX startup logs.
|
||||
extends_documentation_fragment:
|
||||
- ansible.builtin.default_callback
|
||||
requirements:
|
||||
- set as stdout in configuration
|
||||
"""
|
||||
|
||||
from os.path import basename
|
||||
|
||||
from ansible import constants as C
|
||||
from ansible import context
|
||||
from ansible.module_utils.common.text.converters import to_text
|
||||
from ansible.plugins.callback.default import CallbackModule as CallbackModule_default
|
||||
from ansible.utils.color import colorize, hostcolor
|
||||
|
||||
|
||||
class CallbackModule(CallbackModule_default):
|
||||
"""
|
||||
Design goals:
|
||||
- Print consolidated output that looks like a *NIX startup log
|
||||
- Defaults should avoid displaying unnecessary information wherever possible
|
||||
|
||||
TODOs:
|
||||
- Only display task names if the task runs on at least one host
|
||||
- Add option to display all hostnames on a single line in the appropriate result color (failures may have a separate line)
|
||||
- Consolidate stats display
|
||||
- Don't show play name if no hosts found
|
||||
"""
|
||||
|
||||
CALLBACK_VERSION = 2.0
|
||||
CALLBACK_TYPE = "stdout"
|
||||
CALLBACK_NAME = "community.general.unixy"
|
||||
|
||||
def _run_is_verbose(self, result):
|
||||
return (
|
||||
self._display.verbosity > 0 or "_ansible_verbose_always" in result._result
|
||||
) and "_ansible_verbose_override" not in result._result
|
||||
|
||||
def _get_task_display_name(self, task):
|
||||
self.task_display_name = None
|
||||
display_name = task.get_name().strip().split(" : ")
|
||||
|
||||
task_display_name = display_name[-1]
|
||||
if task_display_name.startswith("include"):
|
||||
return
|
||||
else:
|
||||
self.task_display_name = task_display_name
|
||||
|
||||
def _preprocess_result(self, result):
|
||||
self.delegated_vars = result._result.get("_ansible_delegated_vars", None)
|
||||
self._handle_exception(result._result, use_stderr=self.get_option("display_failed_stderr"))
|
||||
self._handle_warnings(result._result)
|
||||
|
||||
def _process_result_output(self, result, msg):
|
||||
task_host = result._host.get_name()
|
||||
task_result = f"{task_host} {msg}"
|
||||
|
||||
if self._run_is_verbose(result):
|
||||
task_result = f"{task_host} {msg}: {self._dump_results(result._result, indent=4)}"
|
||||
return task_result
|
||||
|
||||
if self.delegated_vars:
|
||||
task_delegate_host = self.delegated_vars.get("ansible_host") or result._task.delegate_to or ""
|
||||
task_result = f"{task_host} -> {task_delegate_host} {msg}"
|
||||
|
||||
if result._result.get("msg") and result._result.get("msg") != "All items completed":
|
||||
task_result += f" | msg: {to_text(result._result.get('msg'))}"
|
||||
|
||||
if result._result.get("stdout"):
|
||||
task_result += f" | stdout: {result._result.get('stdout')}"
|
||||
|
||||
if result._result.get("stderr"):
|
||||
task_result += f" | stderr: {result._result.get('stderr')}"
|
||||
|
||||
return task_result
|
||||
|
||||
def v2_playbook_on_task_start(self, task, is_conditional):
|
||||
self._get_task_display_name(task)
|
||||
if self.task_display_name is not None:
|
||||
if task.check_mode and self.get_option("check_mode_markers"):
|
||||
self._display.display(f"{self.task_display_name} (check mode)...")
|
||||
else:
|
||||
self._display.display(f"{self.task_display_name}...")
|
||||
|
||||
def v2_playbook_on_handler_task_start(self, task):
|
||||
self._get_task_display_name(task)
|
||||
if self.task_display_name is not None:
|
||||
if task.check_mode and self.get_option("check_mode_markers"):
|
||||
self._display.display(f"{self.task_display_name} (via handler in check mode)... ")
|
||||
else:
|
||||
self._display.display(f"{self.task_display_name} (via handler)... ")
|
||||
|
||||
def v2_playbook_on_play_start(self, play):
|
||||
name = play.get_name().strip()
|
||||
if play.check_mode and self.get_option("check_mode_markers"):
|
||||
if name and play.hosts:
|
||||
msg = f"\n- {name} (in check mode) on hosts: {','.join(play.hosts)} -"
|
||||
else:
|
||||
msg = "- check mode -"
|
||||
else:
|
||||
if name and play.hosts:
|
||||
msg = f"\n- {name} on hosts: {','.join(play.hosts)} -"
|
||||
else:
|
||||
msg = "---"
|
||||
|
||||
self._display.display(msg)
|
||||
|
||||
def v2_runner_on_skipped(self, result, ignore_errors=False):
|
||||
if self.get_option("display_skipped_hosts"):
|
||||
self._preprocess_result(result)
|
||||
display_color = C.COLOR_SKIP
|
||||
msg = "skipped"
|
||||
|
||||
task_result = self._process_result_output(result, msg)
|
||||
self._display.display(f" {task_result}", display_color)
|
||||
else:
|
||||
return
|
||||
|
||||
def v2_runner_on_failed(self, result, ignore_errors=False):
|
||||
self._preprocess_result(result)
|
||||
display_color = C.COLOR_ERROR
|
||||
msg = "failed"
|
||||
item_value = self._get_item_label(result._result)
|
||||
if item_value:
|
||||
msg += f" | item: {item_value}"
|
||||
|
||||
task_result = self._process_result_output(result, msg)
|
||||
self._display.display(f" {task_result}", display_color, stderr=self.get_option("display_failed_stderr"))
|
||||
|
||||
def v2_runner_on_ok(self, result, msg="ok", display_color=C.COLOR_OK):
|
||||
self._preprocess_result(result)
|
||||
|
||||
result_was_changed = "changed" in result._result and result._result["changed"]
|
||||
if result_was_changed:
|
||||
msg = "done"
|
||||
item_value = self._get_item_label(result._result)
|
||||
if item_value:
|
||||
msg += f" | item: {item_value}"
|
||||
display_color = C.COLOR_CHANGED
|
||||
task_result = self._process_result_output(result, msg)
|
||||
self._display.display(f" {task_result}", display_color)
|
||||
elif self.get_option("display_ok_hosts"):
|
||||
task_result = self._process_result_output(result, msg)
|
||||
self._display.display(f" {task_result}", display_color)
|
||||
|
||||
def v2_runner_item_on_skipped(self, result):
|
||||
self.v2_runner_on_skipped(result)
|
||||
|
||||
def v2_runner_item_on_failed(self, result):
|
||||
self.v2_runner_on_failed(result)
|
||||
|
||||
def v2_runner_item_on_ok(self, result):
|
||||
self.v2_runner_on_ok(result)
|
||||
|
||||
def v2_runner_on_unreachable(self, result):
|
||||
self._preprocess_result(result)
|
||||
|
||||
msg = "unreachable"
|
||||
display_color = C.COLOR_UNREACHABLE
|
||||
task_result = self._process_result_output(result, msg)
|
||||
|
||||
self._display.display(f" {task_result}", display_color, stderr=self.get_option("display_failed_stderr"))
|
||||
|
||||
def v2_on_file_diff(self, result):
|
||||
if result._task.loop and "results" in result._result:
|
||||
for res in result._result["results"]:
|
||||
if "diff" in res and res["diff"] and res.get("changed", False):
|
||||
diff = self._get_diff(res["diff"])
|
||||
if diff:
|
||||
self._display.display(diff)
|
||||
elif "diff" in result._result and result._result["diff"] and result._result.get("changed", False):
|
||||
diff = self._get_diff(result._result["diff"])
|
||||
if diff:
|
||||
self._display.display(diff)
|
||||
|
||||
def v2_playbook_on_stats(self, stats):
|
||||
self._display.display("\n- Play recap -", screen_only=True)
|
||||
|
||||
hosts = sorted(stats.processed.keys())
|
||||
for h in hosts:
|
||||
# TODO how else can we display these?
|
||||
t = stats.summarize(h)
|
||||
|
||||
self._display.display(
|
||||
f" {hostcolor(h, t)} : {colorize('ok', t['ok'], C.COLOR_OK)} {colorize('changed', t['changed'], C.COLOR_CHANGED)} "
|
||||
f"{colorize('unreachable', t['unreachable'], C.COLOR_UNREACHABLE)} {colorize('failed', t['failures'], C.COLOR_ERROR)} "
|
||||
f"{colorize('rescued', t['rescued'], C.COLOR_OK)} {colorize('ignored', t['ignored'], C.COLOR_WARN)}",
|
||||
screen_only=True,
|
||||
)
|
||||
|
||||
self._display.display(
|
||||
f" {hostcolor(h, t, False)} : {colorize('ok', t['ok'], None)} {colorize('changed', t['changed'], None)} "
|
||||
f"{colorize('unreachable', t['unreachable'], None)} {colorize('failed', t['failures'], None)} {colorize('rescued', t['rescued'], None)} "
|
||||
f"{colorize('ignored', t['ignored'], None)}",
|
||||
log_only=True,
|
||||
)
|
||||
if stats.custom and self.get_option("show_custom_stats"):
|
||||
self._display.banner("CUSTOM STATS: ")
|
||||
# per host
|
||||
# TODO: come up with 'pretty format'
|
||||
for k in sorted(stats.custom.keys()):
|
||||
if k == "_run":
|
||||
continue
|
||||
stat_val = self._dump_results(stats.custom[k], indent=1).replace("\n", "")
|
||||
self._display.display(f"\t{k}: {stat_val}")
|
||||
|
||||
# print per run custom stats
|
||||
if "_run" in stats.custom:
|
||||
self._display.display("", screen_only=True)
|
||||
stat_val_run = self._dump_results(stats.custom["_run"], indent=1).replace("\n", "")
|
||||
self._display.display(f"\tRUN: {stat_val_run}")
|
||||
self._display.display("", screen_only=True)
|
||||
|
||||
def v2_playbook_on_no_hosts_matched(self):
|
||||
self._display.display(" No hosts found!", color=C.COLOR_DEBUG)
|
||||
|
||||
def v2_playbook_on_no_hosts_remaining(self):
|
||||
self._display.display(" Ran out of hosts!", color=C.COLOR_ERROR)
|
||||
|
||||
def v2_playbook_on_start(self, playbook):
|
||||
if context.CLIARGS["check"] and self.get_option("check_mode_markers"):
|
||||
self._display.display(f"Executing playbook {basename(playbook._file_name)} in check mode")
|
||||
else:
|
||||
self._display.display(f"Executing playbook {basename(playbook._file_name)}")
|
||||
|
||||
# show CLI arguments
|
||||
if self._display.verbosity > 3:
|
||||
if context.CLIARGS.get("args"):
|
||||
self._display.display(
|
||||
f"Positional arguments: {' '.join(context.CLIARGS['args'])}",
|
||||
color=C.COLOR_VERBOSE,
|
||||
screen_only=True,
|
||||
)
|
||||
|
||||
for argument in (a for a in context.CLIARGS if a != "args"):
|
||||
val = context.CLIARGS[argument]
|
||||
if val:
|
||||
self._display.vvvv(f"{argument}: {val}")
|
||||
|
||||
def v2_runner_retry(self, result):
|
||||
msg = f" Retrying... ({result._result['attempts']} of {result._result['retries']})"
|
||||
if self._run_is_verbose(result):
|
||||
msg += f"Result was: {self._dump_results(result._result)}"
|
||||
self._display.display(msg, color=C.COLOR_DEBUG)
|
||||
+233
@@ -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
|
||||
+107
@@ -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
|
||||
+358
@@ -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
|
||||
+88
@@ -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")
|
||||
+207
@@ -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
|
||||
+154
@@ -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
|
||||
+125
@@ -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
|
||||
+202
@@ -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
|
||||
+96
@@ -0,0 +1,96 @@
|
||||
# Copyright (c) 2017-present Alibaba Group Holding Limited. He Guimin <heguimin36@163.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
|
||||
|
||||
# Note that this doc fragment is **PRIVATE** to the collection. It can have breaking changes at any time.
|
||||
# Do not use this from other collections or standalone plugins/modules!
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
class ModuleDocFragment:
|
||||
# Alicloud only documentation fragment
|
||||
DOCUMENTATION = r"""
|
||||
options:
|
||||
alicloud_access_key:
|
||||
description:
|
||||
- Alibaba Cloud access key. If not set then the value of environment variable E(ALICLOUD_ACCESS_KEY), E(ALICLOUD_ACCESS_KEY_ID)
|
||||
is used instead.
|
||||
aliases: ['access_key_id', 'access_key']
|
||||
type: str
|
||||
alicloud_secret_key:
|
||||
description:
|
||||
- Alibaba Cloud secret key. If not set then the value of environment variable E(ALICLOUD_SECRET_KEY), E(ALICLOUD_SECRET_ACCESS_KEY)
|
||||
is used instead.
|
||||
aliases: ['secret_access_key', 'secret_key']
|
||||
type: str
|
||||
alicloud_region:
|
||||
description:
|
||||
- The Alibaba Cloud region to use. If not specified then the value of environment variable E(ALICLOUD_REGION), E(ALICLOUD_REGION_ID)
|
||||
is used instead.
|
||||
aliases: ['region', 'region_id']
|
||||
required: true
|
||||
type: str
|
||||
alicloud_security_token:
|
||||
description:
|
||||
- The Alibaba Cloud security token. If not specified then the value of environment variable E(ALICLOUD_SECURITY_TOKEN)
|
||||
is used instead.
|
||||
aliases: ['security_token']
|
||||
type: str
|
||||
alicloud_assume_role:
|
||||
description:
|
||||
- If provided with a role ARN, Ansible attempts to assume this role using the supplied credentials.
|
||||
- The nested assume_role block supports C(alicloud_assume_role_arn), C(alicloud_assume_role_session_name), C(alicloud_assume_role_session_expiration)
|
||||
and C(alicloud_assume_role_policy).
|
||||
type: dict
|
||||
aliases: ['assume_role']
|
||||
alicloud_assume_role_arn:
|
||||
description:
|
||||
- The Alibaba Cloud C(role_arn). The ARN of the role to assume. If ARN is set to an empty string, it does not perform
|
||||
role switching. It supports environment variable E(ALICLOUD_ASSUME_ROLE_ARN). Ansible executes with provided credentials.
|
||||
aliases: ['assume_role_arn']
|
||||
type: str
|
||||
alicloud_assume_role_session_name:
|
||||
description:
|
||||
- The Alibaba Cloud session_name. The session name to use when assuming the role. If omitted, 'ansible' is passed to
|
||||
the AssumeRole call as session name. It supports environment variable E(ALICLOUD_ASSUME_ROLE_SESSION_NAME).
|
||||
aliases: ['assume_role_session_name']
|
||||
type: str
|
||||
alicloud_assume_role_session_expiration:
|
||||
description:
|
||||
- The Alibaba Cloud C(session_expiration). The time after which the established session for assuming role expires. Valid
|
||||
value range 900-3600 seconds. Default to 3600 (in this case Alicloud use own default value). It supports environment
|
||||
variable E(ALICLOUD_ASSUME_ROLE_SESSION_EXPIRATION).
|
||||
aliases: ['assume_role_session_expiration']
|
||||
type: int
|
||||
ecs_role_name:
|
||||
description:
|
||||
- The RAM Role Name attached on an ECS instance for API operations. You can retrieve this from the 'Access Control' section
|
||||
of the Alibaba Cloud console.
|
||||
- If you are running Ansible from an ECS instance with RAM Instance using RAM Role, Ansible just accesses the metadata
|
||||
U(http://100.100.100.200/latest/meta-data/ram/security-credentials/<ecs_role_name>) to obtain the STS credential.
|
||||
This is a preferred approach over any other when running in ECS as you can avoid hard coding credentials. Instead
|
||||
these are leased on-the-fly by Ansible which reduces the chance of leakage.
|
||||
aliases: ['role_name']
|
||||
type: str
|
||||
profile:
|
||||
description:
|
||||
- This is the Alicloud profile name as set in the shared credentials file. It can also be sourced from the E(ALICLOUD_PROFILE)
|
||||
environment variable.
|
||||
type: str
|
||||
shared_credentials_file:
|
||||
description:
|
||||
- This is the path to the shared credentials file. It can also be sourced from the E(ALICLOUD_SHARED_CREDENTIALS_FILE)
|
||||
environment variable.
|
||||
- If this is not set and a profile is specified, C(~/.aliyun/config.json) is used.
|
||||
type: str
|
||||
author:
|
||||
- "He Guimin (@xiaozhu36)"
|
||||
notes:
|
||||
- If parameters are not set within the module, the following environment variables can be used in decreasing order of precedence
|
||||
E(ALICLOUD_ACCESS_KEY) or E(ALICLOUD_ACCESS_KEY_ID), E(ALICLOUD_SECRET_KEY) or E(ALICLOUD_SECRET_ACCESS_KEY), E(ALICLOUD_REGION)
|
||||
or E(ALICLOUD_REGION_ID), E(ALICLOUD_SECURITY_TOKEN), E(ALICLOUD_ECS_ROLE_NAME), E(ALICLOUD_SHARED_CREDENTIALS_FILE),
|
||||
E(ALICLOUD_PROFILE), E(ALICLOUD_ASSUME_ROLE_ARN), E(ALICLOUD_ASSUME_ROLE_SESSION_NAME), E(ALICLOUD_ASSUME_ROLE_SESSION_EXPIRATION).
|
||||
- E(ALICLOUD_REGION) or E(ALICLOUD_REGION_ID) can typically be used to specify the Alicloud region, when required, but
|
||||
this can also be configured in the footmark config file.
|
||||
"""
|
||||
+92
@@ -0,0 +1,92 @@
|
||||
# Copyright (c) Ansible Project
|
||||
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
# Note that this doc fragment is **PRIVATE** to the collection. It can have breaking changes at any time.
|
||||
# Do not use this from other collections or standalone plugins/modules!
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
class ModuleDocFragment:
|
||||
# Standard documentation fragment
|
||||
DOCUMENTATION = r"""
|
||||
options: {}
|
||||
attributes:
|
||||
check_mode:
|
||||
description: Can run in C(check_mode) and return changed status prediction without modifying target.
|
||||
diff_mode:
|
||||
description: Returns details on what has changed (or possibly needs changing in C(check_mode)), when in diff mode.
|
||||
"""
|
||||
|
||||
PLATFORM = r"""
|
||||
options: {}
|
||||
attributes:
|
||||
platform:
|
||||
description: Target OS/families that can be operated against.
|
||||
support: N/A
|
||||
"""
|
||||
|
||||
# Should be used together with the standard fragment
|
||||
INFO_MODULE = r"""
|
||||
options: {}
|
||||
attributes:
|
||||
check_mode:
|
||||
support: full
|
||||
details:
|
||||
- This action does not modify state.
|
||||
diff_mode:
|
||||
support: N/A
|
||||
details:
|
||||
- This action does not modify state.
|
||||
"""
|
||||
|
||||
CONN = r"""
|
||||
options: {}
|
||||
attributes:
|
||||
become:
|
||||
description: Is usable alongside C(become) keywords.
|
||||
connection:
|
||||
description: Uses the target's configured connection information to execute code on it.
|
||||
delegation:
|
||||
description: Can be used in conjunction with C(delegate_to) and related keywords.
|
||||
"""
|
||||
|
||||
FACTS = r"""
|
||||
options: {}
|
||||
attributes:
|
||||
facts:
|
||||
description: Action returns an C(ansible_facts) dictionary that updates existing host facts.
|
||||
"""
|
||||
|
||||
# Should be used together with the standard fragment and the FACTS fragment
|
||||
FACTS_MODULE = r"""
|
||||
options: {}
|
||||
attributes:
|
||||
check_mode:
|
||||
support: full
|
||||
details:
|
||||
- This action does not modify state.
|
||||
diff_mode:
|
||||
support: N/A
|
||||
details:
|
||||
- This action does not modify state.
|
||||
facts:
|
||||
support: full
|
||||
"""
|
||||
|
||||
FILES = r"""
|
||||
options: {}
|
||||
attributes:
|
||||
safe_file_operations:
|
||||
description: Uses Ansible's strict file operation functions to ensure proper permissions and avoid data corruption.
|
||||
"""
|
||||
|
||||
FLOW = r"""
|
||||
options: {}
|
||||
attributes:
|
||||
action:
|
||||
description: Indicates this has a corresponding action plugin so some parts of the options can be executed on the controller.
|
||||
async:
|
||||
description: Supports being used with the C(async) keyword.
|
||||
"""
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
# Copyright (c) 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
|
||||
|
||||
# Note that this doc fragment is **PRIVATE** to the collection. It can have breaking changes at any time.
|
||||
# Do not use this from other collections or standalone plugins/modules!
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
class ModuleDocFragment:
|
||||
# Standard files documentation fragment
|
||||
DOCUMENTATION = r"""
|
||||
options:
|
||||
api_url:
|
||||
description:
|
||||
- The resolvable endpoint for the API.
|
||||
type: str
|
||||
api_username:
|
||||
description:
|
||||
- The username to use for authentication against the API.
|
||||
type: str
|
||||
api_password:
|
||||
description:
|
||||
- The password to use for authentication against the API.
|
||||
type: str
|
||||
validate_certs:
|
||||
description:
|
||||
- Whether or not to validate SSL certs when supplying a HTTPS endpoint.
|
||||
type: bool
|
||||
default: true
|
||||
"""
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
# Copyright (c) 2019, Evgeniy Krysanov <evgeniy.krysanov@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
|
||||
|
||||
# Note that this doc fragment is **PRIVATE** to the collection. It can have breaking changes at any time.
|
||||
# Do not use this from other collections or standalone plugins/modules!
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
class ModuleDocFragment:
|
||||
# Standard documentation fragment
|
||||
DOCUMENTATION = r"""
|
||||
options:
|
||||
client_id:
|
||||
description:
|
||||
- The OAuth consumer key.
|
||||
- If not set the environment variable E(BITBUCKET_CLIENT_ID) is used.
|
||||
type: str
|
||||
client_secret:
|
||||
description:
|
||||
- The OAuth consumer secret.
|
||||
- If not set the environment variable E(BITBUCKET_CLIENT_SECRET) is used.
|
||||
type: str
|
||||
user:
|
||||
description:
|
||||
- The username.
|
||||
- If not set the environment variable E(BITBUCKET_USERNAME) is used.
|
||||
- O(ignore:username) is an alias of O(user) since community.general 6.0.0. It was an alias of O(workspace) before.
|
||||
type: str
|
||||
version_added: 4.0.0
|
||||
aliases: [username]
|
||||
password:
|
||||
description:
|
||||
- The App password.
|
||||
- If not set the environment variable E(BITBUCKET_PASSWORD) is used.
|
||||
type: str
|
||||
version_added: 4.0.0
|
||||
notes:
|
||||
- Bitbucket OAuth consumer key and secret can be obtained from Bitbucket profile -> Settings -> Access Management -> OAuth.
|
||||
- Bitbucket App password can be created from Bitbucket profile -> Personal Settings -> App passwords.
|
||||
- If both OAuth and Basic Auth credentials are passed, OAuth credentials take precedence.
|
||||
"""
|
||||
+75
@@ -0,0 +1,75 @@
|
||||
# Copyright (c) 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
|
||||
|
||||
# Note that this doc fragment is **PRIVATE** to the collection. It can have breaking changes at any time.
|
||||
# Do not use this from other collections or standalone plugins/modules!
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
class ModuleDocFragment:
|
||||
# Common parameters for Consul modules
|
||||
DOCUMENTATION = r"""
|
||||
options:
|
||||
url:
|
||||
description:
|
||||
- The address of the Consul agent, in the V(host:port) or V(scheme://host:port) form. The scheme and the port are
|
||||
optional, the host is not.
|
||||
- O(host), O(port) and O(scheme) take precedence over the components of this option.
|
||||
- If unset, the value of the E(CONSUL_HTTP_ADDR) environment variable is used when set. An address these modules
|
||||
cannot use, a C(unix://) socket for example, makes the module fail, unless O(host), O(port) and O(scheme) are all
|
||||
set, in which case the address is not consulted at all.
|
||||
type: str
|
||||
version_added: 13.4.0
|
||||
host:
|
||||
description:
|
||||
- Host of the Consul agent.
|
||||
- If unset, the host component of O(url) is used, and V(localhost) when O(url) is not set either.
|
||||
type: str
|
||||
port:
|
||||
type: int
|
||||
description:
|
||||
- The port on which the consul agent is running.
|
||||
- If unset, the port component of O(url) is used, and V(8500) when that does not specify one either.
|
||||
scheme:
|
||||
description:
|
||||
- The protocol scheme on which the Consul agent is running.
|
||||
- If unset, a C(true) value in the E(CONSUL_HTTP_SSL) environment variable selects V(https), otherwise the scheme
|
||||
component of O(url) is used, and V(http) when that does not specify one either. A C(false) E(CONSUL_HTTP_SSL) does
|
||||
not downgrade an V(https) O(url).
|
||||
type: str
|
||||
validate_certs:
|
||||
type: bool
|
||||
description:
|
||||
- Whether to verify the TLS certificate of the Consul agent.
|
||||
- If unset, the value of the E(CONSUL_HTTP_SSL_VERIFY) environment variable is used when set.
|
||||
This is supported since community.general 13.4.0.
|
||||
default: true
|
||||
ca_path:
|
||||
description:
|
||||
- The CA bundle to use for https connections.
|
||||
- If unset, the value of the E(CONSUL_CACERT) environment variable is used when set.
|
||||
This is supported since community.general 13.4.0.
|
||||
type: str
|
||||
"""
|
||||
|
||||
TOKEN = r"""
|
||||
options:
|
||||
token:
|
||||
description:
|
||||
- The token to use for authorization.
|
||||
- If unset, the value of the E(CONSUL_HTTP_TOKEN) environment variable is used.
|
||||
This is supported since community.general 13.4.0.
|
||||
type: str
|
||||
"""
|
||||
|
||||
ACTIONGROUP_CONSUL = r"""
|
||||
options: {}
|
||||
attributes:
|
||||
action_group:
|
||||
description: Use C(group/community.general.consul) in C(module_defaults) to set defaults for this module.
|
||||
support: full
|
||||
membership:
|
||||
- community.general.consul
|
||||
"""
|
||||
+96
@@ -0,0 +1,96 @@
|
||||
# Copyright (c) 2024, 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
|
||||
|
||||
# Note that this doc fragment is **PRIVATE** to the collection. It can have breaking changes at any time.
|
||||
# Do not use this from other collections or standalone plugins/modules!
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
class ModuleDocFragment:
|
||||
DOCUMENTATION = r"""
|
||||
options:
|
||||
venv:
|
||||
description:
|
||||
- Use the Python interpreter from this virtual environment.
|
||||
- Pass the path to the root of the virtualenv, not the C(bin/) directory nor the C(python) executable.
|
||||
type: path
|
||||
settings:
|
||||
description:
|
||||
- Specifies the settings module to use.
|
||||
- The value is passed as is to the C(--settings) argument in C(django-admin).
|
||||
type: str
|
||||
required: true
|
||||
pythonpath:
|
||||
description:
|
||||
- Adds the given filesystem path to the Python import search path.
|
||||
- The value is passed as is to the C(--pythonpath) argument in C(django-admin).
|
||||
type: path
|
||||
traceback:
|
||||
description:
|
||||
- Provides a full stack trace in the output when a C(CommandError) is raised.
|
||||
type: bool
|
||||
verbosity:
|
||||
description:
|
||||
- Specifies the amount of notification and debug information in the output of C(django-admin).
|
||||
type: int
|
||||
choices: [0, 1, 2, 3]
|
||||
|
||||
|
||||
notes:
|
||||
- The C(django-admin) command is always executed using the C(C) locale, and the option C(--no-color) is always passed.
|
||||
seealso:
|
||||
- name: django-admin and manage.py in official Django documentation
|
||||
description: >-
|
||||
Refer to this documentation for the builtin commands and options of C(django-admin). Please make sure that you select
|
||||
the right version of Django in the version selector on that page.
|
||||
link: https://docs.djangoproject.com/en/5.0/ref/django-admin/
|
||||
"""
|
||||
|
||||
SKIP_CHECKS = r"""
|
||||
options:
|
||||
skip_checks:
|
||||
description:
|
||||
- Skips running system checks prior to running the command.
|
||||
type: bool
|
||||
"""
|
||||
|
||||
DEPRECATED_SKIP_CHECKS = r"""
|
||||
options:
|
||||
skip_checks:
|
||||
description:
|
||||
- This option is ignored, because the underlying C(django-admin) command does not support it.
|
||||
- This option has been deprecated and will be removed in community.general 16.0.0.
|
||||
type: bool
|
||||
"""
|
||||
|
||||
DATABASE = r"""
|
||||
options:
|
||||
database:
|
||||
description:
|
||||
- Specify the database to be used.
|
||||
type: str
|
||||
default: default
|
||||
"""
|
||||
|
||||
DATA = r"""
|
||||
options:
|
||||
excludes:
|
||||
description:
|
||||
- Applications or models to be excluded.
|
||||
- Format must be either V(app_label) or V(app_label.ModelName).
|
||||
type: list
|
||||
elements: str
|
||||
format:
|
||||
description:
|
||||
- Serialization format of the output data.
|
||||
type: str
|
||||
default: json
|
||||
choices: [xml, json, jsonl, yaml]
|
||||
notes:
|
||||
- As it is now, the module is B(not idempotent). Ensuring idempotency for this case can be a bit tricky, because it would
|
||||
amount to ensuring beforehand that all the data in the fixture file is already in the database, which is not a trivial feat.
|
||||
Unfortunately, neither C(django loaddata) nor C(django dumpdata) have a C(--dry-run) option, so the only way to know whether
|
||||
there is a change or not is to actually load or dump the data.
|
||||
"""
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
# Copyright (c) 2018, Luca Lorenzetto (@remix_tj) <lorenzetto.luca@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
|
||||
|
||||
# Note that this doc fragment is **PRIVATE** to the collection. It can have breaking changes at any time.
|
||||
# Do not use this from other collections or standalone plugins/modules!
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
class ModuleDocFragment:
|
||||
# Documentation fragment for VNX (emc_vnx)
|
||||
EMC_VNX = r"""
|
||||
options:
|
||||
sp_address:
|
||||
description:
|
||||
- Address of the SP of target/secondary storage.
|
||||
type: str
|
||||
required: true
|
||||
sp_user:
|
||||
description:
|
||||
- Username for accessing SP.
|
||||
type: str
|
||||
default: sysadmin
|
||||
sp_password:
|
||||
description:
|
||||
- password for accessing SP.
|
||||
type: str
|
||||
default: sysadmin
|
||||
requirements:
|
||||
- An EMC VNX Storage device.
|
||||
- storops (0.5.10 or greater). Install using C(pip install storops).
|
||||
notes:
|
||||
- The modules prefixed with C(emc_vnx) are built to support the EMC VNX storage platform.
|
||||
"""
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
# Copyright (c) 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
|
||||
|
||||
# Note that this doc fragment is **PRIVATE** to the collection. It can have breaking changes at any time.
|
||||
# Do not use this from other collections or standalone plugins/modules!
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
class ModuleDocFragment:
|
||||
# Standard files documentation fragment
|
||||
DOCUMENTATION = r"""
|
||||
requirements:
|
||||
- requests (Python library U(https://pypi.org/project/requests/))
|
||||
|
||||
options:
|
||||
api_token:
|
||||
description:
|
||||
- GitLab access token with API permissions.
|
||||
type: str
|
||||
api_oauth_token:
|
||||
description:
|
||||
- GitLab OAuth token for logging in.
|
||||
type: str
|
||||
version_added: 4.2.0
|
||||
api_job_token:
|
||||
description:
|
||||
- GitLab CI job token for logging in.
|
||||
type: str
|
||||
version_added: 4.2.0
|
||||
ca_path:
|
||||
description:
|
||||
- The CA certificates bundle to use to verify GitLab server certificate.
|
||||
type: str
|
||||
version_added: 8.1.0
|
||||
"""
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
# Copyright (c) 2018, Hewlett Packard Enterprise Development LP
|
||||
# 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
|
||||
|
||||
# Note that this doc fragment is **PRIVATE** to the collection. It can have breaking changes at any time.
|
||||
# Do not use this from other collections or standalone plugins/modules!
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
class ModuleDocFragment:
|
||||
# HPE 3PAR doc fragment
|
||||
DOCUMENTATION = r"""
|
||||
options:
|
||||
storage_system_ip:
|
||||
description:
|
||||
- The storage system IP address.
|
||||
type: str
|
||||
required: true
|
||||
storage_system_password:
|
||||
description:
|
||||
- The storage system password.
|
||||
type: str
|
||||
required: true
|
||||
storage_system_username:
|
||||
description:
|
||||
- The storage system user name.
|
||||
type: str
|
||||
required: true
|
||||
|
||||
requirements:
|
||||
- hpe3par_sdk >= 1.0.2. Install using C(pip install hpe3par_sdk).
|
||||
- WSAPI service should be enabled on the 3PAR storage array.
|
||||
notes:
|
||||
"""
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
# Copyright (c) 2018, Huawei Inc.
|
||||
# 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
|
||||
|
||||
# Note that this doc fragment is **PRIVATE** to the collection. It can have breaking changes at any time.
|
||||
# Do not use this from other collections or standalone plugins/modules!
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
class ModuleDocFragment:
|
||||
# HWC doc fragment.
|
||||
DOCUMENTATION = r"""
|
||||
options:
|
||||
identity_endpoint:
|
||||
description:
|
||||
- The Identity authentication URL.
|
||||
type: str
|
||||
required: true
|
||||
user:
|
||||
description:
|
||||
- The user name to login with.
|
||||
- Currently only user names are supported, and not user IDs.
|
||||
type: str
|
||||
required: true
|
||||
password:
|
||||
description:
|
||||
- The password to login with.
|
||||
type: str
|
||||
required: true
|
||||
domain:
|
||||
description:
|
||||
- The name of the Domain to scope to (Identity v3).
|
||||
- Currently only domain names are supported, and not domain IDs.
|
||||
type: str
|
||||
required: true
|
||||
project:
|
||||
description:
|
||||
- The name of the Tenant (Identity v2) or Project (Identity v3).
|
||||
- Currently only project names are supported, and not project IDs.
|
||||
type: str
|
||||
required: true
|
||||
region:
|
||||
description:
|
||||
- The region to which the project belongs.
|
||||
type: str
|
||||
id:
|
||||
description:
|
||||
- The ID of resource to be managed.
|
||||
type: str
|
||||
notes:
|
||||
- For authentication, you can set identity_endpoint using the E(ANSIBLE_HWC_IDENTITY_ENDPOINT) environment variable.
|
||||
- For authentication, you can set user using the E(ANSIBLE_HWC_USER) environment variable.
|
||||
- For authentication, you can set password using the E(ANSIBLE_HWC_PASSWORD) environment variable.
|
||||
- For authentication, you can set domain using the E(ANSIBLE_HWC_DOMAIN) environment variable.
|
||||
- For authentication, you can set project using the E(ANSIBLE_HWC_PROJECT) environment variable.
|
||||
- For authentication, you can set region using the E(ANSIBLE_HWC_REGION) environment variable.
|
||||
- Environment variables values are only used when the playbook values are not set.
|
||||
"""
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
# Copyright (c) 2018, IBM CORPORATION
|
||||
# Author(s): Tzur Eliyahu <tzure@il.ibm.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
|
||||
|
||||
# Note that this doc fragment is **PRIVATE** to the collection. It can have breaking changes at any time.
|
||||
# Do not use this from other collections or standalone plugins/modules!
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
class ModuleDocFragment:
|
||||
# ibm_storage documentation fragment
|
||||
DOCUMENTATION = r"""
|
||||
options:
|
||||
username:
|
||||
description:
|
||||
- Management user on the Spectrum Accelerate storage system.
|
||||
type: str
|
||||
required: true
|
||||
password:
|
||||
description:
|
||||
- Password for username on the Spectrum Accelerate storage system.
|
||||
type: str
|
||||
required: true
|
||||
endpoints:
|
||||
description:
|
||||
- The hostname or management IP of Spectrum Accelerate storage system.
|
||||
type: str
|
||||
required: true
|
||||
notes:
|
||||
- This module requires pyxcli Python library. Use C(pip install pyxcli) in order to get pyxcli.
|
||||
requirements:
|
||||
- pyxcli
|
||||
"""
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
# SPDX-FileCopyrightText: 2026 Christoph Fiehe <christoph.fiehe@gmail.com>
|
||||
|
||||
# Note that this doc fragment is **PRIVATE** to the collection. It can have breaking changes at any time.
|
||||
# Do not use this from other collections or standalone plugins/modules!
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
class ModuleDocFragment:
|
||||
# Use together with ansible.builtin.url and icinga2_argument_spec from
|
||||
# ansible_collections.community.general.plugins.module_utils._icinga2
|
||||
DOCUMENTATION = r"""
|
||||
options:
|
||||
url:
|
||||
description:
|
||||
- URL of the Icinga 2 REST API.
|
||||
type: str
|
||||
required: true
|
||||
ca_path:
|
||||
description:
|
||||
- CA certificates bundle to use to verify the Icinga 2 server certificate.
|
||||
type: path
|
||||
timeout:
|
||||
description:
|
||||
- How long to wait for the server to send data before giving up.
|
||||
type: int
|
||||
default: 10
|
||||
"""
|
||||
+85
@@ -0,0 +1,85 @@
|
||||
# Copyright (c) 2017, Ansible Project
|
||||
# Copyright (c) 2017, Abhijeet Kasurde (akasurde@redhat.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
|
||||
|
||||
# Note that this doc fragment is **PRIVATE** to the collection. It can have breaking changes at any time.
|
||||
# Do not use this from other collections or standalone plugins/modules!
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
class ModuleDocFragment:
|
||||
# Parameters for influxdb modules
|
||||
DOCUMENTATION = r"""
|
||||
options:
|
||||
hostname:
|
||||
description:
|
||||
- The hostname or IP address on which InfluxDB server is listening.
|
||||
type: str
|
||||
default: localhost
|
||||
username:
|
||||
description:
|
||||
- Username that is used to authenticate against InfluxDB server.
|
||||
type: str
|
||||
default: root
|
||||
aliases: [login_username]
|
||||
password:
|
||||
description:
|
||||
- Password that is used to authenticate against InfluxDB server.
|
||||
type: str
|
||||
default: root
|
||||
aliases: [login_password]
|
||||
port:
|
||||
description:
|
||||
- The port on which InfluxDB server is listening.
|
||||
type: int
|
||||
default: 8086
|
||||
path:
|
||||
description:
|
||||
- The path on which InfluxDB server is accessible.
|
||||
- Only available when using python-influxdb >= 5.1.0.
|
||||
type: str
|
||||
default: ''
|
||||
version_added: '0.2.0'
|
||||
validate_certs:
|
||||
description:
|
||||
- If set to V(false), the SSL certificates are not validated.
|
||||
- This should only be set to V(false) when used on personally controlled sites using self-signed certificates.
|
||||
type: bool
|
||||
default: true
|
||||
ssl:
|
||||
description:
|
||||
- Use https instead of http to connect to InfluxDB server.
|
||||
type: bool
|
||||
default: false
|
||||
timeout:
|
||||
description:
|
||||
- Number of seconds Requests waits for client to establish a connection.
|
||||
type: int
|
||||
retries:
|
||||
description:
|
||||
- Number of retries client performs before aborting.
|
||||
- V(0) indicates try until success.
|
||||
- Only available when using C(python-influxdb) >= 4.1.0.
|
||||
type: int
|
||||
default: 3
|
||||
use_udp:
|
||||
description:
|
||||
- Use UDP to connect to InfluxDB server.
|
||||
type: bool
|
||||
default: false
|
||||
udp_port:
|
||||
description:
|
||||
- UDP port to connect to InfluxDB server.
|
||||
type: int
|
||||
default: 4444
|
||||
proxies:
|
||||
description:
|
||||
- HTTP(S) proxy to use for Requests to connect to InfluxDB server.
|
||||
type: dict
|
||||
default: {}
|
||||
notes:
|
||||
- Please note that this module relies on the C(influxdb) Python package, which is no longer active.
|
||||
Moreover, it is only compatible with InfluxDB 1.x, meaning this module will not work with InfluxDB 2.x or 3.x.
|
||||
"""
|
||||
+85
@@ -0,0 +1,85 @@
|
||||
# Copyright (c) 2017-18, Ansible Project
|
||||
# Copyright (c) 2017-18, Abhijeet Kasurde (akasurde@redhat.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
|
||||
|
||||
# Note that this doc fragment is **PRIVATE** to the collection. It can have breaking changes at any time.
|
||||
# Do not use this from other collections or standalone plugins/modules!
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
class ModuleDocFragment:
|
||||
# Parameters for FreeIPA/IPA modules
|
||||
DOCUMENTATION = r"""
|
||||
options:
|
||||
ipa_port:
|
||||
description:
|
||||
- Port of FreeIPA / IPA server.
|
||||
- If the value is not specified in the task, the value of environment variable E(IPA_PORT) is used instead.
|
||||
- If both the environment variable E(IPA_PORT) and the value are not specified in the task, then default value is set.
|
||||
type: int
|
||||
default: 443
|
||||
ipa_host:
|
||||
description:
|
||||
- IP or hostname of IPA server.
|
||||
- If the value is not specified in the task, the value of environment variable E(IPA_HOST) is used instead.
|
||||
- If both the environment variable E(IPA_HOST) and the value are not specified in the task, then DNS is used to try
|
||||
to discover the FreeIPA server.
|
||||
- The relevant entry needed in FreeIPA is the C(ipa-ca) entry.
|
||||
- If neither the DNS entry, nor the environment E(IPA_HOST), nor the value are available in the task, then the default
|
||||
value is used.
|
||||
type: str
|
||||
default: ipa.example.com
|
||||
ipa_user:
|
||||
description:
|
||||
- Administrative account used on IPA server.
|
||||
- If the value is not specified in the task, the value of environment variable E(IPA_USER) is used instead.
|
||||
- If both the environment variable E(IPA_USER) and the value are not specified in the task, then default value is set.
|
||||
type: str
|
||||
default: admin
|
||||
ipa_pass:
|
||||
description:
|
||||
- Password of administrative user.
|
||||
- If the value is not specified in the task, the value of environment variable E(IPA_PASS) is used instead.
|
||||
- Note that if the C(urllib_gssapi) library is available, it is possible to use GSSAPI to authenticate to FreeIPA.
|
||||
- If the environment variable E(KRB5CCNAME) is available, the module uses this Kerberos credentials cache to authenticate
|
||||
to the FreeIPA server.
|
||||
- If the environment variable E(KRB5_CLIENT_KTNAME) is available, and E(KRB5CCNAME) is not; the module uses this Kerberos
|
||||
keytab to authenticate.
|
||||
- If GSSAPI is not available, the usage of O(ipa_pass) is required.
|
||||
type: str
|
||||
ipa_prot:
|
||||
description:
|
||||
- Protocol used by IPA server.
|
||||
- If the value is not specified in the task, the value of environment variable E(IPA_PROT) is used instead.
|
||||
- If both the environment variable E(IPA_PROT) and the value are not specified in the task, then default value is set.
|
||||
type: str
|
||||
choices: [http, https]
|
||||
default: https
|
||||
validate_certs:
|
||||
description:
|
||||
- This only applies if O(ipa_prot) is V(https).
|
||||
- If set to V(false), the SSL certificates are not validated.
|
||||
- This should only be set to V(false) when used on personally controlled sites using self-signed certificates.
|
||||
type: bool
|
||||
default: true
|
||||
ipa_timeout:
|
||||
description:
|
||||
- Specifies idle timeout (in seconds) for the connection.
|
||||
- For bulk operations, you may want to increase this in order to avoid timeout from IPA server.
|
||||
- If the value is not specified in the task, the value of environment variable E(IPA_TIMEOUT) is used instead.
|
||||
- If both the environment variable E(IPA_TIMEOUT) and the value are not specified in the task, then default value is
|
||||
set.
|
||||
type: int
|
||||
default: 10
|
||||
"""
|
||||
|
||||
CONNECTION_NOTES = r"""
|
||||
options: {}
|
||||
notes:
|
||||
- This module uses JSON-RPC over HTTP(S) to communicate with the FreeIPA server.
|
||||
If you need to enroll the managed node into FreeIPA realm, you might want to consider using the collection
|
||||
L(freeipa.ansible_freeipa, https://galaxy.ansible.com/ui/repo/published/freeipa/ansible_freeipa/), but shell access to one
|
||||
node from the realm is required to manage the deployment.
|
||||
"""
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
# Copyright (c) 2026, Dexter Le <dextersydney2001@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
|
||||
|
||||
# Note that this doc fragment is **PRIVATE** to the collection. It can have breaking changes at any time.
|
||||
# Do not use this from other collections or standalone plugins/modules!
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
class ModuleDocFragment:
|
||||
# Common parameters for Kopia modules
|
||||
DOCUMENTATION = r"""
|
||||
options:
|
||||
password:
|
||||
description:
|
||||
- Repository password used to encrypt and decrypt repository contents.
|
||||
type: str
|
||||
config:
|
||||
description:
|
||||
- Path to the Kopia config file for this repository connection.
|
||||
- Defaults to the Kopia default config path when not set.
|
||||
type: path
|
||||
"""
|
||||
+106
@@ -0,0 +1,106 @@
|
||||
# Copyright (c) 2016, Peter Sagerson <psagers@ignorare.net>
|
||||
# Copyright (c) 2016, Jiri Tyr <jiri.tyr@gmail.com>
|
||||
# Copyright (c) 2017-2018 Keller Fuchs (@KellerFuchs) <kellerfuchs@hashbang.sh>
|
||||
# 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
|
||||
|
||||
# Note that this doc fragment is **PRIVATE** to the collection. It can have breaking changes at any time.
|
||||
# Do not use this from other collections or standalone plugins/modules!
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
class ModuleDocFragment:
|
||||
# Standard LDAP documentation fragment
|
||||
DOCUMENTATION = r"""
|
||||
notes:
|
||||
- The default authentication settings attempt to use a SASL EXTERNAL bind over a UNIX domain socket. This works well with
|
||||
the default Ubuntu install for example, which includes a C(cn=peercred,cn=external,cn=auth) ACL rule allowing root to
|
||||
modify the server configuration. If you need to use a simple bind to access your server, pass the credentials in O(bind_dn)
|
||||
and O(bind_pw).
|
||||
options:
|
||||
bind_dn:
|
||||
description:
|
||||
- A DN to bind with. Try to use a SASL bind with the EXTERNAL mechanism as default when this parameter is omitted.
|
||||
- Use an anonymous bind if the parameter is blank.
|
||||
type: str
|
||||
bind_pw:
|
||||
description:
|
||||
- The password to use with O(bind_dn).
|
||||
type: str
|
||||
default: ''
|
||||
ca_path:
|
||||
description:
|
||||
- Set the path to PEM file with CA certs.
|
||||
type: path
|
||||
version_added: "6.5.0"
|
||||
client_cert:
|
||||
type: path
|
||||
description:
|
||||
- PEM formatted certificate chain file to be used for SSL client authentication.
|
||||
- Required if O(client_key) is defined.
|
||||
version_added: "7.1.0"
|
||||
client_key:
|
||||
type: path
|
||||
description:
|
||||
- PEM formatted file that contains your private key to be used for SSL client authentication.
|
||||
- Required if O(client_cert) is defined.
|
||||
version_added: "7.1.0"
|
||||
dn:
|
||||
required: true
|
||||
description:
|
||||
- The DN of the entry to add or remove.
|
||||
type: str
|
||||
referrals_chasing:
|
||||
choices: [disabled, anonymous]
|
||||
default: anonymous
|
||||
type: str
|
||||
description:
|
||||
- Set the referrals chasing behavior.
|
||||
- V(anonymous) follow referrals anonymously. This is the default behavior.
|
||||
- V(disabled) disable referrals chasing. This sets C(OPT_REFERRALS) to off.
|
||||
version_added: 2.0.0
|
||||
server_uri:
|
||||
description:
|
||||
- The O(server_uri) parameter may be a comma- or whitespace-separated list of URIs containing only the schema, the host,
|
||||
and the port fields.
|
||||
- The default value lets the underlying LDAP client library look for a UNIX domain socket in its default location.
|
||||
- Note that when using multiple URIs you cannot determine to which URI your client gets connected.
|
||||
- For URIs containing additional fields, particularly when using commas, behavior is undefined.
|
||||
type: str
|
||||
default: ldapi:///
|
||||
start_tls:
|
||||
description:
|
||||
- Use the START_TLS LDAP extension if set to V(true).
|
||||
type: bool
|
||||
default: false
|
||||
validate_certs:
|
||||
description:
|
||||
- If set to V(false), SSL certificates are not validated.
|
||||
- This should only be used on sites using self-signed certificates.
|
||||
type: bool
|
||||
default: true
|
||||
sasl_class:
|
||||
description:
|
||||
- The class to use for SASL authentication.
|
||||
type: str
|
||||
choices: ['external', 'gssapi']
|
||||
default: external
|
||||
version_added: "2.0.0"
|
||||
sasl_auth_id:
|
||||
description:
|
||||
- The SASL authorization identity, equivalent to the C(-X) CLI argument.
|
||||
- If not provided, no authorization identity is sent.
|
||||
type: str
|
||||
version_added: "13.5.0"
|
||||
xorder_discovery:
|
||||
description:
|
||||
- Set the behavior on how to process Xordered DNs.
|
||||
- V(enable) performs a C(ONELEVEL) search below the superior RDN to find the matching DN.
|
||||
- V(disable) always uses the DN unmodified (as passed by the O(dn) parameter).
|
||||
- V(auto) only performs a search if the first RDN does not contain an index number (C({x})).
|
||||
type: str
|
||||
choices: ['enable', 'auto', 'disable']
|
||||
default: auto
|
||||
version_added: "6.4.0"
|
||||
"""
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
# Copyright (C) 2017 Lenovo, Inc.
|
||||
# Simplified BSD License (see LICENSES/BSD-2-Clause.txt or https://opensource.org/licenses/BSD-2-Clause)
|
||||
# SPDX-License-Identifier: BSD-2-Clause
|
||||
|
||||
# Note that this doc fragment is **PRIVATE** to the collection. It can have breaking changes at any time.
|
||||
# Do not use this from other collections or standalone plugins/modules!
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
class ModuleDocFragment:
|
||||
# Standard Pylxca documentation fragment
|
||||
DOCUMENTATION = r"""
|
||||
author:
|
||||
- Naval Patel (@navalkp)
|
||||
- Prashant Bhosale (@prabhosa)
|
||||
|
||||
options:
|
||||
login_user:
|
||||
description:
|
||||
- The username for use in HTTP basic authentication.
|
||||
type: str
|
||||
required: true
|
||||
|
||||
login_password:
|
||||
description:
|
||||
- The password for use in HTTP basic authentication.
|
||||
type: str
|
||||
required: true
|
||||
|
||||
auth_url:
|
||||
description:
|
||||
- Lxca HTTPS full web address.
|
||||
type: str
|
||||
required: true
|
||||
|
||||
requirements:
|
||||
- pylxca
|
||||
|
||||
notes:
|
||||
- Additional detail about pylxca can be found at U(https://github.com/lenovo/pylxca).
|
||||
- Playbooks using these modules can be found at U(https://github.com/lenovo/ansible.lenovo-lxca).
|
||||
"""
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
# Copyright (c) 2017, Daniel Korn <korndaniel1@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
|
||||
|
||||
# Note that this doc fragment is **PRIVATE** to the collection. It can have breaking changes at any time.
|
||||
# Do not use this from other collections or standalone plugins/modules!
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
class ModuleDocFragment:
|
||||
# Standard ManageIQ documentation fragment
|
||||
DOCUMENTATION = r"""
|
||||
options:
|
||||
manageiq_connection:
|
||||
description:
|
||||
- ManageIQ connection configuration information.
|
||||
required: false
|
||||
type: dict
|
||||
suboptions:
|
||||
url:
|
||||
description:
|
||||
- ManageIQ environment URL. E(MIQ_URL) environment variable if set. Otherwise, it is required to pass it.
|
||||
type: str
|
||||
required: false
|
||||
username:
|
||||
description:
|
||||
- ManageIQ username. E(MIQ_USERNAME) environment variable if set. Otherwise, required if no token is passed in.
|
||||
type: str
|
||||
password:
|
||||
description:
|
||||
- ManageIQ password. E(MIQ_PASSWORD) environment variable if set. Otherwise, required if no token is passed in.
|
||||
type: str
|
||||
token:
|
||||
description:
|
||||
- ManageIQ token. E(MIQ_TOKEN) environment variable if set. Otherwise, required if no username or password is passed
|
||||
in.
|
||||
type: str
|
||||
validate_certs:
|
||||
description:
|
||||
- Whether SSL certificates should be verified for HTTPS requests.
|
||||
type: bool
|
||||
default: true
|
||||
aliases: [verify_ssl]
|
||||
ca_cert:
|
||||
description:
|
||||
- The path to a CA bundle file or directory with certificates.
|
||||
type: str
|
||||
aliases: [ca_bundle_path]
|
||||
|
||||
requirements:
|
||||
- 'manageiq-client U(https://github.com/ManageIQ/manageiq-api-client-python/)'
|
||||
"""
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
# Copyright (c) 2020 FERREIRA Christophe <christophe.ferreira@cnaf.fr>
|
||||
# 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
|
||||
|
||||
# Note that this doc fragment is **PRIVATE** to the collection. It can have breaking changes at any time.
|
||||
# Do not use this from other collections or standalone plugins/modules!
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
class ModuleDocFragment:
|
||||
# Standard files documentation fragment
|
||||
DOCUMENTATION = r"""
|
||||
options:
|
||||
host:
|
||||
description:
|
||||
- FQDN of Nomad server.
|
||||
required: true
|
||||
type: str
|
||||
port:
|
||||
description:
|
||||
- Port of Nomad server.
|
||||
type: int
|
||||
default: 4646
|
||||
version_added: 8.0.0
|
||||
use_ssl:
|
||||
description:
|
||||
- Use TLS/SSL connection.
|
||||
type: bool
|
||||
default: true
|
||||
timeout:
|
||||
description:
|
||||
- Timeout (in seconds) for the request to Nomad.
|
||||
type: int
|
||||
default: 5
|
||||
validate_certs:
|
||||
description:
|
||||
- Enable TLS/SSL certificate validation.
|
||||
type: bool
|
||||
default: true
|
||||
client_cert:
|
||||
description:
|
||||
- Path of certificate for TLS/SSL.
|
||||
type: path
|
||||
client_key:
|
||||
description:
|
||||
- Path of certificate's private key for TLS/SSL.
|
||||
type: path
|
||||
namespace:
|
||||
description:
|
||||
- Namespace for Nomad.
|
||||
type: str
|
||||
token:
|
||||
description:
|
||||
- ACL token for authentication.
|
||||
type: str
|
||||
"""
|
||||
+86
@@ -0,0 +1,86 @@
|
||||
# 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
|
||||
|
||||
# Note that this doc fragment is **PRIVATE** to the collection. It can have breaking changes at any time.
|
||||
# Do not use this from other collections or standalone plugins/modules!
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
class ModuleDocFragment:
|
||||
DOCUMENTATION = r"""
|
||||
requirements:
|
||||
- C(op) 1Password command line utility version 2 or later.
|
||||
- See U(https://support.1password.com/command-line/)
|
||||
options:
|
||||
master_password:
|
||||
description: The password used to unlock the specified vault.
|
||||
aliases: ['vault_password']
|
||||
type: str
|
||||
section:
|
||||
description: Item section containing the field to retrieve (case-insensitive). If absent, returns first match from any
|
||||
section.
|
||||
domain:
|
||||
description: Domain of 1Password.
|
||||
default: '1password.com'
|
||||
type: str
|
||||
subdomain:
|
||||
description: The 1Password subdomain to authenticate against.
|
||||
type: str
|
||||
account_id:
|
||||
description: The account ID to target.
|
||||
type: str
|
||||
username:
|
||||
description: The username used to sign in.
|
||||
type: str
|
||||
secret_key:
|
||||
description: The secret key used when performing an initial sign in.
|
||||
type: str
|
||||
service_account_token:
|
||||
description:
|
||||
- The access key for a service account.
|
||||
type: str
|
||||
vault:
|
||||
description: Vault containing the item to retrieve (case-insensitive). If absent, searches all vaults.
|
||||
type: str
|
||||
connect_host:
|
||||
description: The host for 1Password Connect. Must be used in combination with O(connect_token).
|
||||
type: str
|
||||
env:
|
||||
- name: OP_CONNECT_HOST
|
||||
version_added: 8.1.0
|
||||
connect_token:
|
||||
description: The token for 1Password Connect. Must be used in combination with O(connect_host).
|
||||
type: str
|
||||
env:
|
||||
- name: OP_CONNECT_TOKEN
|
||||
version_added: 8.1.0
|
||||
"""
|
||||
|
||||
LOOKUP = r"""
|
||||
options:
|
||||
master_password:
|
||||
secret: true
|
||||
secret_key:
|
||||
secret: true
|
||||
service_account_token:
|
||||
env:
|
||||
- name: OP_SERVICE_ACCOUNT_TOKEN
|
||||
version_added: 8.2.0
|
||||
secret: true
|
||||
connect_token:
|
||||
secret: true
|
||||
notes:
|
||||
- This lookup uses an existing 1Password session if one exists. If not, and you have already performed an initial sign in
|
||||
(meaning C(~/.op/config), C(~/.config/op/config) or C(~/.config/.op/config) exists), then only the O(master_password)
|
||||
is required. You may optionally specify O(subdomain) in this scenario, otherwise the last used subdomain is used by C(op).
|
||||
- This lookup can perform an initial login by providing O(subdomain), O(username), O(secret_key), and O(master_password).
|
||||
- Can target a specific account by providing the O(account_id).
|
||||
- Due to the B(very) sensitive nature of these credentials, it is B(highly) recommended that you only pass in the minimal
|
||||
credentials needed at any given time. Also, store these credentials in an Ansible Vault using a key that is equal to or
|
||||
greater in strength to the 1Password master password.
|
||||
- This lookup stores potentially sensitive data from 1Password as Ansible facts. Facts are subject to caching if enabled,
|
||||
which means this data could be stored in clear text on disk or in a database.
|
||||
- Tested with C(op) version 2.7.2.
|
||||
"""
|
||||
+73
@@ -0,0 +1,73 @@
|
||||
# Copyright (c) 2016-2017, Hewlett Packard Enterprise Development LP
|
||||
# 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
|
||||
|
||||
# Note that this doc fragment is **PRIVATE** to the collection. It can have breaking changes at any time.
|
||||
# Do not use this from other collections or standalone plugins/modules!
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
class ModuleDocFragment:
|
||||
# OneView doc fragment
|
||||
DOCUMENTATION = r"""
|
||||
options:
|
||||
config:
|
||||
description:
|
||||
- Path to a JSON configuration file containing the OneView client configuration. The configuration file is optional
|
||||
and when used should be present on the host running the Ansible commands. If the file path is not provided, the configuration
|
||||
is loaded from environment variables. For links to example configuration files or how to use the environment variables
|
||||
verify the notes section.
|
||||
type: path
|
||||
api_version:
|
||||
description:
|
||||
- OneView API Version.
|
||||
type: int
|
||||
image_streamer_hostname:
|
||||
description:
|
||||
- IP address or hostname for the HPE Image Streamer REST API.
|
||||
type: str
|
||||
hostname:
|
||||
description:
|
||||
- IP address or hostname for the appliance.
|
||||
type: str
|
||||
username:
|
||||
description:
|
||||
- Username for API authentication.
|
||||
type: str
|
||||
password:
|
||||
description:
|
||||
- Password for API authentication.
|
||||
type: str
|
||||
|
||||
notes:
|
||||
- 'A sample configuration file for the config parameter can be found at:
|
||||
U(https://github.com/HewlettPackard/oneview-ansible/blob/master/examples/oneview_config-rename.json).'
|
||||
- 'Check how to use environment variables for configuration at: U(https://github.com/HewlettPackard/oneview-ansible#environment-variables).'
|
||||
- 'Additional Playbooks for the HPE OneView Ansible modules can be found at: U(https://github.com/HewlettPackard/oneview-ansible/tree/master/examples).'
|
||||
- 'The OneView API version used directly affects returned and expected fields in resources. Information on setting the desired
|
||||
API version and can be found at: U(https://github.com/HewlettPackard/oneview-ansible#setting-your-oneview-version).'
|
||||
"""
|
||||
|
||||
VALIDATEETAG = r"""
|
||||
options:
|
||||
validate_etag:
|
||||
description:
|
||||
- When the ETag Validation is enabled, the request is conditionally processed only if the current ETag for the resource
|
||||
matches the ETag provided in the data.
|
||||
type: bool
|
||||
default: true
|
||||
"""
|
||||
|
||||
FACTSPARAMS = r"""
|
||||
options:
|
||||
params:
|
||||
description:
|
||||
- List of parameters to delimit, filter and sort the list of resources.
|
||||
- 'Parameter keys allowed are:'
|
||||
- 'V(start): The first item to return, using 0-based indexing.'
|
||||
- 'V(count): The number of resources to return.'
|
||||
- 'V(filter): A general filter/query string to narrow the list of items returned.'
|
||||
- 'V(sort): The sort order of the returned data set.'
|
||||
type: dict
|
||||
"""
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
# Copyright (c) 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
|
||||
|
||||
# Note that this doc fragment is **PRIVATE** to the collection. It can have breaking changes at any time.
|
||||
# Do not use this from other collections or standalone plugins/modules!
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
class ModuleDocFragment:
|
||||
# Standard documentation fragment
|
||||
DOCUMENTATION = r"""
|
||||
options:
|
||||
api_token:
|
||||
description:
|
||||
- Online OAuth token.
|
||||
type: str
|
||||
required: true
|
||||
aliases: [oauth_token]
|
||||
api_url:
|
||||
description:
|
||||
- Online API URL.
|
||||
type: str
|
||||
default: 'https://api.online.net'
|
||||
aliases: [base_url]
|
||||
api_timeout:
|
||||
description:
|
||||
- HTTP timeout to Online API in seconds.
|
||||
type: int
|
||||
default: 30
|
||||
aliases: [timeout]
|
||||
validate_certs:
|
||||
description:
|
||||
- Validate SSL certs of the Online API.
|
||||
type: bool
|
||||
default: true
|
||||
notes:
|
||||
- Also see the API documentation on U(https://console.online.net/en/api/).
|
||||
- If O(api_token) is not set within the module, the following environment variables can be used in decreasing order of precedence
|
||||
E(ONLINE_TOKEN), E(ONLINE_API_KEY), E(ONLINE_OAUTH_TOKEN), E(ONLINE_API_TOKEN).
|
||||
- If one wants to use a different O(api_url) one can also set the E(ONLINE_API_URL) environment variable.
|
||||
"""
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
# Copyright (c) 2018, www.privaz.io Valletech AB
|
||||
# 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
|
||||
|
||||
# Note that this doc fragment is **PRIVATE** to the collection. It can have breaking changes at any time.
|
||||
# Do not use this from other collections or standalone plugins/modules!
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
class ModuleDocFragment:
|
||||
# OpenNebula common documentation
|
||||
DOCUMENTATION = r"""
|
||||
options:
|
||||
api_url:
|
||||
description:
|
||||
- The ENDPOINT URL of the XMLRPC server.
|
||||
- If not specified then the value of the E(ONE_URL) environment variable, if any, is used.
|
||||
type: str
|
||||
aliases:
|
||||
- api_endpoint
|
||||
api_username:
|
||||
description:
|
||||
- The name of the user for XMLRPC authentication.
|
||||
- If not specified then the value of the E(ONE_USERNAME) environment variable, if any, is used.
|
||||
type: str
|
||||
api_password:
|
||||
description:
|
||||
- The password or token for XMLRPC authentication.
|
||||
- If not specified then the value of the E(ONE_PASSWORD) environment variable, if any, is used.
|
||||
type: str
|
||||
aliases:
|
||||
- api_token
|
||||
validate_certs:
|
||||
description:
|
||||
- Whether to validate the TLS/SSL certificates or not.
|
||||
- This parameter is ignored if E(PYTHONHTTPSVERIFY) environment variable is used.
|
||||
type: bool
|
||||
default: true
|
||||
wait_timeout:
|
||||
description:
|
||||
- Time to wait for the desired state to be reached before timeout, in seconds.
|
||||
type: int
|
||||
default: 300
|
||||
"""
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
# Copyright (c) 2024, 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
|
||||
|
||||
# Note that this doc fragment is **PRIVATE** to the collection. It can have breaking changes at any time.
|
||||
# Do not use this from other collections or standalone plugins/modules!
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
class ModuleDocFragment:
|
||||
DOCUMENTATION = r"""
|
||||
options:
|
||||
global:
|
||||
description:
|
||||
- The module passes the C(--global) argument to C(pipx), to execute actions in global scope.
|
||||
type: bool
|
||||
default: false
|
||||
executable:
|
||||
description:
|
||||
- Path to the C(pipx) installed in the system.
|
||||
- If not specified, the module uses C(python -m pipx) to run the tool, using the same Python interpreter as ansible
|
||||
itself.
|
||||
type: path
|
||||
requirements:
|
||||
- This module requires C(pipx) version 1.7.0 or above.
|
||||
- Please note that C(pipx) 1.7.0 requires Python 3.8 or above.
|
||||
- Please note that C(pipx) 1.8.0 requires Python 3.9 or above.
|
||||
notes:
|
||||
- This module does not install the C(pipx) python package, however that can be easily done with the module M(ansible.builtin.pip).
|
||||
- This module does not require C(pipx) to be in the shell C(PATH), but it must be loadable by Python as a module, meaning
|
||||
that C(python -m pipx) must work.
|
||||
- This module honors C(pipx) environment variables such as but not limited to E(PIPX_HOME) and E(PIPX_BIN_DIR) passed using
|
||||
the R(environment Ansible keyword, playbooks_environment).
|
||||
- This module disables emojis in the output of C(pipx) commands to reduce clutter. In C(pipx) 1.8.0, the environment variable
|
||||
E(USE_EMOJI) was renamed to E(PIPX_USE_EMOJI) and for compatibility with both versions, starting in community.general
|
||||
11.4.0, this module sets them both to C(0) to disable emojis.
|
||||
seealso:
|
||||
- name: C(pipx) command manual page
|
||||
description: Manual page for the command.
|
||||
link: https://pipx.pypa.io/latest/docs/
|
||||
"""
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
# Copyright (c) 2021, Florian Dambrine <android.florian@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
|
||||
|
||||
# Note that this doc fragment is **PRIVATE** to the collection. It can have breaking changes at any time.
|
||||
# Do not use this from other collections or standalone plugins/modules!
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
class ModuleDocFragment:
|
||||
DOCUMENTATION = r"""
|
||||
options:
|
||||
pritunl_url:
|
||||
type: str
|
||||
required: true
|
||||
description:
|
||||
- URL and port of the Pritunl server on which the API is enabled.
|
||||
pritunl_api_token:
|
||||
type: str
|
||||
required: true
|
||||
description:
|
||||
- API Token of a Pritunl admin user.
|
||||
- It needs to be enabled in Administrators > USERNAME > Enable Token Authentication.
|
||||
pritunl_api_secret:
|
||||
type: str
|
||||
required: true
|
||||
description:
|
||||
- API Secret found in Administrators > USERNAME > API Secret.
|
||||
validate_certs:
|
||||
type: bool
|
||||
required: false
|
||||
default: true
|
||||
description:
|
||||
- If certificates should be validated or not.
|
||||
- This should never be set to V(false), except if you are very sure that your connection to the server can not be subject
|
||||
to a Man In The Middle attack.
|
||||
"""
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
# Copyright (c) 2025 Ansible community
|
||||
# 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
|
||||
|
||||
# Note that this doc fragment is **PRIVATE** to the collection. It can have breaking changes at any time.
|
||||
# Do not use this from other collections or standalone plugins/modules!
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
class ModuleDocFragment:
|
||||
# Use together with the community.general.redfish module utils' REDFISH_COMMON_ARGUMENT_SPEC
|
||||
DOCUMENTATION = r"""
|
||||
options:
|
||||
validate_certs:
|
||||
description:
|
||||
- If V(false), TLS/SSL certificates are not validated.
|
||||
- Set this to V(true) to enable certificate checking. Should be used together with O(ca_path).
|
||||
type: bool
|
||||
default: false
|
||||
ca_path:
|
||||
description:
|
||||
- PEM formatted file that contains a CA certificate to be used for validation.
|
||||
- Only used if O(validate_certs=true).
|
||||
type: path
|
||||
ciphers:
|
||||
required: false
|
||||
description:
|
||||
- TLS/SSL Ciphers to use for the request.
|
||||
- When a list is provided, all ciphers are joined in order with V(:).
|
||||
- See the L(OpenSSL Cipher List Format,https://www.openssl.org/docs/manmaster/man1/openssl-ciphers.html#CIPHER-LIST-FORMAT)
|
||||
for more details.
|
||||
- The available ciphers is dependent on the Python and OpenSSL/LibreSSL versions.
|
||||
type: list
|
||||
elements: str
|
||||
"""
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
# Copyright (c) 2021, Andreas Botzner <andreas at botzner dot 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
|
||||
|
||||
# Note that this doc fragment is **PRIVATE** to the collection. It can have breaking changes at any time.
|
||||
# Do not use this from other collections or standalone plugins/modules!
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
class ModuleDocFragment:
|
||||
# Common parameters for Redis modules
|
||||
DOCUMENTATION = r"""
|
||||
options:
|
||||
login_host:
|
||||
description:
|
||||
- Specify the target host running the database.
|
||||
default: localhost
|
||||
type: str
|
||||
login_port:
|
||||
description:
|
||||
- Specify the port to connect to.
|
||||
default: 6379
|
||||
type: int
|
||||
login_user:
|
||||
description:
|
||||
- Specify the user to authenticate with.
|
||||
- Requires L(redis,https://pypi.org/project/redis) >= 3.4.0.
|
||||
type: str
|
||||
login_password:
|
||||
description:
|
||||
- Specify the password to authenticate with.
|
||||
- Usually not used when target is localhost.
|
||||
type: str
|
||||
tls:
|
||||
description:
|
||||
- Specify whether or not to use TLS for the connection.
|
||||
type: bool
|
||||
default: true
|
||||
validate_certs:
|
||||
description:
|
||||
- Specify whether or not to validate TLS certificates.
|
||||
- This should only be turned off for personally controlled sites or with C(localhost) as target.
|
||||
type: bool
|
||||
default: true
|
||||
ca_certs:
|
||||
description:
|
||||
- Path to root certificates file. If not set and O(tls) is set to V(true), certifi's CA certificates are used.
|
||||
type: str
|
||||
client_cert_file:
|
||||
description:
|
||||
- Path to the client certificate file.
|
||||
type: str
|
||||
version_added: 9.3.0
|
||||
client_key_file:
|
||||
description:
|
||||
- Path to the client private key file.
|
||||
type: str
|
||||
version_added: 9.3.0
|
||||
requirements: ["redis", "certifi"]
|
||||
|
||||
notes:
|
||||
- Requires the C(redis) Python package on the remote host. You can install it with pip (C(pip install redis)) or with a
|
||||
package manager. Information on the library can be found at U(https://github.com/andymccurdy/redis-py).
|
||||
"""
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
# Copyright (c) 2021, Phillipe Smith <phsmithcc@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
|
||||
|
||||
# Note that this doc fragment is **PRIVATE** to the collection. It can have breaking changes at any time.
|
||||
# Do not use this from other collections or standalone plugins/modules!
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
class ModuleDocFragment:
|
||||
# Standard files documentation fragment
|
||||
DOCUMENTATION = r"""
|
||||
options:
|
||||
url:
|
||||
type: str
|
||||
description:
|
||||
- Rundeck instance URL.
|
||||
required: true
|
||||
api_version:
|
||||
type: int
|
||||
description:
|
||||
- Rundeck API version to be used.
|
||||
- API version must be at least 14.
|
||||
default: 39
|
||||
api_token:
|
||||
type: str
|
||||
description:
|
||||
- Rundeck User API Token.
|
||||
required: true
|
||||
"""
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
# Copyright (c) 2018, Yanis Guenane <yanis+ansible@guenane.org>
|
||||
# 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
|
||||
|
||||
# Note that this doc fragment is **PRIVATE** to the collection. It can have breaking changes at any time.
|
||||
# Do not use this from other collections or standalone plugins/modules!
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
class ModuleDocFragment:
|
||||
# Standard documentation fragment
|
||||
DOCUMENTATION = r"""
|
||||
options:
|
||||
api_token:
|
||||
description:
|
||||
- Scaleway OAuth token.
|
||||
- This is required if O(profile) is not specified.
|
||||
type: str
|
||||
aliases: [oauth_token]
|
||||
api_url:
|
||||
description:
|
||||
- Scaleway API URL.
|
||||
type: str
|
||||
default: https://api.scaleway.com
|
||||
aliases: [base_url]
|
||||
api_timeout:
|
||||
description:
|
||||
- HTTP timeout to Scaleway API in seconds.
|
||||
type: int
|
||||
default: 30
|
||||
aliases: [timeout]
|
||||
profile:
|
||||
description:
|
||||
- The config profile in config file to load the Scaleway OAuth token from, use instead of O(api_token).
|
||||
- It is also possible to set E(SCW_PROFILE) to use a SCW CLI config profile.
|
||||
type: str
|
||||
aliases: [scw_profile]
|
||||
version_added: 12.2.0
|
||||
query_parameters:
|
||||
description:
|
||||
- List of parameters passed to the query string.
|
||||
type: dict
|
||||
default: {}
|
||||
validate_certs:
|
||||
description:
|
||||
- Validate SSL certs of the Scaleway API.
|
||||
type: bool
|
||||
default: true
|
||||
requirements:
|
||||
- PyYAML (when O(profile) is used)
|
||||
notes:
|
||||
- Also see the API documentation on U(https://developer.scaleway.com/).
|
||||
- If O(api_token) is not set within the module, the following environment variables can be used in decreasing order of precedence
|
||||
E(SCW_TOKEN), E(SCW_API_KEY), E(SCW_OAUTH_TOKEN) or E(SCW_API_TOKEN).
|
||||
- If one wants to use a different O(api_url) one can also set the E(SCW_API_URL) environment variable.
|
||||
"""
|
||||
|
||||
ACTIONGROUP_SCALEWAY = r"""
|
||||
options: {}
|
||||
attributes:
|
||||
action_group:
|
||||
description: Use C(group/community.general.scaleway) in C(module_defaults) to set defaults for this module.
|
||||
support: full
|
||||
membership:
|
||||
- community.general.scaleway
|
||||
"""
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
# Copyright (c) 2022, Guillaume MARTINEZ <lunik@tiwabbit.fr>
|
||||
# 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
|
||||
|
||||
# Note that this doc fragment is **PRIVATE** to the collection. It can have breaking changes at any time.
|
||||
# Do not use this from other collections or standalone plugins/modules!
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
class ModuleDocFragment:
|
||||
# Standard documentation fragment
|
||||
DOCUMENTATION = r"""
|
||||
options:
|
||||
wait:
|
||||
description:
|
||||
- Wait for the resource to reach its desired state before returning.
|
||||
type: bool
|
||||
default: true
|
||||
wait_timeout:
|
||||
type: int
|
||||
description:
|
||||
- Time to wait for the resource to reach the expected state.
|
||||
required: false
|
||||
default: 300
|
||||
wait_sleep_time:
|
||||
type: int
|
||||
description:
|
||||
- Time to wait before every attempt to check the state of the resource.
|
||||
required: false
|
||||
default: 3
|
||||
"""
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
# Copyright (c) 2018, Johannes Brunswicker <johannes.brunswicker@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
|
||||
|
||||
# Note that this doc fragment is **PRIVATE** to the collection. It can have breaking changes at any time.
|
||||
# Do not use this from other collections or standalone plugins/modules!
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
class ModuleDocFragment:
|
||||
DOCUMENTATION = r"""
|
||||
options:
|
||||
headers:
|
||||
description:
|
||||
- A dictionary of additional headers to be sent to POST and PUT requests.
|
||||
- Is needed for some modules.
|
||||
type: dict
|
||||
required: false
|
||||
default: {}
|
||||
utm_host:
|
||||
description:
|
||||
- The REST Endpoint of the Sophos UTM.
|
||||
type: str
|
||||
required: true
|
||||
utm_port:
|
||||
description:
|
||||
- The port of the REST interface.
|
||||
type: int
|
||||
default: 4444
|
||||
utm_token:
|
||||
description:
|
||||
- The token used to identify at the REST-API.
|
||||
- See U(https://www.sophos.com/en-us/medialibrary/PDFs/documentation/UTMonAWS/Sophos-UTM-RESTful-API.pdf?la=en), Chapter
|
||||
2.4.2.
|
||||
type: str
|
||||
required: true
|
||||
utm_protocol:
|
||||
description:
|
||||
- The protocol of the REST Endpoint.
|
||||
choices: [http, https]
|
||||
type: str
|
||||
default: https
|
||||
validate_certs:
|
||||
description:
|
||||
- Whether the REST interface's SSL certificate should be verified or not.
|
||||
type: bool
|
||||
default: true
|
||||
state:
|
||||
description:
|
||||
- The desired state of the object.
|
||||
- V(present) creates or updates an object.
|
||||
- V(absent) deletes an object if present.
|
||||
type: str
|
||||
choices: [absent, present]
|
||||
default: present
|
||||
"""
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
# Copyright (c) 2019, Sandeep Kasargod <sandeep@vexata.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
|
||||
|
||||
# Note that this doc fragment is **PRIVATE** to the collection. It can have breaking changes at any time.
|
||||
# Do not use this from other collections or standalone plugins/modules!
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
class ModuleDocFragment:
|
||||
# Documentation fragment for Vexata VX100 series
|
||||
VX100 = r"""
|
||||
options:
|
||||
array:
|
||||
description:
|
||||
- Vexata VX100 array hostname or IPv4 Address.
|
||||
required: true
|
||||
type: str
|
||||
user:
|
||||
description:
|
||||
- Vexata API user with administrative privileges.
|
||||
- Uses the E(VEXATA_USER) environment variable as a fallback.
|
||||
required: false
|
||||
type: str
|
||||
password:
|
||||
description:
|
||||
- Vexata API user password.
|
||||
- Uses the E(VEXATA_PASSWORD) environment variable as a fallback.
|
||||
required: false
|
||||
type: str
|
||||
validate_certs:
|
||||
description:
|
||||
- Allows connection when SSL certificates are not valid. Set to V(false) when certificates are not trusted.
|
||||
required: false
|
||||
type: bool
|
||||
default: false
|
||||
|
||||
requirements:
|
||||
- Vexata VX100 storage array with VXOS >= v3.5.0 on storage array
|
||||
- vexatapi >= 0.0.1
|
||||
- E(VEXATA_USER) and E(VEXATA_PASSWORD) environment variables must be set if
|
||||
user and password arguments are not passed to the module directly.
|
||||
"""
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
# Copyright (c) 2018, Bojan Vitnik <bvitnik@mainstream.rs>
|
||||
# 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
|
||||
|
||||
# Note that this doc fragment is **PRIVATE** to the collection. It can have breaking changes at any time.
|
||||
# Do not use this from other collections or standalone plugins/modules!
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
class ModuleDocFragment:
|
||||
# Common parameters for XenServer modules
|
||||
DOCUMENTATION = r"""
|
||||
options:
|
||||
hostname:
|
||||
description:
|
||||
- The hostname or IP address of the XenServer host or XenServer pool master.
|
||||
- If the value is not specified in the task, the value of environment variable E(XENSERVER_HOST) is used instead.
|
||||
type: str
|
||||
default: localhost
|
||||
aliases: [host, pool]
|
||||
username:
|
||||
description:
|
||||
- The username to use for connecting to XenServer.
|
||||
- If the value is not specified in the task, the value of environment variable E(XENSERVER_USER) is used instead.
|
||||
type: str
|
||||
default: root
|
||||
aliases: [admin, user]
|
||||
password:
|
||||
description:
|
||||
- The password to use for connecting to XenServer.
|
||||
- If the value is not specified in the task, the value of environment variable E(XENSERVER_PASSWORD) is used instead.
|
||||
type: str
|
||||
aliases: [pass, pwd]
|
||||
validate_certs:
|
||||
description:
|
||||
- Allows connection when SSL certificates are not valid. Set to V(false) when certificates are not trusted.
|
||||
- If the value is not specified in the task, the value of environment variable E(XENSERVER_VALIDATE_CERTS) is used instead.
|
||||
type: bool
|
||||
default: true
|
||||
"""
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
# Copyright (c) 2014, Red Hat, Inc.
|
||||
# Copyright (c) 2014, Tim Bielawa <tbielawa@redhat.com>
|
||||
# Copyright (c) 2014, Magnus Hedemark <mhedemar@redhat.com>
|
||||
# Copyright (c) 2017, Dag Wieers <dag@wieers.com>
|
||||
# Copyright (c) 2026, Shreyash Bhosale <shreyashpb16@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
|
||||
|
||||
# Note that this doc fragment is **PRIVATE** to the collection. It can have breaking changes at any time.
|
||||
# Do not use this from other collections or standalone plugins/modules!
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
class ModuleDocFragment:
|
||||
DOCUMENTATION = r"""
|
||||
options:
|
||||
path:
|
||||
description:
|
||||
- Path to the file to operate on.
|
||||
- This file must exist ahead of time.
|
||||
- This parameter is required, unless O(xmlstring) is given.
|
||||
type: path
|
||||
aliases: [dest, file]
|
||||
xmlstring:
|
||||
description:
|
||||
- A string containing XML on which to operate.
|
||||
- This parameter is required, unless O(path) is given.
|
||||
type: str
|
||||
xpath:
|
||||
description:
|
||||
- A valid XPath expression describing the item(s) you want to operate on.
|
||||
- Operates on the document root, V(/), by default.
|
||||
type: str
|
||||
namespaces:
|
||||
description:
|
||||
- The namespace C(prefix:uri) mapping for the XPath expression.
|
||||
- Needs to be a C(dict), not a C(list) of items.
|
||||
type: dict
|
||||
default: {}
|
||||
strip_cdata_tags:
|
||||
description:
|
||||
- Remove CDATA tags surrounding text values.
|
||||
- Note that this might break your XML file if text values contain characters that could be interpreted as XML.
|
||||
type: bool
|
||||
default: false
|
||||
huge_tree:
|
||||
description:
|
||||
- Disable libxml2 security restrictions on XML node size or document depth, allowing processing of very large XML files.
|
||||
- This option should only be activated when needed, as it disables internal safety limits.
|
||||
type: bool
|
||||
default: false
|
||||
requirements:
|
||||
- lxml >= 2.3.0
|
||||
notes:
|
||||
- This module does not handle complicated xpath expressions, so limit xpath selectors to simple expressions.
|
||||
- Beware that in case your XML elements are namespaced, you need to use the O(namespaces) parameter, see the examples.
|
||||
- Namespaces prefix should be used for all children of an element where namespace is defined, unless another namespace is
|
||||
defined for them.
|
||||
"""
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
# Copyright (c) Max Gautier <mg@max.gautier.name>
|
||||
# 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"""
|
||||
name: accumulate
|
||||
short_description: Produce a list of accumulated sums of the input list contents
|
||||
version_added: 10.1.0
|
||||
author: Max Gautier (@VannTen)
|
||||
description:
|
||||
- Passthrough to the L(Python itertools.accumulate function,https://docs.python.org/3/library/itertools.html#itertools.accumulate).
|
||||
- Transforms an input list into the cumulative list of results from applying addition to the elements of the input list.
|
||||
- Addition means the default Python implementation of C(+) for input list elements type.
|
||||
options:
|
||||
_input:
|
||||
description: A list.
|
||||
type: list
|
||||
elements: any
|
||||
required: true
|
||||
"""
|
||||
|
||||
RETURN = r"""
|
||||
_value:
|
||||
description: A list of cumulated sums of the elements of the input list.
|
||||
type: list
|
||||
elements: any
|
||||
"""
|
||||
|
||||
EXAMPLES = r"""
|
||||
- name: Enumerate parent directories of some path
|
||||
ansible.builtin.debug:
|
||||
var: >
|
||||
"/some/path/to/my/file"
|
||||
| split('/') | map('split', '/')
|
||||
| community.general.accumulate | map('join', '/')
|
||||
# Produces: ['', '/some', '/some/path', '/some/path/to', '/some/path/to/my', '/some/path/to/my/file']
|
||||
|
||||
- name: Growing string
|
||||
ansible.builtin.debug:
|
||||
var: "'abc' | community.general.accumulate"
|
||||
# Produces ['a', 'ab', 'abc']
|
||||
"""
|
||||
|
||||
from collections.abc import Sequence
|
||||
from itertools import accumulate
|
||||
|
||||
from ansible.errors import AnsibleFilterError
|
||||
|
||||
|
||||
def list_accumulate(sequence):
|
||||
if not isinstance(sequence, Sequence):
|
||||
raise AnsibleFilterError(f"Invalid value type ({type(sequence)}) for accumulate ({sequence!r})")
|
||||
|
||||
return accumulate(sequence)
|
||||
|
||||
|
||||
class FilterModule:
|
||||
def filters(self):
|
||||
return {
|
||||
"accumulate": list_accumulate,
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
# Copyright (c) 2021, Remy Keil <remy.keil@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
|
||||
|
||||
DOCUMENTATION = r"""
|
||||
name: counter
|
||||
short_description: Counts hashable elements in a sequence
|
||||
version_added: 4.3.0
|
||||
author: Rémy Keil (@keilr)
|
||||
description:
|
||||
- Counts hashable elements in a sequence.
|
||||
options:
|
||||
_input:
|
||||
description: A sequence.
|
||||
type: list
|
||||
elements: any
|
||||
required: true
|
||||
"""
|
||||
|
||||
EXAMPLES = r"""
|
||||
- name: Count occurrences
|
||||
ansible.builtin.debug:
|
||||
msg: >-
|
||||
{{ [1, 'a', 2, 2, 'a', 'b', 'a'] | community.general.counter }}
|
||||
# Produces: {1: 1, 'a': 3, 2: 2, 'b': 1}
|
||||
"""
|
||||
|
||||
RETURN = r"""
|
||||
_value:
|
||||
description: A dictionary with the elements of the sequence as keys, and their number of occurrences in the sequence as
|
||||
values.
|
||||
type: dictionary
|
||||
"""
|
||||
|
||||
from collections import Counter
|
||||
from collections.abc import Sequence
|
||||
|
||||
from ansible.errors import AnsibleFilterError
|
||||
|
||||
|
||||
def counter(sequence):
|
||||
"""Count elements in a sequence. Returns dict with count result."""
|
||||
if not isinstance(sequence, Sequence):
|
||||
raise AnsibleFilterError(
|
||||
f"Argument for community.general.counter must be a sequence (string or list). {sequence} is {type(sequence)}"
|
||||
)
|
||||
|
||||
try:
|
||||
result = dict(Counter(sequence))
|
||||
except TypeError as e:
|
||||
raise AnsibleFilterError(
|
||||
f"community.general.counter needs a sequence with hashable elements (int, float or str) - {e}"
|
||||
) from e
|
||||
return result
|
||||
|
||||
|
||||
class FilterModule:
|
||||
"""Ansible counter jinja2 filters"""
|
||||
|
||||
def filters(self):
|
||||
filters = {
|
||||
"counter": counter,
|
||||
}
|
||||
|
||||
return filters
|
||||
@@ -0,0 +1,62 @@
|
||||
# Copyright (c) 2022, Julien Riou <julien@riou.xyz>
|
||||
# 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
|
||||
|
||||
from ansible.errors import AnsibleFilterError
|
||||
from ansible.module_utils.common.collections import is_string
|
||||
from ansible.module_utils.common.text.converters import to_bytes
|
||||
|
||||
try:
|
||||
from zlib import crc32
|
||||
|
||||
HAS_ZLIB = True
|
||||
except ImportError:
|
||||
HAS_ZLIB = False
|
||||
|
||||
|
||||
DOCUMENTATION = r"""
|
||||
name: crc32
|
||||
short_description: Generate a CRC32 checksum
|
||||
version_added: 5.4.0
|
||||
description:
|
||||
- Checksum a string using CRC32 algorithm and return its hexadecimal representation.
|
||||
options:
|
||||
_input:
|
||||
description:
|
||||
- The string to checksum.
|
||||
type: string
|
||||
required: true
|
||||
author:
|
||||
- Julien Riou
|
||||
"""
|
||||
|
||||
EXAMPLES = r"""
|
||||
- name: Checksum a test string
|
||||
ansible.builtin.debug:
|
||||
msg: "{{ 'test' | community.general.crc32 }}"
|
||||
"""
|
||||
|
||||
RETURN = r"""
|
||||
_value:
|
||||
description: CRC32 checksum.
|
||||
type: string
|
||||
"""
|
||||
|
||||
|
||||
def crc32s(value):
|
||||
if not is_string(value):
|
||||
raise AnsibleFilterError(f"Invalid value type ({type(value)}) for crc32 ({value!r})")
|
||||
|
||||
if not HAS_ZLIB:
|
||||
raise AnsibleFilterError("Failed to import zlib module")
|
||||
|
||||
data = to_bytes(value, errors="surrogate_or_strict")
|
||||
return f"{crc32(data) & 0xFFFFFFFF:x}"
|
||||
|
||||
|
||||
class FilterModule:
|
||||
def filters(self):
|
||||
return {
|
||||
"crc32": crc32s,
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
# Copyright (c) 2021, Felix Fontein <felix@fontein.de>
|
||||
# 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"""
|
||||
name: dict
|
||||
short_description: Convert a list of tuples into a dictionary
|
||||
version_added: 3.0.0
|
||||
author: Felix Fontein (@felixfontein)
|
||||
description:
|
||||
- Convert a list of tuples into a dictionary. This is a filter version of the C(dict) function.
|
||||
options:
|
||||
_input:
|
||||
description: A list of tuples (with exactly two elements).
|
||||
type: list
|
||||
elements: tuple
|
||||
required: true
|
||||
"""
|
||||
|
||||
EXAMPLES = r"""
|
||||
- name: Convert list of tuples into dictionary
|
||||
ansible.builtin.set_fact:
|
||||
dictionary: "{{ [[1, 2], ['a', 'b']] | community.general.dict }}"
|
||||
# Result is {1: 2, 'a': 'b'}
|
||||
|
||||
- name: Create a list of dictionaries with map and the community.general.dict filter
|
||||
ansible.builtin.debug:
|
||||
msg: >-
|
||||
{{ values | map('zip', ['k1', 'k2', 'k3'])
|
||||
| map('map', 'reverse')
|
||||
| map('community.general.dict') }}
|
||||
vars:
|
||||
values:
|
||||
- - foo
|
||||
- 23
|
||||
- a
|
||||
- - bar
|
||||
- 42
|
||||
- b
|
||||
# Produces the following list of dictionaries:
|
||||
# {
|
||||
# "k1": "foo",
|
||||
# "k2": 23,
|
||||
# "k3": "a"
|
||||
# },
|
||||
# {
|
||||
# "k1": "bar",
|
||||
# "k2": 42,
|
||||
# "k3": "b"
|
||||
# }
|
||||
"""
|
||||
|
||||
RETURN = r"""
|
||||
_value:
|
||||
description: A dictionary with the provided key-value pairs.
|
||||
type: dictionary
|
||||
"""
|
||||
|
||||
|
||||
def dict_filter(sequence):
|
||||
"""Convert a list of tuples to a dictionary.
|
||||
|
||||
Example: ``[[1, 2], ['a', 'b']] | community.general.dict`` results in ``{1: 2, 'a': 'b'}``
|
||||
"""
|
||||
return dict(sequence)
|
||||
|
||||
|
||||
class FilterModule:
|
||||
"""Ansible jinja2 filters"""
|
||||
|
||||
def filters(self):
|
||||
return {
|
||||
"dict": dict_filter,
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
# Copyright (C) 2020 Stanislav German-Evtushenko (@giner) <ginermail@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
|
||||
|
||||
DOCUMENTATION = r"""
|
||||
name: dict_kv
|
||||
short_description: Convert a value to a dictionary with a single key-value pair
|
||||
version_added: 1.3.0
|
||||
author: Stanislav German-Evtushenko (@giner)
|
||||
description:
|
||||
- Convert a value to a dictionary with a single key-value pair.
|
||||
positional: key
|
||||
options:
|
||||
_input:
|
||||
description: The value for the single key-value pair.
|
||||
type: any
|
||||
required: true
|
||||
key:
|
||||
description: The key for the single key-value pair.
|
||||
type: any
|
||||
required: true
|
||||
"""
|
||||
|
||||
EXAMPLES = r"""
|
||||
- name: Create a one-element dictionary from a value
|
||||
ansible.builtin.debug:
|
||||
msg: "{{ 'myvalue' | dict_kv('mykey') }}"
|
||||
# Produces the dictionary {'mykey': 'myvalue'}
|
||||
"""
|
||||
|
||||
RETURN = r"""
|
||||
_value:
|
||||
description: A dictionary with a single key-value pair.
|
||||
type: dictionary
|
||||
"""
|
||||
|
||||
|
||||
def dict_kv(value, key):
|
||||
"""Return a dictionary with a single key-value pair
|
||||
|
||||
Example:
|
||||
|
||||
- hosts: localhost
|
||||
gather_facts: false
|
||||
vars:
|
||||
myvar: myvalue
|
||||
tasks:
|
||||
- debug:
|
||||
msg: "{{ myvar | dict_kv('thatsmyvar') }}"
|
||||
|
||||
produces:
|
||||
|
||||
ok: [localhost] => {
|
||||
"msg": {
|
||||
"thatsmyvar": "myvalue"
|
||||
}
|
||||
}
|
||||
|
||||
Example 2:
|
||||
|
||||
- hosts: localhost
|
||||
gather_facts: false
|
||||
vars:
|
||||
common_config:
|
||||
type: host
|
||||
database: all
|
||||
myservers:
|
||||
- server1
|
||||
- server2
|
||||
tasks:
|
||||
- debug:
|
||||
msg: "{{ myservers | map('dict_kv', 'server') | map('combine', common_config) }}"
|
||||
|
||||
produces:
|
||||
|
||||
ok: [localhost] => {
|
||||
"msg": [
|
||||
{
|
||||
"database": "all",
|
||||
"server": "server1",
|
||||
"type": "host"
|
||||
},
|
||||
{
|
||||
"database": "all",
|
||||
"server": "server2",
|
||||
"type": "host"
|
||||
}
|
||||
]
|
||||
}
|
||||
"""
|
||||
return {key: value}
|
||||
|
||||
|
||||
class FilterModule:
|
||||
"""Query filter"""
|
||||
|
||||
def filters(self):
|
||||
return {"dict_kv": dict_kv}
|
||||
+118
@@ -0,0 +1,118 @@
|
||||
# Copyright (c) 2021, Andrew Pantuso (@ajpantuso) <ajpantuso@gmail.com>
|
||||
# Copyright (c) 2018, Dag Wieers (@dagwieers) <dag@wieers.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
|
||||
|
||||
DOCUMENTATION = r"""
|
||||
name: from_csv
|
||||
short_description: Converts CSV text input into list of dicts
|
||||
version_added: 2.3.0
|
||||
author: Andrew Pantuso (@Ajpantuso)
|
||||
description:
|
||||
- Converts CSV text input into list of dictionaries.
|
||||
options:
|
||||
_input:
|
||||
description: A string containing a CSV document.
|
||||
type: string
|
||||
required: true
|
||||
dialect:
|
||||
description:
|
||||
- The CSV dialect to use when parsing the CSV file.
|
||||
- Possible values include V(excel), V(excel-tab) or V(unix).
|
||||
type: str
|
||||
default: excel
|
||||
fieldnames:
|
||||
description:
|
||||
- A list of field names for every column.
|
||||
- This is needed if the CSV does not have a header.
|
||||
type: list
|
||||
elements: str
|
||||
delimiter:
|
||||
description:
|
||||
- A one-character string used to separate fields.
|
||||
- When using this parameter, you change the default value used by O(dialect).
|
||||
- The default value depends on the dialect used.
|
||||
type: str
|
||||
skipinitialspace:
|
||||
description:
|
||||
- Whether to ignore any whitespaces immediately following the delimiter.
|
||||
- When using this parameter, you change the default value used by O(dialect).
|
||||
- The default value depends on the dialect used.
|
||||
type: bool
|
||||
strict:
|
||||
description:
|
||||
- Whether to raise an exception on bad CSV input.
|
||||
- When using this parameter, you change the default value used by O(dialect).
|
||||
- The default value depends on the dialect used.
|
||||
type: bool
|
||||
"""
|
||||
|
||||
EXAMPLES = r"""
|
||||
- name: Parse a CSV file's contents
|
||||
ansible.builtin.debug:
|
||||
msg: >-
|
||||
{{ csv_data | community.general.from_csv(dialect='unix') }}
|
||||
vars:
|
||||
csv_data: |
|
||||
Column 1,Value
|
||||
foo,23
|
||||
bar,42
|
||||
# Produces the following list of dictionaries:
|
||||
# {
|
||||
# "Column 1": "foo",
|
||||
# "Value": "23",
|
||||
# },
|
||||
# {
|
||||
# "Column 1": "bar",
|
||||
# "Value": "42",
|
||||
# }
|
||||
"""
|
||||
|
||||
RETURN = r"""
|
||||
_value:
|
||||
description: A list with one dictionary per row.
|
||||
type: list
|
||||
elements: dictionary
|
||||
"""
|
||||
|
||||
from ansible.errors import AnsibleFilterError
|
||||
|
||||
from ansible_collections.community.general.plugins.module_utils._csv import (
|
||||
CSVError,
|
||||
CustomDialectFailureError,
|
||||
DialectNotAvailableError,
|
||||
initialize_dialect,
|
||||
read_csv,
|
||||
)
|
||||
|
||||
|
||||
def from_csv(data, dialect="excel", fieldnames=None, delimiter=None, skipinitialspace=None, strict=None):
|
||||
dialect_params = {
|
||||
"delimiter": delimiter,
|
||||
"skipinitialspace": skipinitialspace,
|
||||
"strict": strict,
|
||||
}
|
||||
|
||||
try:
|
||||
dialect = initialize_dialect(dialect, **dialect_params)
|
||||
except (CustomDialectFailureError, DialectNotAvailableError) as e:
|
||||
raise AnsibleFilterError(str(e)) from e
|
||||
|
||||
reader = read_csv(data, dialect, fieldnames)
|
||||
|
||||
data_list = []
|
||||
|
||||
try:
|
||||
for row in reader:
|
||||
data_list.append(row)
|
||||
except CSVError as e:
|
||||
raise AnsibleFilterError(f"Unable to process file: {e}") from e
|
||||
|
||||
return data_list
|
||||
|
||||
|
||||
class FilterModule:
|
||||
def filters(self):
|
||||
return {"from_csv": from_csv}
|
||||
+117
@@ -0,0 +1,117 @@
|
||||
# Copyright (c) 2023, Steffen Scheib <steffen@scheib.me>
|
||||
# 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"""
|
||||
name: from_ini
|
||||
short_description: Converts INI text input into a dictionary
|
||||
version_added: 8.2.0
|
||||
author: Steffen Scheib (@sscheib)
|
||||
description:
|
||||
- Converts INI text input into a dictionary.
|
||||
options:
|
||||
_input:
|
||||
description: A string containing an INI document.
|
||||
type: string
|
||||
required: true
|
||||
delimiters:
|
||||
description: A list of characters used as delimiters in the INI document.
|
||||
type: list
|
||||
elements: string
|
||||
default:
|
||||
- "="
|
||||
- ":"
|
||||
version_added: 12.4.0
|
||||
seealso:
|
||||
- plugin: community.general.to_ini
|
||||
plugin_type: filter
|
||||
- plugin: ansible.builtin.ini
|
||||
plugin_type: lookup
|
||||
- module: community.general.ini_file
|
||||
"""
|
||||
|
||||
EXAMPLES = r"""
|
||||
- name: Slurp an INI file
|
||||
ansible.builtin.slurp:
|
||||
src: /etc/rhsm/rhsm.conf
|
||||
register: rhsm_conf
|
||||
|
||||
- name: Display the INI file as dictionary
|
||||
ansible.builtin.debug:
|
||||
var: rhsm_conf.content | b64decode | community.general.from_ini
|
||||
|
||||
- name: Set a new dictionary fact with the contents of the INI file
|
||||
ansible.builtin.set_fact:
|
||||
rhsm_dict: >-
|
||||
{{
|
||||
rhsm_conf.content | b64decode | community.general.from_ini
|
||||
}}
|
||||
"""
|
||||
|
||||
RETURN = r"""
|
||||
_value:
|
||||
description: A dictionary representing the INI file.
|
||||
type: dictionary
|
||||
"""
|
||||
|
||||
|
||||
from configparser import ConfigParser
|
||||
from io import StringIO
|
||||
|
||||
from ansible.errors import AnsibleFilterError
|
||||
from ansible.module_utils.common.collections import is_sequence
|
||||
|
||||
|
||||
class IniParser(ConfigParser):
|
||||
"""Implements a configparser which is able to return a dict"""
|
||||
|
||||
def __init__(self, delimiters=None):
|
||||
if delimiters is None:
|
||||
super().__init__(interpolation=None)
|
||||
else:
|
||||
super().__init__(interpolation=None, delimiters=delimiters)
|
||||
self.optionxform = str
|
||||
|
||||
def as_dict(self):
|
||||
d = dict(self._sections)
|
||||
for k in d:
|
||||
d[k] = dict(self._defaults, **d[k])
|
||||
d[k].pop("__name__", None)
|
||||
|
||||
if self._defaults:
|
||||
d["DEFAULT"] = dict(self._defaults)
|
||||
|
||||
return d
|
||||
|
||||
|
||||
def from_ini(obj, delimiters=None):
|
||||
"""Read the given string as INI file and return a dict"""
|
||||
|
||||
if not isinstance(obj, str):
|
||||
raise AnsibleFilterError(f"from_ini requires a str, got {type(obj)}")
|
||||
if delimiters is not None:
|
||||
if not is_sequence(delimiters):
|
||||
raise AnsibleFilterError(f"from_ini's delimiters parameter must be a sequence, got {type(delimiters)}")
|
||||
delimiters = tuple(delimiters)
|
||||
if not all(isinstance(elt, str) for elt in delimiters):
|
||||
raise AnsibleFilterError(
|
||||
f"from_ini's delimiters parameter must be a sequence of strings, got {delimiters!r}"
|
||||
)
|
||||
|
||||
parser = IniParser(delimiters=delimiters)
|
||||
|
||||
try:
|
||||
parser.read_file(StringIO(obj))
|
||||
except Exception as ex:
|
||||
raise AnsibleFilterError(f"from_ini failed to parse given string: {ex}", orig_exc=ex) from ex
|
||||
|
||||
return parser.as_dict()
|
||||
|
||||
|
||||
class FilterModule:
|
||||
"""Query filter"""
|
||||
|
||||
def filters(self):
|
||||
return {"from_ini": from_ini}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
# Copyright (c) Contributors to the Ansible project
|
||||
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import tomllib
|
||||
import typing as t
|
||||
from collections.abc import Mapping
|
||||
|
||||
from ansible.errors import AnsibleFilterError
|
||||
|
||||
|
||||
def from_toml(value: t.Any) -> Mapping:
|
||||
if not isinstance(value, str):
|
||||
raise AnsibleFilterError("from_toml only accepts strings.")
|
||||
return tomllib.loads(value)
|
||||
|
||||
|
||||
class FilterModule:
|
||||
def filters(self):
|
||||
return {
|
||||
"from_toml": from_toml,
|
||||
}
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
---
|
||||
# Copyright (c) Contributors to the Ansible project
|
||||
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
DOCUMENTATION:
|
||||
name: from_toml
|
||||
author:
|
||||
- Christian Schürmann (@spike77453)
|
||||
version_added: 13.1.0
|
||||
short_description: Convert TOML string into dictionary
|
||||
description:
|
||||
- Converts a string containing a TOML document into an Ansible variable
|
||||
positional: _input
|
||||
options:
|
||||
_input:
|
||||
description:
|
||||
- A string that contains a TOML document.
|
||||
type: str
|
||||
required: true
|
||||
|
||||
EXAMPLES: |
|
||||
- name: Slurp TOML file
|
||||
ansible.builtin.slurp:
|
||||
src: config.toml
|
||||
register: config
|
||||
|
||||
- name: Convert data into dictionary
|
||||
ansible.builtin.set_fact:
|
||||
my_config: "{{ config['content'] | b64decode | community.general.from_toml }}"
|
||||
|
||||
|
||||
RETURN:
|
||||
_value:
|
||||
description:
|
||||
- Dictionary representing the data from the TOML string.
|
||||
type: dict
|
||||
+90
@@ -0,0 +1,90 @@
|
||||
# Copyright (c) 2021, Felix Fontein <felix@fontein.de>
|
||||
# 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"""
|
||||
name: groupby_as_dict
|
||||
short_description: Transform a sequence of dictionaries to a dictionary where the dictionaries are indexed by an attribute
|
||||
version_added: 3.1.0
|
||||
author: Felix Fontein (@felixfontein)
|
||||
description:
|
||||
- Transform a sequence of dictionaries to a dictionary where the dictionaries are indexed by an attribute.
|
||||
- This filter is similar to the Jinja2 C(groupby) filter. Use the Jinja2 C(groupby) filter if you have multiple entries
|
||||
with the same value, or when you need a dictionary with list values, or when you need to use deeply nested attributes.
|
||||
positional: attribute
|
||||
options:
|
||||
_input:
|
||||
description: A list of dictionaries.
|
||||
type: list
|
||||
elements: dictionary
|
||||
required: true
|
||||
attribute:
|
||||
description: The attribute to use as the key.
|
||||
type: str
|
||||
required: true
|
||||
"""
|
||||
|
||||
EXAMPLES = r"""
|
||||
- name: Arrange a list of dictionaries as a dictionary of dictionaries
|
||||
ansible.builtin.debug:
|
||||
msg: "{{ sequence | community.general.groupby_as_dict('key') }}"
|
||||
vars:
|
||||
sequence:
|
||||
- key: value
|
||||
foo: bar
|
||||
- key: other_value
|
||||
baz: bar
|
||||
# Produces the following nested structure:
|
||||
#
|
||||
# value:
|
||||
# key: value
|
||||
# foo: bar
|
||||
# other_value:
|
||||
# key: other_value
|
||||
# baz: bar
|
||||
"""
|
||||
|
||||
RETURN = r"""
|
||||
_value:
|
||||
description: A dictionary containing the dictionaries from the list as values.
|
||||
type: dictionary
|
||||
"""
|
||||
|
||||
from collections.abc import Mapping, Sequence
|
||||
|
||||
from ansible.errors import AnsibleFilterError
|
||||
|
||||
|
||||
def groupby_as_dict(sequence, attribute):
|
||||
"""
|
||||
Given a sequence of dictionaries and an attribute name, returns a dictionary mapping
|
||||
the value of this attribute to the dictionary.
|
||||
|
||||
If multiple dictionaries in the sequence have the same value for this attribute,
|
||||
the filter will fail.
|
||||
"""
|
||||
if not isinstance(sequence, Sequence):
|
||||
raise AnsibleFilterError("Input is not a sequence")
|
||||
|
||||
result = dict()
|
||||
for list_index, element in enumerate(sequence):
|
||||
if not isinstance(element, Mapping):
|
||||
raise AnsibleFilterError(f"Sequence element #{list_index} is not a mapping")
|
||||
if attribute not in element:
|
||||
raise AnsibleFilterError(f"Attribute not contained in element #{list_index} of sequence")
|
||||
result_index = element[attribute]
|
||||
if result_index in result:
|
||||
raise AnsibleFilterError(f"Multiple sequence entries have attribute value {result_index!r}")
|
||||
result[result_index] = element
|
||||
return result
|
||||
|
||||
|
||||
class FilterModule:
|
||||
"""Ansible list filters"""
|
||||
|
||||
def filters(self):
|
||||
return {
|
||||
"groupby_as_dict": groupby_as_dict,
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
# Copyright (c) 2021, Andrew Pantuso (@ajpantuso) <ajpantuso@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
|
||||
|
||||
from ansible.errors import (
|
||||
AnsibleError,
|
||||
AnsibleFilterError,
|
||||
)
|
||||
from ansible.module_utils.common.collections import is_sequence
|
||||
|
||||
try:
|
||||
from ansible.errors import AnsibleTypeError
|
||||
except ImportError:
|
||||
from ansible.errors import AnsibleFilterTypeError as AnsibleTypeError # type: ignore
|
||||
|
||||
try:
|
||||
from hashids import Hashids
|
||||
|
||||
HAS_HASHIDS = True
|
||||
except ImportError:
|
||||
HAS_HASHIDS = False
|
||||
|
||||
|
||||
def initialize_hashids(**kwargs):
|
||||
if not HAS_HASHIDS:
|
||||
raise AnsibleError("The hashids library must be installed in order to use this plugin")
|
||||
|
||||
params = {k: v for k, v in kwargs.items() if v}
|
||||
|
||||
try:
|
||||
return Hashids(**params)
|
||||
except TypeError as e:
|
||||
str_params = ", ".join([f"{k}={v}" for k, v in params.items()])
|
||||
raise AnsibleFilterError(f"The provided parameters {str_params} are invalid: {e}") from e
|
||||
|
||||
|
||||
def hashids_encode(nums, salt=None, alphabet=None, min_length=None):
|
||||
"""Generates a YouTube-like hash from a sequence of ints
|
||||
|
||||
:nums: Sequence of one or more ints to hash
|
||||
:salt: String to use as salt when hashing
|
||||
:alphabet: String of 16 or more unique characters to produce a hash
|
||||
:min_length: Minimum length of hash produced
|
||||
"""
|
||||
|
||||
hashids = initialize_hashids(salt=salt, alphabet=alphabet, min_length=min_length)
|
||||
|
||||
# Handles the case where a single int is not encapsulated in a list or tuple.
|
||||
# User convenience seems preferable to strict typing in this case
|
||||
# Also avoids obfuscated error messages related to single invalid inputs
|
||||
if not is_sequence(nums):
|
||||
nums = [nums]
|
||||
|
||||
try:
|
||||
hashid = hashids.encode(*nums)
|
||||
except TypeError as e:
|
||||
raise AnsibleTypeError(f"Data to encode must by a tuple or list of ints: {e}") from e
|
||||
|
||||
return hashid
|
||||
|
||||
|
||||
def hashids_decode(hashid, salt=None, alphabet=None, min_length=None):
|
||||
"""Decodes a YouTube-like hash to a sequence of ints
|
||||
|
||||
:hashid: Hash string to decode
|
||||
:salt: String to use as salt when hashing
|
||||
:alphabet: String of 16 or more unique characters to produce a hash
|
||||
:min_length: Minimum length of hash produced
|
||||
"""
|
||||
|
||||
hashids = initialize_hashids(salt=salt, alphabet=alphabet, min_length=min_length)
|
||||
nums = hashids.decode(hashid)
|
||||
return list(nums)
|
||||
|
||||
|
||||
class FilterModule:
|
||||
def filters(self):
|
||||
return {
|
||||
"hashids_encode": hashids_encode,
|
||||
"hashids_decode": hashids_decode,
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user