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

This commit is contained in:
2026-11-11 12:13:20 +01:00
parent acb5c4ba82
commit 72fb458dab
3659 changed files with 471307 additions and 12 deletions
@@ -0,0 +1,35 @@
# 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
import pytest
from ansible.cli.arguments import option_helpers as opt_help
from ansible.utils import context_objects as co
@pytest.fixture
def parser():
parser = opt_help.create_base_parser("testparser")
opt_help.add_runas_options(parser)
opt_help.add_meta_options(parser)
opt_help.add_runtask_options(parser)
opt_help.add_vault_options(parser)
opt_help.add_async_options(parser)
opt_help.add_connect_options(parser)
opt_help.add_subset_options(parser)
opt_help.add_check_options(parser)
opt_help.add_inventory_options(parser)
return parser
@pytest.fixture
def reset_cli_args():
co.GlobalCLIArgs._Singleton__instance = None
yield
co.GlobalCLIArgs._Singleton__instance = None
@@ -0,0 +1,16 @@
# 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
from ansible.plugins.loader import become_loader, get_shell_plugin
def call_become_plugin(task, var_options, cmd, executable=None):
"""Helper function to call become plugin similarly on how Ansible itself handles this."""
plugin = become_loader.get(task["become_method"])
plugin.set_options(task_keys=task, var_options=var_options)
shell = get_shell_plugin(executable=executable)
return plugin.build_become_command(cmd, shell)
@@ -0,0 +1,92 @@
# Copyright (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com>
# Copyright (c) 2020 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
import re
from ansible import context
from .helper import call_become_plugin
def test_doas_basic(mocker, parser, reset_cli_args):
options = parser.parse_args([])
context._init_global_context(options)
default_cmd = "/bin/foo"
default_exe = "/bin/bash"
doas_exe = "doas"
doas_flags = "-n"
success = "BECOME-SUCCESS-.+?"
task = {
"become_method": "community.general.doas",
}
var_options = {}
cmd = call_become_plugin(task, var_options, cmd=default_cmd, executable=default_exe)
print(cmd)
assert re.match(f"""{doas_exe} {doas_flags} {default_exe} -c 'echo {success}; {default_cmd}'""", cmd) is not None
def test_doas(mocker, parser, reset_cli_args):
options = parser.parse_args([])
context._init_global_context(options)
default_cmd = "/bin/foo"
default_exe = "/bin/bash"
doas_exe = "doas"
doas_flags = "-n"
success = "BECOME-SUCCESS-.+?"
task = {
"become_user": "foo",
"become_method": "community.general.doas",
"become_flags": doas_flags,
}
var_options = {}
cmd = call_become_plugin(task, var_options, cmd=default_cmd, executable=default_exe)
print(cmd)
assert (
re.match(
f"""{doas_exe} {doas_flags} -u {task["become_user"]} {default_exe} -c 'echo {success}; {default_cmd}'""",
cmd,
)
is not None
)
def test_doas_varoptions(mocker, parser, reset_cli_args):
options = parser.parse_args([])
context._init_global_context(options)
default_cmd = "/bin/foo"
default_exe = "/bin/bash"
doas_exe = "doas"
doas_flags = "-n"
success = "BECOME-SUCCESS-.+?"
task = {
"become_user": "foo",
"become_method": "community.general.doas",
"become_flags": "xxx",
}
var_options = {
"ansible_become_user": "bar",
"ansible_become_flags": doas_flags,
}
cmd = call_become_plugin(task, var_options, cmd=default_cmd, executable=default_exe)
print(cmd)
assert (
re.match(
f"""{doas_exe} {doas_flags} -u {var_options["ansible_become_user"]} {default_exe} -c 'echo {success}; {default_cmd}'""",
cmd,
)
is not None
)
@@ -0,0 +1,114 @@
# Copyright (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com>
# Copyright (c) 2020 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
import re
from ansible import context
from .helper import call_become_plugin
def test_dzdo_basic(mocker, parser, reset_cli_args):
options = parser.parse_args([])
context._init_global_context(options)
default_cmd = "/bin/foo"
default_exe = "/bin/bash"
dzdo_exe = "dzdo"
dzdo_flags = "-H -S -n"
success = "BECOME-SUCCESS-.+?"
task = {
"become_method": "community.general.dzdo",
}
var_options = {}
cmd = call_become_plugin(task, var_options, cmd=default_cmd, executable=default_exe)
print(cmd)
assert re.match(f"""{dzdo_exe} {dzdo_flags} {default_exe} -c 'echo {success}; {default_cmd}'""", cmd) is not None
def test_dzdo(mocker, parser, reset_cli_args):
options = parser.parse_args([])
context._init_global_context(options)
default_cmd = "/bin/foo"
default_exe = "/bin/bash"
dzdo_exe = "dzdo"
dzdo_flags = ""
success = "BECOME-SUCCESS-.+?"
task = {
"become_user": "foo",
"become_method": "community.general.dzdo",
"become_flags": dzdo_flags,
}
var_options = {}
cmd = call_become_plugin(task, var_options, cmd=default_cmd, executable=default_exe)
print(cmd)
assert (
re.match(
f"""{dzdo_exe} {dzdo_flags} -u {task["become_user"]} {default_exe} -c 'echo {success}; {default_cmd}'""",
cmd,
)
is not None
)
task["become_pass"] = "testpass"
cmd = call_become_plugin(task, var_options, cmd=default_cmd, executable=default_exe)
print(cmd)
password_pattern = r"\"\[dzdo via ansible, key=.+?\] password:\""
assert (
re.match(
f"""{dzdo_exe} {dzdo_flags} -p {password_pattern} -u {task["become_user"]} {default_exe} -c 'echo {success}; {default_cmd}'""",
cmd,
)
is not None
)
def test_dzdo_varoptions(mocker, parser, reset_cli_args):
options = parser.parse_args([])
context._init_global_context(options)
default_cmd = "/bin/foo"
default_exe = "/bin/bash"
dzdo_exe = "dzdo"
dzdo_flags = ""
success = "BECOME-SUCCESS-.+?"
task = {
"become_user": "foo",
"become_method": "community.general.dzdo",
"become_flags": "xxx",
}
var_options = {
"ansible_become_user": "bar",
"ansible_become_flags": dzdo_flags,
}
cmd = call_become_plugin(task, var_options, cmd=default_cmd, executable=default_exe)
print(cmd)
assert (
re.match(
f"""{dzdo_exe} {dzdo_flags} -u {var_options["ansible_become_user"]} {default_exe} -c 'echo {success}; {default_cmd}'""",
cmd,
)
is not None
)
var_options["ansible_become_pass"] = "testpass"
cmd = call_become_plugin(task, var_options, cmd=default_cmd, executable=default_exe)
print(cmd)
password_pattern = r"\"\[dzdo via ansible, key=.+?\] password:\""
assert (
re.match(
f"""{dzdo_exe} {dzdo_flags} -p {password_pattern} -u {var_options["ansible_become_user"]} {default_exe} -c 'echo {success}; {default_cmd}'""",
cmd,
)
is not None
)
@@ -0,0 +1,97 @@
# Copyright (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com>
# Copyright (c) 2020 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
import re
from ansible import context
from .helper import call_become_plugin
def test_ksu_basic(mocker, parser, reset_cli_args):
options = parser.parse_args([])
context._init_global_context(options)
default_cmd = "/bin/foo"
default_exe = "/bin/bash"
ksu_exe = "ksu"
ksu_flags = ""
success = "BECOME-SUCCESS-.+?"
task = {
"become_user": "foo",
"become_method": "community.general.ksu",
}
var_options = {}
cmd = call_become_plugin(task, var_options, cmd=default_cmd, executable=default_exe)
print(cmd)
assert (
re.match(
f"""{ksu_exe} {task["become_user"]} {ksu_flags} -e {default_exe} -c 'echo {success}; {default_cmd}'""", cmd
)
is not None
)
def test_ksu(mocker, parser, reset_cli_args):
options = parser.parse_args([])
context._init_global_context(options)
default_cmd = "/bin/foo"
default_exe = "/bin/bash"
ksu_exe = "ksu"
ksu_flags = ""
success = "BECOME-SUCCESS-.+?"
task = {
"become_user": "foo",
"become_method": "community.general.ksu",
"become_flags": ksu_flags,
}
var_options = {}
cmd = call_become_plugin(task, var_options, cmd=default_cmd, executable=default_exe)
print(cmd)
assert (
re.match(
f"""{ksu_exe} {task["become_user"]} {ksu_flags} -e {default_exe} -c 'echo {success}; {default_cmd}'""", cmd
)
is not None
)
def test_ksu_varoptions(mocker, parser, reset_cli_args):
options = parser.parse_args([])
context._init_global_context(options)
default_cmd = "/bin/foo"
default_exe = "/bin/bash"
ksu_exe = "ksu"
ksu_flags = ""
success = "BECOME-SUCCESS-.+?"
task = {
"become_user": "foo",
"become_method": "community.general.ksu",
"become_flags": "xxx",
}
var_options = {
"ansible_become_user": "bar",
"ansible_become_flags": ksu_flags,
}
cmd = call_become_plugin(task, var_options, cmd=default_cmd, executable=default_exe)
print(cmd)
assert (
re.match(
f"""{ksu_exe} {var_options["ansible_become_user"]} {ksu_flags} -e {default_exe} -c 'echo {success}; {default_cmd}'""",
cmd,
)
is not None
)
@@ -0,0 +1,64 @@
# Copyright (c) 2026 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
import re
from ansible import context
from .helper import call_become_plugin
def test_machinectl_basic(mocker, parser, reset_cli_args):
options = parser.parse_args([])
context._init_global_context(options)
default_cmd = "/bin/foo"
default_exe = "/bin/sh"
machinectl_exe = "machinectl"
success = "BECOME-SUCCESS-.+?"
task = {
"become_method": "community.general.machinectl",
"become_user": "root",
}
var_options = {}
cmd = call_become_plugin(task, var_options, cmd=default_cmd, executable=default_exe)
assert (
re.match(
f"SYSTEMD_COLORS=0 {machinectl_exe} -q shell root@ {default_exe} -c 'echo {success}; {default_cmd}'",
cmd,
)
is not None
)
def test_machinectl_flags(mocker, parser, reset_cli_args):
options = parser.parse_args([])
context._init_global_context(options)
default_cmd = "/bin/foo"
default_exe = "/bin/sh"
machinectl_exe = "machinectl"
machinectl_flags = "--setenv=FOO=bar"
success = "BECOME-SUCCESS-.+?"
task = {
"become_method": "community.general.machinectl",
"become_user": "root",
"become_flags": machinectl_flags,
}
var_options = {}
cmd = call_become_plugin(task, var_options, cmd=default_cmd, executable=default_exe)
assert (
re.match(
f"SYSTEMD_COLORS=0 {machinectl_exe} -q shell --setenv=FOO=bar root@ {default_exe} -c 'echo {success}; {default_cmd}'",
cmd,
)
is not None
)
@@ -0,0 +1,89 @@
# Copyright (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com>
# Copyright (c) 2020 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
import re
from ansible import context
from .helper import call_become_plugin
def test_pbrun_basic(mocker, parser, reset_cli_args):
options = parser.parse_args([])
context._init_global_context(options)
default_cmd = "/bin/foo"
default_exe = "/bin/bash"
pbrun_exe = "pbrun"
pbrun_flags = ""
success = "BECOME-SUCCESS-.+?"
task = {
"become_method": "community.general.pbrun",
}
var_options = {}
cmd = call_become_plugin(task, var_options, cmd=default_cmd, executable=default_exe)
print(cmd)
assert re.match(f"""{pbrun_exe} {pbrun_flags} 'echo {success}; {default_cmd}'""", cmd) is not None
def test_pbrun(mocker, parser, reset_cli_args):
options = parser.parse_args([])
context._init_global_context(options)
default_cmd = "/bin/foo"
default_exe = "/bin/bash"
pbrun_exe = "pbrun"
pbrun_flags = ""
success = "BECOME-SUCCESS-.+?"
task = {
"become_user": "foo",
"become_method": "community.general.pbrun",
"become_flags": pbrun_flags,
}
var_options = {}
cmd = call_become_plugin(task, var_options, cmd=default_cmd, executable=default_exe)
print(cmd)
assert (
re.match(f"""{pbrun_exe} {pbrun_flags} -u {task["become_user"]} 'echo {success}; {default_cmd}'""", cmd)
is not None
)
def test_pbrun_var_varoptions(mocker, parser, reset_cli_args):
options = parser.parse_args([])
context._init_global_context(options)
default_cmd = "/bin/foo"
default_exe = "/bin/bash"
pbrun_exe = "pbrun"
pbrun_flags = ""
success = "BECOME-SUCCESS-.+?"
task = {
"become_user": "foo",
"become_method": "community.general.pbrun",
"become_flags": "xxx",
}
var_options = {
"ansible_become_user": "bar",
"ansible_become_flags": pbrun_flags,
}
cmd = call_become_plugin(task, var_options, cmd=default_cmd, executable=default_exe)
print(cmd)
assert (
re.match(
f"""{pbrun_exe} {pbrun_flags} -u {var_options["ansible_become_user"]} 'echo {success}; {default_cmd}'""",
cmd,
)
is not None
)
@@ -0,0 +1,109 @@
# Copyright (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com>
# Copyright (c) 2020 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
import re
from ansible import context
from .helper import call_become_plugin
def test_pfexec_wrap(mocker, parser, reset_cli_args):
"""Test pfexec with wrap_exe explicitly enabled."""
options = parser.parse_args([])
context._init_global_context(options)
default_cmd = "/bin/foo"
default_exe = "/bin/bash"
pfexec_exe = "pfexec"
success = "BECOME-SUCCESS-.+?"
task = {
"become_method": "community.general.pfexec",
}
var_options = {
"ansible_pfexec_wrap_execution": "true",
}
cmd = call_become_plugin(task, var_options, cmd=default_cmd, executable=default_exe)
print(cmd)
assert re.match(f"""{pfexec_exe} {default_exe} -c 'echo {success}; {default_cmd}'""", cmd) is not None
def test_pfexec_no_wrap(mocker, parser, reset_cli_args):
"""Test pfexec with wrap_exe explicitly disabled."""
options = parser.parse_args([])
context._init_global_context(options)
default_cmd = "/bin/foo"
default_exe = "/bin/bash"
pfexec_exe = "pfexec"
success = "BECOME-SUCCESS-.+?"
task = {
"become_method": "community.general.pfexec",
"become_flags": "",
}
var_options = {
"ansible_pfexec_wrap_execution": "false",
}
cmd = call_become_plugin(task, var_options, cmd=default_cmd, executable=default_exe)
print(cmd)
assert re.match(f"""{pfexec_exe} 'echo {success}; {default_cmd}'""", cmd) is not None
def test_pfexec_custom_flags(mocker, parser, reset_cli_args):
"""Test pfexec with custom flags and wrap_exe enabled."""
options = parser.parse_args([])
context._init_global_context(options)
default_cmd = "/bin/foo"
default_exe = "/bin/bash"
pfexec_exe = "pfexec"
pfexec_flags = "-P basic"
success = "BECOME-SUCCESS-.+?"
task = {
"become_method": "community.general.pfexec",
"become_flags": pfexec_flags,
}
var_options = {}
cmd = call_become_plugin(task, var_options, cmd=default_cmd, executable=default_exe)
print(cmd)
assert (
re.match(f"""{pfexec_exe} {pfexec_flags} {default_exe} -c 'echo {success}; {default_cmd}'""", cmd) is not None
)
def test_pfexec_varoptions(mocker, parser, reset_cli_args):
"""Test that var_options override task options."""
options = parser.parse_args([])
context._init_global_context(options)
default_cmd = "/bin/foo"
default_exe = "/bin/bash"
pfexec_exe = "pfexec"
success = "BECOME-SUCCESS-.+?"
task = {
"become_user": "foo",
"become_method": "community.general.pfexec",
"become_flags": "xxx",
}
var_options = {
"ansible_become_user": "bar",
"ansible_become_flags": "",
"ansible_pfexec_wrap_execution": "true",
}
cmd = call_become_plugin(task, var_options, cmd=default_cmd, executable=default_exe)
print(cmd)
# var_options override task flags, so flags should be empty
assert re.match(f"""{pfexec_exe} {default_exe} -c 'echo {success}; {default_cmd}'""", cmd) is not None
@@ -0,0 +1,62 @@
# 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
import re
from ansible import context
from .helper import call_become_plugin
def test_run0_basic(mocker, parser, reset_cli_args):
options = parser.parse_args([])
context._init_global_context(options)
default_cmd = "/bin/foo"
default_exe = "/bin/sh"
run0_exe = "run0"
success = "BECOME-SUCCESS-.+?"
task = {
"become_method": "community.general.run0",
}
var_options = {}
cmd = call_become_plugin(task, var_options, cmd=default_cmd, executable=default_exe)
assert (
re.match(
f"SYSTEMD_COLORS=0 {run0_exe} --user=root {default_exe} -c 'echo {success}; {default_cmd}'",
cmd,
)
is not None
)
def test_run0_flags(mocker, parser, reset_cli_args):
options = parser.parse_args([])
context._init_global_context(options)
default_cmd = "/bin/foo"
default_exe = "/bin/sh"
run0_exe = "run0"
run0_flags = "--nice=15"
success = "BECOME-SUCCESS-.+?"
task = {
"become_method": "community.general.run0",
"become_flags": run0_flags,
}
var_options = {}
cmd = call_become_plugin(task, var_options, cmd=default_cmd, executable=default_exe)
assert (
re.match(
f"SYSTEMD_COLORS=0 {run0_exe} --user=root --nice=15 {default_exe} -c 'echo {success}; {default_cmd}'",
cmd,
)
is not None
)
@@ -0,0 +1,60 @@
# Copyright (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com>
# 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
import re
from ansible import context
from .helper import call_become_plugin
def test_sudosu(mocker, parser, reset_cli_args):
options = parser.parse_args([])
context._init_global_context(options)
default_cmd = "/bin/foo"
default_exe = "/bin/bash"
sudo_exe = "sudo"
sudo_flags = "-H -s -n"
success = "BECOME-SUCCESS-.+?"
task = {
"become_user": "foo",
"become_method": "community.general.sudosu",
"become_flags": sudo_flags,
}
var_options = {}
cmd = call_become_plugin(task, var_options, cmd=default_cmd, executable=default_exe)
print(cmd)
assert (
re.match(
f"""{sudo_exe} {sudo_flags} su -l {task["become_user"]} {default_exe} -c 'echo {success}; {default_cmd}'""",
cmd,
)
is not None
)
task = {
"become_user": "foo",
"become_method": "community.general.sudosu",
"become_flags": sudo_flags,
"become_pass": "testpass",
}
var_options = {}
cmd = call_become_plugin(task, var_options, cmd=default_cmd, executable=default_exe)
print(cmd)
password_pattern = r"\[sudo via ansible, key=.+?\] password:"
assert (
re.match(
f"""{sudo_exe} {sudo_flags.replace("-n", "")} -p "{password_pattern}" """
f"""su -l {task["become_user"]} {default_exe} -c 'echo {success}; {default_cmd}'""",
cmd,
)
is not None
)
@@ -0,0 +1,17 @@
# Copyright (c) 2012-2015, 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
import pytest
pytest.importorskip("memcache")
from ansible.plugins.loader import cache_loader
from ansible_collections.community.general.plugins.cache.memcached import CacheModule as MemcachedCache
def test_memcached_cachemodule():
assert isinstance(cache_loader.get("community.general.memcached"), MemcachedCache)
@@ -0,0 +1,25 @@
# Copyright (c) 2012-2015, 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
import pytest
pytest.importorskip("redis")
from ansible.plugins.loader import cache_loader
from ansible_collections.community.general.plugins.cache.redis import CacheModule as RedisCache
def test_redis_cachemodule():
# The _uri option is required for the redis plugin
connection = "127.0.0.1:6379:1"
assert isinstance(cache_loader.get("community.general.redis", **{"_uri": connection}), RedisCache)
def test_redis_cachemodule_2():
# The _uri option is required for the redis plugin
connection = "[::1]:6379:1"
assert isinstance(cache_loader.get("community.general.redis", **{"_uri": connection}), RedisCache)
@@ -0,0 +1,127 @@
# 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
import unittest
from collections import OrderedDict
from unittest.mock import MagicMock, Mock, patch
import pytest
from ansible.executor.task_result import TaskResult
from ansible.playbook.task import Task
from ansible.release import __version__ as ansible_release
from ansible_collections.community.general.plugins.callback.elastic import ElasticSource, TaskData
if tuple(int(x) for x in ansible_release.split(".")[:2]) >= (2, 21):
# https://github.com/ansible/ansible/issues/86761
pytest.skip("Temporarily skipping callback tests for ansible-core >= 2.21", allow_module_level=True)
class TestOpentelemetry(unittest.TestCase):
@patch("ansible_collections.community.general.plugins.callback.elastic.socket")
def setUp(self, mock_socket):
mock_socket.gethostname.return_value = "my-host"
mock_socket.gethostbyname.return_value = "1.2.3.4"
self.elastic = ElasticSource(display=None)
self.task_fields = {"args": {}}
self.mock_host = Mock("MockHost")
self.mock_host.name = "myhost"
self.mock_host._uuid = "myhost_uuid"
self.mock_task = Task()
self.mock_task.action = "myaction"
self.mock_task.no_log = False
self.mock_task._role = "myrole"
self.mock_task._uuid = "myuuid"
self.mock_task.args = {}
self.mock_task.get_name = MagicMock(return_value="mytask")
self.mock_task.get_path = MagicMock(return_value="/mypath")
self.my_task = TaskData("myuuid", "mytask", "/mypath", "myplay", "myaction", "")
self.my_task_result = TaskResult(
host=self.mock_host, task=self.mock_task, return_data={}, task_fields=self.task_fields
)
def test_start_task(self):
tasks_data = OrderedDict()
self.elastic.start_task(tasks_data, False, "myplay", self.mock_task)
task_data = tasks_data["myuuid"]
self.assertEqual(task_data.uuid, "myuuid")
self.assertEqual(task_data.name, "mytask")
self.assertEqual(task_data.path, "/mypath")
self.assertEqual(task_data.play, "myplay")
self.assertEqual(task_data.action, "myaction")
self.assertEqual(task_data.args, "")
def test_finish_task_with_a_host_match(self):
tasks_data = OrderedDict()
tasks_data["myuuid"] = self.my_task
self.elastic.finish_task(tasks_data, "ok", self.my_task_result)
task_data = tasks_data["myuuid"]
host_data = task_data.host_data["myhost_uuid"]
self.assertEqual(host_data.uuid, "myhost_uuid")
self.assertEqual(host_data.name, "myhost")
self.assertEqual(host_data.status, "ok")
def test_finish_task_without_a_host_match(self):
result = TaskResult(host=None, task=self.mock_task, return_data={}, task_fields=self.task_fields)
tasks_data = OrderedDict()
tasks_data["myuuid"] = self.my_task
self.elastic.finish_task(tasks_data, "ok", result)
task_data = tasks_data["myuuid"]
host_data = task_data.host_data["include"]
self.assertEqual(host_data.uuid, "include")
self.assertEqual(host_data.name, "include")
self.assertEqual(host_data.status, "ok")
def test_get_error_message(self):
test_cases = (
("my-exception", "my-msg", None, "my-exception"),
(None, "my-msg", None, "my-msg"),
(None, None, None, "failed"),
)
for tc in test_cases:
result = self.elastic.get_error_message(generate_test_data(tc[0], tc[1], tc[2]))
self.assertEqual(result, tc[3])
def test_enrich_error_message(self):
test_cases = (
(
"my-exception",
"my-msg",
"my-stderr",
'message: "my-msg"\nexception: "my-exception"\nstderr: "my-stderr"',
),
("my-exception", None, "my-stderr", 'message: "failed"\nexception: "my-exception"\nstderr: "my-stderr"'),
(None, "my-msg", "my-stderr", 'message: "my-msg"\nexception: "None"\nstderr: "my-stderr"'),
("my-exception", "my-msg", None, 'message: "my-msg"\nexception: "my-exception"\nstderr: "None"'),
(
"my-exception",
"my-msg",
"\nline1\nline2",
'message: "my-msg"\nexception: "my-exception"\nstderr: "\nline1\nline2"',
),
)
for tc in test_cases:
result = self.elastic.enrich_error_message(generate_test_data(tc[0], tc[1], tc[2]))
self.assertEqual(result, tc[3])
def generate_test_data(exception=None, msg=None, stderr=None):
res_data = OrderedDict()
if exception:
res_data["exception"] = exception
if msg:
res_data["msg"] = msg
if stderr:
res_data["stderr"] = stderr
return res_data
@@ -0,0 +1,90 @@
# 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
import json
import time
import unittest
import unittest.mock
import urllib
import pytest
from ansible.executor.task_result import TaskResult
from ansible.release import __version__ as ansible_release
from ansible_collections.community.general.plugins.callback.loganalytics_ingestion import (
AzureLogAnalyticsIngestionSource,
)
if tuple(int(x) for x in ansible_release.split(".")[:2]) >= (2, 21):
# https://github.com/ansible/ansible/issues/86761
pytest.skip("Temporarily skipping callback tests for ansible-core >= 2.21", allow_module_level=True)
class TestAzureLogAnalyticsIngestion(unittest.TestCase):
dce_url = "https://fake.dce_url.ansible.com"
dcr_id = "fake-dcr-id"
client_id = "fake-client_id"
client_secret = "fake-client-secret"
tenant_id = "fake-tenant-id"
stream_name = "fake-stream-name"
fake_access_token = None
def setUp(self):
self.fake_access_token = json.dumps(
{"expires_in": time.time() + 3600, "access_token": "fake_access_token"}
).encode("utf-8")
@unittest.mock.patch(
"ansible_collections.community.general.plugins.callback.loganalytics_ingestion.open_url", autospec=True
)
@unittest.mock.patch("ansible.executor.task_result.TaskResult")
def test_sending_data(self, task_result_mock, open_url_mock):
"""
Tests sending data by verifying that the expected POST requests are submitted to the expected hosts.
"""
# The data returned from 'open_url' is only ever read during authentication.
open_url_mock.return_value.read.return_value = self.fake_access_token
# TODO: How to set plugin default arguments?
# I tried instantiating the 'CallbackModule' but all it ever did was complain that 'client_id' wasn't defined.
self.loganalytics = AzureLogAnalyticsIngestionSource(
self.dce_url,
self.dcr_id,
3,
True,
self.client_id,
self.client_secret,
self.tenant_id,
self.stream_name,
False,
False,
2,
"community.general.loganalytics_ingestion",
)
assert open_url_mock.call_count == 1
url = urllib.parse.urlparse(open_url_mock.call_args_list[0][0][0])
assert url.netloc == "login.microsoftonline.com"
results = ["foo", "bar", "biz"]
for i, result in enumerate(results, start=1):
host_mock = unittest.mock.Mock("host_mock")
host_mock.name = "fake-name"
task_mock = unittest.mock.Mock("task_mock")
task_mock._role = "fake-role"
task_mock.get_name = lambda r=result: r
task_result = TaskResult(
host=host_mock, task=task_mock, return_data={}, task_fields={"action": "fake-action", "args": {}}
)
self.loganalytics.send_to_loganalytics("fake-playbook", task_result, "OK")
assert open_url_mock.call_count == 1 + i
url = urllib.parse.urlparse(open_url_mock.call_args_list[i][0][0])
assert url.scheme + "://" + url.netloc == self.dce_url
assert json.loads(open_url_mock.call_args_list[i].kwargs.get("data"))[0].get("TaskName") == result
@@ -0,0 +1,372 @@
# 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
import logging
from unittest.mock import Mock, patch
from urllib.error import HTTPError
import pytest
from ansible.errors import AnsibleError
from ansible.plugins.callback import CallbackBase
from ansible_collections.community.general.plugins.callback import logstash as logstash_callback
from ansible_collections.community.general.plugins.callback.logstash import CallbackModule, LogstashHTTPHandler
def _configure_callback(options):
logger = Mock()
formatter = Mock()
logstash = Mock()
with (
patch.object(logstash_callback, "HAS_LOGSTASH", True),
patch.object(logstash_callback, "logstash", logstash, create=True),
patch.object(logstash_callback, "LogstashFormatterVersion1", return_value=formatter) as formatter_class,
patch.object(logstash_callback.logging, "getLogger", return_value=logger),
patch.object(CallbackBase, "set_options"),
):
callback = CallbackModule()
callback._display = Mock()
callback.get_option = Mock(side_effect=options.get)
callback.set_options()
return callback, logger, logstash, formatter_class
def test_http_handler_posts_formatted_event():
formatter = Mock()
formatter.format.return_value = b'{"message": "ansible ok"}'
response = Mock()
response.getcode.return_value = 202
handler = LogstashHTTPHandler(
url="https://logstash.example.com/",
formatter=formatter,
username="logger",
password="secret",
validate_certs=True,
timeout=5,
)
record = logging.makeLogRecord({"msg": "ansible ok", "args": ()})
with patch(
"ansible_collections.community.general.plugins.callback.logstash.open_url",
return_value=response,
) as open_url:
handler.emit(record)
open_url.assert_called_once_with(
"https://logstash.example.com/",
data=b'{"message": "ansible ok"}',
headers={"Content-Type": "application/json"},
method="POST",
timeout=5,
validate_certs=True,
url_username="logger",
url_password="secret",
force_basic_auth=True,
use_netrc=False,
follow_redirects="none",
)
response.close.assert_called_once_with()
@pytest.mark.parametrize("status", [200, 201, 202, 204])
def test_http_handler_accepts_success_status(status):
formatter = Mock()
formatter.format.return_value = b"{}"
response = Mock()
response.getcode.return_value = status
display = Mock()
handler = LogstashHTTPHandler(url="https://logstash.example.com/", formatter=formatter, display=display)
with patch(
"ansible_collections.community.general.plugins.callback.logstash.open_url",
return_value=response,
):
handler.emit(logging.makeLogRecord({"msg": "ansible ok", "args": ()}))
display.warning.assert_not_called()
response.close.assert_called_once_with()
def test_http_handler_sends_client_tls_options():
formatter = Mock()
formatter.format.return_value = b"{}"
response = Mock()
response.getcode.return_value = 204
handler = LogstashHTTPHandler(
url="https://logstash.example.com/events",
formatter=formatter,
ca_path="/etc/pki/ca.pem",
client_cert="/etc/pki/client.pem",
client_key="/etc/pki/client.key",
)
with patch(
"ansible_collections.community.general.plugins.callback.logstash.open_url",
return_value=response,
) as open_url:
handler.emit(logging.makeLogRecord({"msg": "ansible ok", "args": ()}))
assert open_url.call_args.kwargs["ca_path"] == "/etc/pki/ca.pem"
assert open_url.call_args.kwargs["client_cert"] == "/etc/pki/client.pem"
assert open_url.call_args.kwargs["client_key"] == "/etc/pki/client.key"
def test_http_handler_omits_auth_for_empty_credentials():
formatter = Mock()
formatter.format.return_value = b"{}"
response = Mock()
response.getcode.return_value = 204
handler = LogstashHTTPHandler(
url="http://logstash.example.com/",
formatter=formatter,
username="",
password="",
)
with patch(
"ansible_collections.community.general.plugins.callback.logstash.open_url",
return_value=response,
) as open_url:
handler.emit(logging.makeLogRecord({"msg": "ansible ok", "args": ()}))
assert "url_username" not in open_url.call_args.kwargs
assert "url_password" not in open_url.call_args.kwargs
def test_http_handler_retries_too_many_requests():
formatter = Mock()
formatter.format.return_value = b"{}"
response = Mock()
response.getcode.return_value = 202
error = HTTPError("https://logstash.example.com/", 429, "busy", None, None)
handler = LogstashHTTPHandler(url="https://logstash.example.com/", formatter=formatter, retries=1)
with (
patch(
"ansible_collections.community.general.plugins.callback.logstash.open_url",
side_effect=[error, response],
) as open_url,
patch("ansible_collections.community.general.plugins.callback.logstash.time.sleep") as sleep,
patch("ansible_collections.community.general.plugins.callback.logstash.random.uniform", return_value=0.1),
):
handler.emit(logging.makeLogRecord({"msg": "ansible ok", "args": ()}))
assert open_url.call_count == 2
sleep.assert_called_once_with(0.6)
def test_http_handler_does_not_retry_authentication_failures():
formatter = Mock()
formatter.format.return_value = b"{}"
error = HTTPError("https://logstash.example.com/", 401, "unauthorized", None, Mock())
display = Mock()
handler = LogstashHTTPHandler(
url="https://logstash.example.com/",
formatter=formatter,
username="logger",
password="secret",
display=display,
)
with patch(
"ansible_collections.community.general.plugins.callback.logstash.open_url",
side_effect=error,
) as open_url:
with pytest.raises(AnsibleError, match="Logstash HTTP request failed with status code 401") as exc_info:
handler.emit(logging.makeLogRecord({"msg": "ansible ok", "args": ()}))
open_url.assert_called_once()
display.warning.assert_not_called()
assert "secret" not in str(exc_info.value)
error.fp.close.assert_called_once_with()
def test_http_handler_network_error_raises_error():
formatter = Mock()
formatter.format.return_value = b"{}"
display = Mock()
handler = LogstashHTTPHandler(url="https://logstash.example.com/", formatter=formatter, display=display)
with patch(
"ansible_collections.community.general.plugins.callback.logstash.open_url",
side_effect=OSError("connection failed"),
) as open_url:
with pytest.raises(AnsibleError, match="Could not send event to Logstash over HTTP"):
handler.emit(logging.makeLogRecord({"msg": "ansible ok", "args": ()}))
open_url.assert_called_once()
display.warning.assert_not_called()
def test_http_handler_format_error_raises_error():
formatter = Mock()
formatter.format.side_effect = ValueError("invalid event")
display = Mock()
handler = LogstashHTTPHandler(url="https://logstash.example.com/", formatter=formatter, display=display)
with pytest.raises(AnsibleError, match="Could not format event for Logstash HTTP delivery"):
handler.emit(logging.makeLogRecord({"msg": "ansible ok", "args": ()}))
display.warning.assert_not_called()
def test_http_protocol_configures_basic_auth_and_tls():
options = {
"server": "logstash.example.com",
"port": 8080,
"protocol": "https",
"http_path": "events",
"username": "logger",
"password": "secret",
"validate_certs": True,
"ca_path": "/etc/pki/ca.pem",
"client_cert": "/etc/pki/client.pem",
"client_key": "/etc/pki/client.key",
"timeout": 4,
"retries": 10,
"type": "ansible",
"pre_command": None,
"format_version": "v1",
}
callback, logger, logstash_mock, formatter_class = _configure_callback(options)
handler = logger.addHandler.call_args.args[0]
assert isinstance(handler, LogstashHTTPHandler)
assert handler.url == "https://logstash.example.com:8080/events"
assert handler.username == "logger"
assert handler.password == "secret"
assert handler.validate_certs is True
assert handler.ca_path == "/etc/pki/ca.pem"
assert handler.client_cert == "/etc/pki/client.pem"
assert handler.client_key == "/etc/pki/client.key"
assert handler.timeout == 4
# retries is not restricted to a fixed set of choices, higher values are accepted
assert handler.retries == 10
formatter_class.assert_called_once_with(message_type="ansible")
logstash_mock.TCPLogstashHandler.assert_not_called()
assert callback.disabled is False
def test_tcp_protocol_keeps_existing_handler():
options = {
"server": "logstash.example.com",
"port": 5000,
"protocol": "tcp",
"username": None,
"password": None,
"type": "ansible",
"pre_command": None,
"format_version": "v1",
}
callback, logger, logstash, formatter_class = _configure_callback(options)
assert callback.disabled is False
logstash.TCPLogstashHandler.assert_called_once_with("logstash.example.com", 5000, version=1, message_type="ansible")
logger.addHandler.assert_called_once_with(logstash.TCPLogstashHandler.return_value)
formatter_class.assert_not_called()
def test_http_protocol_requires_both_credentials():
options = {
"server": "logstash.example.com",
"port": 8080,
"protocol": "http",
"http_path": "/",
"username": "logger",
"password": None,
"validate_certs": True,
"ca_path": None,
"client_cert": None,
"client_key": None,
"timeout": 10,
"retries": 3,
"type": "ansible",
"pre_command": None,
"format_version": "v1",
}
with pytest.raises(AnsibleError, match="Both Logstash HTTP username and password must be configured."):
_configure_callback(options)
@pytest.mark.parametrize(
("protocol", "ca_path", "client_cert", "client_key", "message"),
[
("http", "/etc/pki/ca.pem", None, None, "Logstash TLS certificate options can only be used with HTTPS."),
("https", None, None, "/etc/pki/client.key", "Logstash client_key requires client_cert."),
],
)
def test_http_protocol_rejects_invalid_tls_options(protocol, ca_path, client_cert, client_key, message):
options = {
"server": "logstash.example.com",
"port": 8080,
"protocol": protocol,
"http_path": "/",
"username": None,
"password": None,
"validate_certs": True,
"ca_path": ca_path,
"client_cert": client_cert,
"client_key": client_key,
"timeout": 10,
"retries": 3,
"type": "ansible",
"pre_command": None,
"format_version": "v1",
}
with pytest.raises(AnsibleError, match=message):
_configure_callback(options)
def test_http_protocol_rejects_non_positive_timeout():
options = {
"server": "logstash.example.com",
"port": 8080,
"protocol": "https",
"http_path": "/",
"username": None,
"password": None,
"validate_certs": True,
"ca_path": None,
"client_cert": None,
"client_key": None,
"timeout": 0,
"retries": 3,
"type": "ansible",
"pre_command": None,
"format_version": "v1",
}
with pytest.raises(AnsibleError, match="Logstash HTTP timeout must be greater than zero."):
_configure_callback(options)
def test_http_protocol_rejects_negative_retries():
options = {
"server": "logstash.example.com",
"port": 8080,
"protocol": "https",
"http_path": "/",
"username": None,
"password": None,
"validate_certs": True,
"ca_path": None,
"client_cert": None,
"client_key": None,
"timeout": 10,
"retries": -1,
"type": "ansible",
"pre_command": None,
"format_version": "v1",
}
with pytest.raises(AnsibleError, match="Logstash HTTP retries must be zero or greater."):
_configure_callback(options)
@@ -0,0 +1,293 @@
# 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
import unittest
from collections import OrderedDict
from unittest.mock import MagicMock, Mock, patch
import pytest
from ansible.executor.task_result import TaskResult
from ansible.playbook.task import Task
from ansible.release import __version__ as ansible_release
from ansible_collections.community.general.plugins.callback.opentelemetry import (
CallbackModule,
HostData,
OpenTelemetrySource,
TaskData,
)
if tuple(int(x) for x in ansible_release.split(".")[:2]) >= (2, 21):
# https://github.com/ansible/ansible/issues/86761
pytest.skip("Temporarily skipping callback tests for ansible-core >= 2.21", allow_module_level=True)
class TestOpentelemetry(unittest.TestCase):
@patch("ansible_collections.community.general.plugins.callback.opentelemetry.socket")
def setUp(self, mock_socket):
mock_socket.gethostname.return_value = "my-host"
mock_socket.gethostbyname.return_value = "1.2.3.4"
self.opentelemetry = OpenTelemetrySource(display=None)
self.task_fields = {"args": {}}
self.mock_host = Mock("MockHost")
self.mock_host.name = "myhost"
self.mock_host._uuid = "myhost_uuid"
self.mock_task = Task()
self.mock_task.action = "myaction"
self.mock_task.no_log = False
self.mock_task._role = "myrole"
self.mock_task._uuid = "myuuid"
self.mock_task.args = {}
self.mock_task.get_name = MagicMock(return_value="mytask")
self.mock_task.get_path = MagicMock(return_value="/mypath")
self.my_task = TaskData("myuuid", "mytask", "/mypath", "myplay", "myaction", "")
self.my_task_result = TaskResult(
host=self.mock_host, task=self.mock_task, return_data={}, task_fields=self.task_fields
)
self.mock_span = Mock("MockSpan")
self.mock_span.set_status = MagicMock()
self.mock_span.set_attributes = MagicMock()
self.mock_span.end = MagicMock()
def test_run_task_with_host(self):
tasks_data = OrderedDict()
self.opentelemetry.start_task(tasks_data, False, "myplay", self.mock_task, self.mock_host)
task_data = tasks_data["myuuid"]
self.assertEqual(task_data.uuid, "myuuid")
self.assertEqual(task_data.name, "mytask")
self.assertEqual(task_data.path, "/mypath")
self.assertEqual(task_data.play, "myplay")
self.assertEqual(task_data.action, "myaction")
self.assertEqual(task_data.args, {})
host_data = task_data.host_data["myhost_uuid"]
self.assertEqual(host_data.uuid, "myhost_uuid")
self.assertEqual(host_data.name, "myhost")
self.assertIsNotNone(host_data.start)
self.opentelemetry.finish_task(tasks_data, "ok", self.my_task_result, "")
self.assertEqual(host_data.status, "ok")
def test_finish_task_with_a_host_match(self):
tasks_data = OrderedDict()
tasks_data["myuuid"] = self.my_task
self.opentelemetry.finish_task(tasks_data, "ok", self.my_task_result, "")
task_data = tasks_data["myuuid"]
host_data = task_data.host_data["myhost_uuid"]
self.assertEqual(host_data.uuid, "myhost_uuid")
self.assertEqual(host_data.name, "myhost")
self.assertEqual(host_data.status, "ok")
def test_finish_task_without_a_host_match(self):
result = TaskResult(host=None, task=self.mock_task, return_data={}, task_fields=self.task_fields)
tasks_data = OrderedDict()
tasks_data["myuuid"] = self.my_task
self.opentelemetry.finish_task(tasks_data, "ok", result, "")
task_data = tasks_data["myuuid"]
host_data = task_data.host_data["include"]
self.assertEqual(host_data.uuid, "include")
self.assertEqual(host_data.name, "include")
self.assertEqual(host_data.status, "ok")
@patch("ansible_collections.community.general.plugins.callback.opentelemetry.OTEL_LIBRARY_IMPORT_ERROR", None)
def test_skipped_task_without_runner_start(self):
callback = CallbackModule()
callback.play_name = "myplay"
callback.v2_runner_on_skipped(self.my_task_result)
task_data = callback.tasks_data["myuuid"]
self.assertEqual(task_data.name, "mytask")
self.assertEqual(task_data.play, "myplay")
host_data = task_data.host_data["myhost_uuid"]
self.assertEqual(host_data.name, "myhost")
self.assertEqual(host_data.status, "skipped")
@patch("ansible_collections.community.general.plugins.callback.opentelemetry.Status", create=True)
@patch("ansible_collections.community.general.plugins.callback.opentelemetry.StatusCode", create=True)
def test_update_span_data(self, mock_status_code, mock_status):
unfinished_host = HostData("myhost_uuid", "myhost", "unreachable")
self.opentelemetry.update_span_data(self.mock_task, unfinished_host, self.mock_span, True, True)
self.mock_span.end.assert_called()
def test_get_error_message(self):
test_cases = (
("my-exception", "my-msg", None, "my-exception"),
(None, "my-msg", None, "my-msg"),
(None, None, None, "failed"),
)
for tc in test_cases:
result = self.opentelemetry.get_error_message(generate_test_data(tc[0], tc[1], tc[2]))
self.assertEqual(result, tc[3])
def test_get_error_message_from_results(self):
test_cases = (
("my-exception", "my-msg", None, False, None),
(None, "my-msg", None, False, None),
(None, None, None, False, None),
("my-exception", "my-msg", None, True, "shell(none) - my-exception"),
(None, "my-msg", None, True, "shell(none) - my-msg"),
(None, None, None, True, "shell(none) - failed"),
)
for tc in test_cases:
result = self.opentelemetry.get_error_message_from_results(
[generate_test_data(tc[0], tc[1], tc[2], tc[3])], "shell"
)
self.assertEqual(result, tc[4])
def test_enrich_error_message(self):
test_cases = (
(
"my-exception",
"my-msg",
"my-stderr",
'message: "my-msg"\nexception: "my-exception"\nstderr: "my-stderr"',
),
("my-exception", None, "my-stderr", 'message: "failed"\nexception: "my-exception"\nstderr: "my-stderr"'),
(None, "my-msg", "my-stderr", 'message: "my-msg"\nexception: "None"\nstderr: "my-stderr"'),
("my-exception", "my-msg", None, 'message: "my-msg"\nexception: "my-exception"\nstderr: "None"'),
(
"my-exception",
"my-msg",
"\nline1\nline2",
'message: "my-msg"\nexception: "my-exception"\nstderr: "\nline1\nline2"',
),
)
for tc in test_cases:
result = self.opentelemetry.enrich_error_message(generate_test_data(tc[0], tc[1], tc[2]))
self.assertEqual(result, tc[3])
def test_enrich_error_message_from_results(self):
test_cases = (
("my-exception", "my-msg", "my-stderr", False, ""),
("my-exception", None, "my-stderr", False, ""),
(None, "my-msg", "my-stderr", False, ""),
("my-exception", "my-msg", None, False, ""),
("my-exception", "my-msg", "\nline1\nline2", False, ""),
(
"my-exception",
"my-msg",
"my-stderr",
True,
'shell(none) - message: "my-msg"\nexception: "my-exception"\nstderr: "my-stderr"\n',
),
(
"my-exception",
None,
"my-stderr",
True,
'shell(none) - message: "failed"\nexception: "my-exception"\nstderr: "my-stderr"\n',
),
(
None,
"my-msg",
"my-stderr",
True,
'shell(none) - message: "my-msg"\nexception: "None"\nstderr: "my-stderr"\n',
),
(
"my-exception",
"my-msg",
None,
True,
'shell(none) - message: "my-msg"\nexception: "my-exception"\nstderr: "None"\n',
),
(
"my-exception",
"my-msg",
"\nline1\nline2",
True,
'shell(none) - message: "my-msg"\nexception: "my-exception"\nstderr: "\nline1\nline2"\n',
),
)
for tc in test_cases:
result = self.opentelemetry.enrich_error_message_from_results(
[generate_test_data(tc[0], tc[1], tc[2], tc[3])], "shell"
)
self.assertEqual(result, tc[4])
def test_url_from_args(self):
test_cases = (
({}, ""),
({"url": "my-url"}, "my-url"),
({"url": "my-url", "api_url": "my-api_url"}, "my-url"),
({"api_url": "my-api_url"}, "my-api_url"),
({"api_url": "my-api_url", "chart_repo_url": "my-chart_repo_url"}, "my-api_url"),
)
for tc in test_cases:
result = self.opentelemetry.url_from_args(tc[0])
self.assertEqual(result, tc[1])
def test_parse_and_redact_url_if_possible(self):
test_cases = (
({}, None),
({"url": "wrong"}, None),
({"url": "https://my-url"}, "https://my-url"),
({"url": "https://user:pass@my-url"}, "https://my-url"),
({"url": "https://my-url:{{ my_port }}"}, "https://my-url:{{ my_port }}"),
({"url": "https://{{ my_hostname }}:{{ my_port }}"}, None),
({"url": "{{my_schema}}{{ my_hostname }}:{{ my_port }}"}, None),
)
for tc in test_cases:
result = self.opentelemetry.parse_and_redact_url_if_possible(tc[0])
if tc[1]:
self.assertEqual(result.geturl(), tc[1])
else:
self.assertEqual(result, tc[1])
def test_span_event_carries_the_result_of_its_own_host(mocker):
mocker.patch("ansible_collections.community.general.plugins.callback.opentelemetry.Status", create=True)
mocker.patch("ansible_collections.community.general.plugins.callback.opentelemetry.StatusCode", create=True)
opentelemetry = OpenTelemetrySource(display=None)
task = Task()
task.action = "myaction"
task.no_log = False
task._uuid = "myuuid"
task.args = {}
task.get_name = MagicMock(return_value="mytask")
task.get_path = MagicMock(return_value="/mypath")
tasks_data = OrderedDict()
hosts = []
for name in ("a", "b", "c"):
host = Mock("MockHost")
host.name = name
host._uuid = f"{name}_uuid"
hosts.append(host)
opentelemetry.start_task(tasks_data, False, "myplay", task, host)
for host in hosts:
result = TaskResult(host=host, task=task, return_data={"msg": host.name}, task_fields={"args": {}})
opentelemetry.finish_task(tasks_data, "ok", result, f'{{"msg": "{host.name}"}}')
for host_data in tasks_data["myuuid"].host_data.values():
span = MagicMock()
opentelemetry.update_span_data(tasks_data["myuuid"], host_data, span, False, True)
span.add_event.assert_called_once_with(f'{{"msg": "{host_data.name}"}}', attributes={})
def generate_test_data(exception=None, msg=None, stderr=None, failed=False):
res_data = OrderedDict()
if exception:
res_data["exception"] = exception
if msg:
res_data["msg"] = msg
if stderr:
res_data["stderr"] = stderr
res_data["failed"] = failed
return res_data
@@ -0,0 +1,102 @@
# 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
import json
import unittest
from datetime import datetime
from unittest.mock import Mock, patch
import pytest
from ansible.executor.task_result import TaskResult
from ansible.release import __version__ as ansible_release
from ansible_collections.community.general.plugins.callback.splunk import SplunkHTTPCollectorSource
if tuple(int(x) for x in ansible_release.split(".")[:2]) >= (2, 21):
# https://github.com/ansible/ansible/issues/86761
pytest.skip("Temporarily skipping callback tests for ansible-core >= 2.21", allow_module_level=True)
class TestSplunkClient(unittest.TestCase):
@patch("ansible_collections.community.general.plugins.callback.splunk.socket")
def setUp(self, mock_socket):
mock_socket.gethostname.return_value = "my-host"
mock_socket.gethostbyname.return_value = "1.2.3.4"
self.splunk = SplunkHTTPCollectorSource()
self.mock_task = Mock("MockTask")
self.mock_task._role = "myrole"
self.mock_task._uuid = "myuuid"
self.task_fields = {"args": {}}
self.mock_host = Mock("MockHost")
self.mock_host.name = "myhost"
@patch("ansible_collections.community.general.plugins.callback.splunk.now")
@patch("ansible_collections.community.general.plugins.callback.splunk.open_url")
def test_timestamp_with_milliseconds(self, open_url_mock, mock_now):
mock_now.return_value = datetime(2020, 12, 1)
result = TaskResult(host=self.mock_host, task=self.mock_task, return_data={}, task_fields=self.task_fields)
self.splunk.send_event(
url="endpoint",
authtoken="token",
validate_certs=False,
include_milliseconds=True,
batch="abcefghi-1234-5678-9012-abcdefghijkl",
state="OK",
result=result,
runtime=100,
)
args, kwargs = open_url_mock.call_args
sent_data = json.loads(args[1])
self.assertEqual(sent_data["event"]["timestamp"], "2020-12-01 00:00:00.000000 +0000")
self.assertEqual(sent_data["event"]["host"], "my-host")
self.assertEqual(sent_data["event"]["ip_address"], "1.2.3.4")
@patch("ansible_collections.community.general.plugins.callback.splunk.now")
@patch("ansible_collections.community.general.plugins.callback.splunk.open_url")
def test_timestamp_without_milliseconds(self, open_url_mock, mock_now):
mock_now.return_value = datetime(2020, 12, 1)
result = TaskResult(host=self.mock_host, task=self.mock_task, return_data={}, task_fields=self.task_fields)
self.splunk.send_event(
url="endpoint",
authtoken="token",
validate_certs=False,
include_milliseconds=False,
batch="abcefghi-1234-5678-9012-abcdefghijkl",
state="OK",
result=result,
runtime=100,
)
args, kwargs = open_url_mock.call_args
sent_data = json.loads(args[1])
self.assertEqual(sent_data["event"]["timestamp"], "2020-12-01 00:00:00 +0000")
self.assertEqual(sent_data["event"]["host"], "my-host")
self.assertEqual(sent_data["event"]["ip_address"], "1.2.3.4")
@patch("ansible_collections.community.general.plugins.callback.splunk.open_url")
def test_check_mode_is_reported_per_event(self, open_url_mock):
sent = []
for check_mode in (False, True, False, None):
args = {} if check_mode is None else {"_ansible_check_mode": check_mode}
result = TaskResult(host=self.mock_host, task=self.mock_task, return_data={}, task_fields={"args": args})
self.splunk.send_event(
url="endpoint",
authtoken="token",
validate_certs=False,
include_milliseconds=False,
batch=None,
state="OK",
result=result,
runtime=100,
)
sent.append(json.loads(open_url_mock.call_args[0][1])["event"]["ansible_check_mode"])
self.assertEqual(sent, [False, True, False, False])
@@ -0,0 +1,392 @@
# Copyright (c) 2026, Alexei Znamensky <russoz@gmail.com>
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
# SPDX-License-Identifier: GPL-3.0-or-later
from __future__ import annotations
import typing as t
from io import StringIO
import pytest
from ansible.errors import AnsibleError
from ansible.playbook.play_context import PlayContext
from ansible.plugins.loader import connection_loader
BUILD_CMD_TEST_CASES: list[dict[str, t.Any]] = [
dict(
id="sh simple",
input=dict(
cmd="""echo 123""",
shell="sh",
),
output=["/bin/sh", "-c", "echo 123"],
),
dict(
id="powershell simple",
input=dict(
cmd="""powershell -c My-Command1 -Param 'param' """,
shell="powershell",
),
output=["powershell", "-c", "My-Command1 -Param 'param'"],
),
dict(
id=r"D:\my path\powershell.exe simple",
input=dict(
cmd=r"""D:\my path\powershell.exe -c My-Command1 -Param 'param' """,
shell="powershell",
),
output=[r"D:\my path\powershell.exe", "-c", "My-Command1 -Param 'param'"],
),
dict(
id=r"\\127.0.0.1\share\powershell simple",
input=dict(
cmd=r"""\\127.0.0.1\share\powershell -c My-Command1 -Param 'param' """,
shell="powershell",
),
output=[r"\\127.0.0.1\share\powershell", "-c", "My-Command1 -Param 'param'"],
),
dict(
id=r"C:\powershell simple",
input=dict(
cmd=r"""C:\powershell -c My-Command1 -Param 'param' """,
shell="powershell",
),
output=[r"C:\powershell", "-c", "My-Command1 -Param 'param'"],
),
dict(
id=r'"C:\powershell" simple',
input=dict(
cmd=r""""C:\powershell" -c My-Command1 -Param 'param' """,
shell="cmd", # the plugins does not care the shell type, as long as it is windows
),
output=[r"C:\powershell", "-c", "My-Command1 -Param 'param'"],
),
dict(
id="powershell multiline",
input=dict(
cmd=(
"powershell -ExecutionPolicy bypass -Command\n"
"My-Command1 \\\n"
" -Param 'param';\n"
"My-Command2 \\\n"
" -Param 'param'"
),
shell="powershell",
),
output=[
"powershell",
"-ExecutionPolicy",
"bypass",
"-Command",
"My-Command1 \\\n -Param 'param';\nMy-Command2 \\\n -Param 'param'",
],
),
dict(
id="cmd simple",
input=dict(
cmd="""CMD.EXE /C some-command /flag1 /flag2""",
shell="powershell",
),
output=["CMD.EXE", "/C", "some-command /flag1 /flag2"],
),
dict(
id=r"C:\cmd simple",
input=dict(
cmd=r"""C:\CMD.EXE /C some-command /flag1 /flag2""",
shell="powershell",
),
output=[r"C:\CMD.EXE", "/C", "some-command /flag1 /flag2"],
),
dict(
id=r'"C:\cmd" simple',
input=dict(
cmd=r""""C:\CMD" /c some-command /flag1 /flag2""",
shell="powershell",
),
output=[r"C:\CMD", "/c", "some-command /flag1 /flag2"],
),
dict(
id="powershell encoded command strips quotes",
input=dict(
cmd="""powershell -NoProfile -NonInteractive -ExecutionPolicy Unrestricted -EncodedCommand 'cABhAHIAYQBtAA=='""",
shell="powershell",
),
output=[
"powershell",
"-NoProfile",
"-NonInteractive",
"-ExecutionPolicy",
"Unrestricted",
"-EncodedCommand",
"cABhAHIAYQBtAA==",
],
),
dict(
id="powershell encoded command strips double quotes",
input=dict(
cmd='''powershell -NoProfile -EncodedCommand "cABhAHIAYQBtAA=="''',
shell="powershell",
),
output=[
"powershell",
"-NoProfile",
"-EncodedCommand",
"cABhAHIAYQBtAA==",
],
),
dict(
id="powershell encoded command case-insensitive keyword",
input=dict(
cmd="""powershell -NoProfile -eNcOdEdCoMmAnD 'cABhAHIAYQBtAA=='""",
shell="powershell",
),
output=[
"powershell",
"-NoProfile",
"-eNcOdEdCoMmAnD",
"cABhAHIAYQBtAA==",
],
),
dict(
id="powershell encoded command keeps surrounding flags",
input=dict(
cmd="""powershell -NoProfile -EncodedCommand 'cABhAHIAYQBtAA==' -InputFormat None""",
shell="powershell",
),
output=[
"powershell",
"-NoProfile",
"-EncodedCommand",
"cABhAHIAYQBtAA==",
"-InputFormat",
"None",
],
),
dict(
id="powershell -enc alias strips quotes",
input=dict(
cmd="""powershell -NoProfile -enc 'cABhAHIAYQBtAA=='""",
shell="powershell",
),
output=[
"powershell",
"-NoProfile",
"-enc",
"cABhAHIAYQBtAA==",
],
),
dict(
id="powershell -Command with spaces in path",
input=dict(
cmd="""powershell.exe -NonInteractive -Command 'Write-Host "hello"; & \\'C:\\My Scripts\\run me.ps1\\''""",
shell="powershell",
),
output=[
"powershell.exe",
"-NonInteractive",
"-Command",
"""Write-Host "hello"; & \\'C:\\My Scripts\\run me.ps1\\'""",
],
),
dict(
id="powershell -File with spaces in path",
input=dict(
cmd='''powershell.exe -NonInteractive -File "C:\\My Scripts\\run me.ps1"''',
shell="powershell",
),
output=[
"powershell.exe",
"-NonInteractive",
"-File",
r"C:\My Scripts\run me.ps1",
],
),
dict(
id="powershell -File single quoted path with trailing args",
input=dict(
cmd="""powershell.exe -NoProfile -File 'C:\\My Scripts\\run me.ps1' -Arg1 value""",
shell="powershell",
),
output=[
"powershell.exe",
"-NoProfile",
"-File",
r"C:\My Scripts\run me.ps1",
"-Arg1",
"value",
],
),
dict(
id="powershell -F alias with spaces in path",
input=dict(
cmd='''powershell.exe -NoProfile -F "C:\\My Scripts\\run me.ps1"''',
shell="powershell",
),
output=[
"powershell.exe",
"-NoProfile",
"-F",
r"C:\My Scripts\run me.ps1",
],
),
dict(
id="powershell -Command outer double quotes",
input=dict(
cmd='''powershell.exe -NoProfile -Command "Write-Host 'hello world'"''',
shell="powershell",
),
output=[
"powershell.exe",
"-NoProfile",
"-Command",
"Write-Host 'hello world'",
],
),
dict(
id="powershell -Command empty quoted payload",
input=dict(
cmd='''powershell.exe -NoProfile -Command ""''',
shell="powershell",
),
output=[
"powershell.exe",
"-NoProfile",
"-Command",
"",
],
),
]
BUILD_CMD_TEST_CASE_IDS: list[str] = [tc["id"] for tc in BUILD_CMD_TEST_CASES]
@pytest.mark.parametrize("testcase", BUILD_CMD_TEST_CASES, ids=BUILD_CMD_TEST_CASE_IDS)
def test_build_command(mocker, testcase):
mocker.patch("ansible.module_utils.common.process.get_bin_path").return_value = "/test/bin/incus"
play_context = PlayContext()
play_context.shell = testcase["input"].get("shell", "sh")
in_stream = StringIO()
conn = connection_loader.get("community.general.incus", play_context, in_stream)
conn.set_option("remote_addr", "server1")
conn.set_option("remote_user", "root")
cli_preamble = [
"/test/bin/incus",
"--project",
"default",
"exec",
*(["-T"] if play_context.shell in ["cmd", "powershell"] else []),
"local:server1",
"--",
]
built = conn._build_command(testcase["input"]["cmd"])
tc_cmd = cli_preamble + testcase["output"]
assert built == tc_cmd, f"\n built = {built}\ntestcase = {tc_cmd}"
def _make_conn(mocker):
mocker.patch("ansible.module_utils.common.process.get_bin_path").return_value = "/test/bin/incus"
play_context = PlayContext()
play_context.shell = "sh"
conn = connection_loader.get("community.general.incus", play_context, StringIO())
conn.set_option("remote_addr", "server1")
conn.set_option("remote_user", "root")
return conn
def test_put_file_transfer_failure(mocker, tmp_path):
"""A failed ``incus file push`` must raise instead of silently succeeding."""
conn = _make_conn(mocker)
src = tmp_path / "payload"
src.write_text("data")
process = mocker.MagicMock()
process.communicate.return_value = (b"", b"Error: not authorized\n")
process.returncode = 1
mocker.patch("ansible_collections.community.general.plugins.connection.incus.Popen", return_value=process)
with pytest.raises(AnsibleError) as exc:
conn.put_file(str(src), "/tmp/dest")
assert "failed to transfer file to instance server1" in str(exc.value)
assert "Error: not authorized" in str(exc.value)
def test_put_file_transfer_success(mocker, tmp_path):
"""A successful ``incus file push`` must not raise."""
conn = _make_conn(mocker)
src = tmp_path / "payload"
src.write_text("data")
process = mocker.MagicMock()
process.communicate.return_value = (b"", b"")
process.returncode = 0
mocker.patch("ansible_collections.community.general.plugins.connection.incus.Popen", return_value=process)
conn.put_file(str(src), "/tmp/dest")
def test_fetch_file_transfer_failure(mocker):
"""A failed ``incus file pull`` must raise instead of silently succeeding."""
conn = _make_conn(mocker)
process = mocker.MagicMock()
process.communicate.return_value = (b"", b"Error: Instance is not running.\n")
process.returncode = 1
mocker.patch("ansible_collections.community.general.plugins.connection.incus.Popen", return_value=process)
with pytest.raises(AnsibleError) as exc:
conn.fetch_file("/tmp/src", "/tmp/dest")
assert "failed to transfer file from instance server1" in str(exc.value)
assert "Error: Instance is not running." in str(exc.value)
def test_fetch_file_transfer_success(mocker):
"""A successful ``incus file pull`` must not raise."""
conn = _make_conn(mocker)
process = mocker.MagicMock()
process.communicate.return_value = (b"", b"")
process.returncode = 0
mocker.patch("ansible_collections.community.general.plugins.connection.incus.Popen", return_value=process)
conn.fetch_file("/tmp/src", "/tmp/dest")
def test_get_remote_uid_gid_default_command(mocker):
"""By default ``/bin/id`` is used to resolve the remote UID and GID."""
conn = _make_conn(mocker)
exec_command = mocker.patch.object(conn, "exec_command", side_effect=[(0, "1001\n", ""), (0, "2002\n", "")])
assert conn._get_remote_uid_gid() == (1001, 2002)
assert [call.args[0] for call in exec_command.call_args_list] == ["/bin/id -u", "/bin/id -g"]
def test_get_remote_uid_gid_custom_command(mocker):
"""``remote_user_id_command`` overrides the command used to resolve the remote UID and GID."""
conn = _make_conn(mocker)
conn.set_option("remote_user_id_command", "/usr/bin/id")
exec_command = mocker.patch.object(conn, "exec_command", side_effect=[(0, "1001\n", ""), (0, "2002\n", "")])
assert conn._get_remote_uid_gid() == (1001, 2002)
assert [call.args[0] for call in exec_command.call_args_list] == ["/usr/bin/id -u", "/usr/bin/id -g"]
def test_get_remote_uid_gid_failure(mocker):
"""A failing ``id`` command must raise instead of returning bogus IDs."""
conn = _make_conn(mocker)
mocker.patch.object(conn, "exec_command", return_value=(1, "", "id: command not found"))
with pytest.raises(AnsibleError) as exc:
conn._get_remote_uid_gid()
assert "Failed to get remote uid for user root" in str(exc.value)
@@ -0,0 +1,132 @@
# Copyright (c) 2020 Red Hat 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
from __future__ import annotations
from io import StringIO
from unittest import mock
import pytest
from ansible.errors import AnsibleError
from ansible.playbook.play_context import PlayContext
from ansible.plugins.loader import connection_loader
from ansible_collections.community.general.plugins.connection import lxc as lxc_plugin_module
@pytest.fixture(autouse=True)
def lxc(request, mocker):
"""Fixture to return the lxc plugin module.
The fixture parameter is used to determine the presence of liblxc.
When true (default), a mocked liblxc module is patched into the plugin.
If False, no liblxc will be present.
"""
liblxc_present = getattr(request, "param", True)
class ContainerMock:
# dict of container name to its state
_container_states = {}
def __init__(self, name):
super().__init__()
self.name = name
@property
def state(self):
return ContainerMock._container_states.get(self.name, "STARTED")
liblxc_module_mock = mock.MagicMock()
liblxc_module_mock.Container = ContainerMock
mocker.patch.object(lxc_plugin_module, "HAS_LIBLXC", liblxc_present)
mocker.patch.object(lxc_plugin_module, "_lxc", liblxc_module_mock if liblxc_present else None, create=True)
return lxc_plugin_module
class TestLXCConnectionClass:
@pytest.mark.parametrize("lxc", [True, False], indirect=True)
def test_lxc_connection_module(self, lxc):
"""Test that a connection can be created with the plugin."""
play_context = PlayContext()
in_stream = StringIO()
conn = connection_loader.get("lxc", play_context, in_stream)
assert conn
assert isinstance(conn, lxc.Connection)
@pytest.mark.parametrize("lxc", [False], indirect=True)
def test_lxc_connection_liblxc_error(self, lxc):
"""Test that on connect an error is thrown if liblxc is not present."""
play_context = PlayContext()
in_stream = StringIO()
conn = connection_loader.get("lxc", play_context, in_stream)
with pytest.raises(AnsibleError, match="lxc python bindings are not installed"):
conn._connect()
def test_remote_addr_option(self):
"""Test that the remote_addr option is used"""
play_context = PlayContext()
in_stream = StringIO()
conn = connection_loader.get("lxc", play_context, in_stream)
container_name = "my-container"
conn.set_option("remote_addr", container_name)
assert conn.get_option("remote_addr") == container_name
conn._connect()
assert conn.container_name == container_name
def test_error_when_stopped(self, lxc):
"""Test that on connect an error is thrown if the container is stopped."""
play_context = PlayContext()
in_stream = StringIO()
conn = connection_loader.get("lxc", play_context, in_stream)
conn.set_option("remote_addr", "my-container")
lxc._lxc.Container._container_states["my-container"] = "STOPPED"
with pytest.raises(AnsibleError, match="my-container is not running"):
conn._connect()
def test_container_name_change(self):
"""Test connect method reconnects when remote_addr changes"""
play_context = PlayContext()
in_stream = StringIO()
conn = connection_loader.get("lxc", play_context, in_stream)
# setting the option does nothing
container1_name = "my-container"
conn.set_option("remote_addr", container1_name)
assert conn.container_name is None
assert conn.container is None
# first call initializes the connection
conn._connect()
assert conn.container_name == container1_name
assert conn.container is not None
assert conn.container.name == container1_name
container1 = conn.container
# second call is basically a no-op
conn._connect()
assert conn.container_name == container1_name
assert conn.container is container1
assert conn.container.name == container1_name
# setting the option does again nothing
container2_name = "my-other-container"
conn.set_option("remote_addr", container2_name)
assert conn.container_name == container1_name
assert conn.container is container1
assert conn.container.name == container1_name
# first call with a different remote_addr changes the connection
conn._connect()
assert conn.container_name == container2_name
assert conn.container is not None
assert conn.container is not container1
assert conn.container.name == container2_name
@@ -0,0 +1,602 @@
# Derived from test_proxmox_pct_remote.py (c) 2024 Nils Stein (@mietzen) <github.nstein@mailbox.org>
# 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
import os
from io import StringIO
from pathlib import Path
from unittest.mock import MagicMock, mock_open, patch
import pytest
from ansible.errors import AnsibleAuthenticationFailure, AnsibleConnectionFailure, AnsibleError
from ansible.module_utils.common.text.converters import to_bytes
from ansible.playbook.play_context import PlayContext
from ansible.plugins.loader import connection_loader
from ansible_collections.community.general.plugins.connection.wsl import MyAddPolicy, authenticity_msg
from ansible_collections.community.general.plugins.module_utils._filelock import FileLock, LockTimeout
paramiko = pytest.importorskip("paramiko")
@pytest.fixture
def connection():
play_context = PlayContext()
in_stream = StringIO()
conn = connection_loader.get("community.general.wsl", play_context, in_stream)
conn.set_option("remote_addr", "192.168.1.100")
conn.set_option("remote_user", "root")
conn.set_option("password", "password")
conn.set_option("wsl_distribution", "test")
return conn
def test_connection_options(connection):
"""Test that connection options are properly set"""
assert connection.get_option("remote_addr") == "192.168.1.100"
assert connection.get_option("remote_user") == "root"
assert connection.get_option("password") == "password"
assert connection.get_option("wsl_distribution") == "test"
def test_authenticity_msg():
"""Test authenticity message formatting"""
msg = authenticity_msg("test.host", "ssh-rsa", "AA:BB:CC:DD")
assert "test.host" in msg
assert "ssh-rsa" in msg
assert "AA:BB:CC:DD" in msg
def test_missing_host_key(connection):
"""Test MyAddPolicy missing_host_key method"""
client = MagicMock()
key = MagicMock()
key.get_fingerprint.return_value = b"fingerprint"
key.get_name.return_value = "ssh-rsa"
policy = MyAddPolicy(connection)
connection.set_option("host_key_auto_add", True)
policy.missing_host_key(client, "test.host", key)
assert hasattr(key, "_added_by_ansible_this_time")
connection.set_option("host_key_auto_add", False)
connection.set_option("host_key_checking", False)
policy.missing_host_key(client, "test.host", key)
connection.set_option("host_key_checking", True)
connection.set_option("host_key_auto_add", False)
connection.set_option("use_persistent_connections", False)
with patch("ansible.utils.display.Display.prompt_until", return_value="yes"):
policy.missing_host_key(client, "test.host", key)
with patch("ansible.utils.display.Display.prompt_until", return_value="no"):
with pytest.raises(AnsibleError, match="host connection rejected by user"):
policy.missing_host_key(client, "test.host", key)
def test_set_log_channel(connection):
"""Test setting log channel"""
connection._set_log_channel("test_channel")
assert connection._log_channel == "test_channel"
def test_parse_proxy_command(connection):
"""Test proxy command parsing"""
connection.set_option("proxy_command", "ssh -W %h:%p proxy.example.com")
connection.set_option("remote_addr", "target.example.com")
connection.set_option("remote_user", "testuser")
result = connection._parse_proxy_command(port=2222)
assert "sock" in result
assert isinstance(result["sock"], paramiko.ProxyCommand)
@patch("paramiko.SSHClient")
def test_connect_with_rsa_sha2_disabled(mock_ssh, connection):
"""Test connection with RSA SHA2 algorithms disabled"""
connection.set_option("use_rsa_sha2_algorithms", False)
mock_client = MagicMock()
mock_ssh.return_value = mock_client
connection._connect()
call_kwargs = mock_client.connect.call_args[1]
assert "disabled_algorithms" in call_kwargs
assert "pubkeys" in call_kwargs["disabled_algorithms"]
@patch("paramiko.SSHClient")
def test_connect_with_bad_host_key(mock_ssh, connection):
"""Test connection with bad host key"""
mock_client = MagicMock()
mock_ssh.return_value = mock_client
mock_client.connect.side_effect = paramiko.ssh_exception.BadHostKeyException("hostname", MagicMock(), MagicMock())
with pytest.raises(AnsibleConnectionFailure, match="host key mismatch"):
connection._connect()
@patch("paramiko.SSHClient")
def test_connect_with_invalid_host_key(mock_ssh, connection):
"""Test connection with bad host key"""
connection.set_option("host_key_checking", True)
mock_client = MagicMock()
mock_ssh.return_value = mock_client
mock_client.load_system_host_keys.side_effect = paramiko.hostkeys.InvalidHostKey(
"Bad Line!", Exception("Something crashed!")
)
with pytest.raises(AnsibleConnectionFailure, match="Invalid host key: Bad Line!"):
connection._connect()
@patch("paramiko.SSHClient")
def test_connect_success(mock_ssh, connection):
"""Test successful SSH connection establishment"""
mock_client = MagicMock()
mock_ssh.return_value = mock_client
connection._connect()
assert mock_client.connect.called
assert connection._connected
@patch("paramiko.SSHClient")
def test_connect_authentication_failure(mock_ssh, connection):
"""Test SSH connection with authentication failure"""
mock_client = MagicMock()
mock_ssh.return_value = mock_client
mock_client.connect.side_effect = paramiko.ssh_exception.AuthenticationException("Auth failed")
with pytest.raises(AnsibleAuthenticationFailure):
connection._connect()
def test_any_keys_added(connection):
"""Test checking for added host keys"""
connection.ssh = MagicMock()
connection.ssh._host_keys = {
"host1": {
"ssh-rsa": MagicMock(_added_by_ansible_this_time=True),
"ssh-ed25519": MagicMock(_added_by_ansible_this_time=False),
}
}
assert connection._any_keys_added() is True
connection.ssh._host_keys = {"host1": {"ssh-rsa": MagicMock(_added_by_ansible_this_time=False)}}
assert connection._any_keys_added() is False
@patch("os.path.exists")
@patch("os.stat")
@patch("tempfile.NamedTemporaryFile")
def test_save_ssh_host_keys(mock_tempfile, mock_stat, mock_exists, connection):
"""Test saving SSH host keys"""
mock_exists.return_value = True
mock_stat.return_value = MagicMock(st_mode=0o644, st_uid=1000, st_gid=1000)
mock_tempfile.return_value.__enter__.return_value.name = "/tmp/test_keys"
connection.ssh = MagicMock()
connection.ssh._host_keys = {
"host1": {"ssh-rsa": MagicMock(get_base64=lambda: "KEY1", _added_by_ansible_this_time=True)}
}
mock_open_obj = mock_open()
with patch("builtins.open", mock_open_obj):
connection._save_ssh_host_keys("/tmp/test_keys")
mock_open_obj().write.assert_called_with("host1 ssh-rsa KEY1\n")
def test_build_wsl_command(connection):
"""Test wsl command building with different users"""
cmd = connection._build_wsl_command('/bin/sh -c "ls -la"')
assert cmd == 'wsl.exe --distribution test -- /bin/sh -c "ls -la"'
connection.set_option("wsl_user", "test-user")
cmd = connection._build_wsl_command('/bin/sh -c "ls -la"')
assert cmd == 'wsl.exe --distribution test --user test-user -- /bin/sh -c "ls -la"'
connection.set_option("become", True)
connection.set_option("become_user", "test-become-user")
cmd = connection._build_wsl_command('/bin/sh -c "ls -la"')
assert cmd == 'wsl.exe --distribution test --user test-become-user -- /bin/sh -c "ls -la"'
def test_build_wsl_command_powershell(connection):
"""Test wsl command building for powershell and cmd remote ssh shell"""
cmd = connection._build_wsl_command('/bin/sh -c "ls -la %PATH%"')
assert cmd == 'wsl.exe --distribution test -- /bin/sh -c "ls -la ^%PATH^%"'
connection.set_option("wsl_remote_ssh_shell_type", "powershell")
cmd = connection._build_wsl_command('/bin/sh -c "ls -la"')
assert cmd == 'wsl.exe --% --distribution test -- /bin/sh -c "ls -la"'
with pytest.raises(AnsibleError, match="The command contains '%', cannot safely escape it for Powershell"):
connection._build_wsl_command('/bin/sh -c "ls -la %PATH%"')
@patch("paramiko.SSHClient")
def test_exec_command_success(mock_ssh, connection):
"""Test successful command execution"""
mock_client = MagicMock()
mock_ssh.return_value = mock_client
mock_channel = MagicMock()
mock_transport = MagicMock()
mock_client.get_transport.return_value = mock_transport
mock_transport.open_session.return_value = mock_channel
mock_channel.recv_exit_status.return_value = 0
mock_channel.makefile.return_value = [to_bytes("stdout")]
mock_channel.makefile_stderr.return_value = [to_bytes("")]
connection._connected = True
connection.ssh = mock_client
returncode, stdout, stderr = connection.exec_command("ls -la")
mock_transport.open_session.assert_called_once()
mock_transport.set_keepalive.assert_called_once_with(5)
@patch("paramiko.SSHClient")
def test_exec_command_wsl_not_found(mock_ssh, connection):
"""Test command execution when wsl.exe is not found"""
mock_client = MagicMock()
mock_ssh.return_value = mock_client
mock_channel = MagicMock()
mock_transport = MagicMock()
mock_client.get_transport.return_value = mock_transport
mock_transport.open_session.return_value = mock_channel
mock_channel.recv_exit_status.return_value = 1
mock_channel.makefile.return_value = [to_bytes("")]
mock_channel.makefile_stderr.return_value = [to_bytes("'wsl.exe' is not recognized")]
connection._connected = True
connection.ssh = mock_client
with pytest.raises(AnsibleError, match="wsl.exe not found in path of host"):
connection.exec_command("ls -la")
@patch("paramiko.SSHClient")
def test_exec_command_session_open_failure(mock_ssh, connection):
"""Test exec_command when session opening fails"""
mock_client = MagicMock()
mock_transport = MagicMock()
mock_transport.open_session.side_effect = Exception("Failed to open session")
mock_client.get_transport.return_value = mock_transport
connection._connected = True
connection.ssh = mock_client
with pytest.raises(AnsibleConnectionFailure, match="Failed to open session"):
connection.exec_command("test command")
@patch("paramiko.SSHClient")
def test_exec_command_with_privilege_escalation(mock_ssh, connection):
"""Test exec_command with privilege escalation"""
mock_client = MagicMock()
mock_channel = MagicMock()
mock_transport = MagicMock()
mock_client.get_transport.return_value = mock_transport
mock_transport.open_session.return_value = mock_channel
connection._connected = True
connection.ssh = mock_client
connection.become = MagicMock()
connection.become.expect_prompt.return_value = True
connection.become.check_success.return_value = False
connection.become.check_password_prompt.return_value = True
connection.become.get_option.return_value = "sudo_password"
mock_channel.recv.return_value = b"[sudo] password:"
mock_channel.recv_exit_status.return_value = 0
mock_channel.makefile.return_value = [b""]
mock_channel.makefile_stderr.return_value = [b""]
returncode, stdout, stderr = connection.exec_command("sudo test command")
mock_channel.sendall.assert_called_once_with(b"sudo_password\n")
def test_put_file(connection):
"""Test putting a file to the remote system"""
connection.exec_command = MagicMock()
connection.exec_command.return_value = (0, b"", b"")
with patch("builtins.open", create=True) as mock_open:
mock_open.return_value.__enter__.return_value.read.return_value = b"test content"
connection.put_file("/local/path", "/remote/path")
connection.exec_command.assert_called_once_with(
"/bin/sh -c 'cat > /remote/path'", in_data=b"test content", sudoable=False
)
@patch("paramiko.SSHClient")
def test_put_file_general_error(mock_ssh, connection):
"""Test put_file with general error"""
mock_client = MagicMock()
mock_ssh.return_value = mock_client
mock_channel = MagicMock()
mock_transport = MagicMock()
mock_client.get_transport.return_value = mock_transport
mock_transport.open_session.return_value = mock_channel
mock_channel.recv_exit_status.return_value = 1
mock_channel.makefile.return_value = [to_bytes("")]
mock_channel.makefile_stderr.return_value = [to_bytes("Some error")]
connection._connected = True
connection.ssh = mock_client
with pytest.raises(AnsibleError, match="error occurred while putting file from /remote/path to /local/path"):
connection.put_file("/remote/path", "/local/path")
@patch("paramiko.SSHClient")
def test_put_file_cat_not_found(mock_ssh, connection):
"""Test command execution when cat is not found"""
mock_client = MagicMock()
mock_ssh.return_value = mock_client
mock_channel = MagicMock()
mock_transport = MagicMock()
mock_client.get_transport.return_value = mock_transport
mock_transport.open_session.return_value = mock_channel
mock_channel.recv_exit_status.return_value = 1
mock_channel.makefile.return_value = [to_bytes("")]
mock_channel.makefile_stderr.return_value = [to_bytes("cat: not found")]
connection._connected = True
connection.ssh = mock_client
with pytest.raises(AnsibleError, match="cat not found in path of WSL distribution"):
connection.fetch_file("/remote/path", "/local/path")
def test_fetch_file(connection):
"""Test fetching a file from the remote system"""
connection.exec_command = MagicMock()
connection.exec_command.return_value = (0, b"test content", b"")
with patch("builtins.open", create=True) as mock_open:
connection.fetch_file("/remote/path", "/local/path")
connection.exec_command.assert_called_once_with("/bin/sh -c 'cat /remote/path'", sudoable=False)
mock_open.assert_called_with("/local/path", "wb")
@patch("paramiko.SSHClient")
def test_fetch_file_general_error(mock_ssh, connection):
"""Test fetch_file with general error"""
mock_client = MagicMock()
mock_ssh.return_value = mock_client
mock_channel = MagicMock()
mock_transport = MagicMock()
mock_client.get_transport.return_value = mock_transport
mock_transport.open_session.return_value = mock_channel
mock_channel.recv_exit_status.return_value = 1
mock_channel.makefile.return_value = [to_bytes("")]
mock_channel.makefile_stderr.return_value = [to_bytes("Some error")]
connection._connected = True
connection.ssh = mock_client
with pytest.raises(AnsibleError, match="error occurred while fetching file from /remote/path to /local/path"):
connection.fetch_file("/remote/path", "/local/path")
@patch("paramiko.SSHClient")
def test_fetch_file_cat_not_found(mock_ssh, connection):
"""Test command execution when cat is not found"""
mock_client = MagicMock()
mock_ssh.return_value = mock_client
mock_channel = MagicMock()
mock_transport = MagicMock()
mock_client.get_transport.return_value = mock_transport
mock_transport.open_session.return_value = mock_channel
mock_channel.recv_exit_status.return_value = 1
mock_channel.makefile.return_value = [to_bytes("")]
mock_channel.makefile_stderr.return_value = [to_bytes("cat: not found")]
connection._connected = True
connection.ssh = mock_client
with pytest.raises(AnsibleError, match="cat not found in path of WSL distribution"):
connection.fetch_file("/remote/path", "/local/path")
def test_close(connection):
"""Test connection close"""
mock_ssh = MagicMock()
connection.ssh = mock_ssh
connection._connected = True
connection.close()
assert mock_ssh.close.called, "ssh.close was not called"
assert not connection._connected, "self._connected is still True"
def test_close_with_lock_file(connection):
"""Test close method with lock file creation"""
connection._any_keys_added = MagicMock(return_value=True)
connection._connected = True
connection.keyfile = "/tmp/wsl-known_hosts-test"
connection.set_option("host_key_checking", True)
connection.set_option("lock_file_timeout", 5)
connection.set_option("record_host_keys", True)
connection.ssh = MagicMock()
lock_file_path = os.path.join(
os.path.dirname(connection.keyfile), f"ansible-{os.path.basename(connection.keyfile)}.lock"
)
try:
connection.close()
assert os.path.exists(lock_file_path), "Lock file was not created"
lock_stat = os.stat(lock_file_path)
assert lock_stat.st_mode & 0o777 == 0o600, "Incorrect lock file permissions"
finally:
Path(lock_file_path).unlink(missing_ok=True)
@patch("pathlib.Path.unlink")
@patch("os.path.exists")
def test_close_lock_file_time_out_error_handling(mock_exists, mock_unlink, connection):
"""Test close method with lock file timeout error"""
connection._any_keys_added = MagicMock(return_value=True)
connection._connected = True
connection._save_ssh_host_keys = MagicMock()
connection.keyfile = "/tmp/wsl-known_hosts-test"
connection.set_option("host_key_checking", True)
connection.set_option("lock_file_timeout", 5)
connection.set_option("record_host_keys", True)
connection.ssh = MagicMock()
mock_exists.return_value = False
matcher = f"writing lock file for {connection.keyfile} ran in to the timeout of {connection.get_option('lock_file_timeout')}s"
with pytest.raises(AnsibleError, match=matcher):
with (
patch("os.getuid", return_value=1000),
patch("os.getgid", return_value=1000),
patch("os.chmod"),
patch("os.chown"),
patch("os.rename"),
patch.object(FileLock, "lock_file", side_effect=LockTimeout()),
):
connection.close()
@patch("ansible_collections.community.general.plugins.module_utils._filelock.FileLock.lock_file")
@patch("tempfile.NamedTemporaryFile")
@patch("os.chmod")
@patch("os.chown")
@patch("os.rename")
@patch("os.path.exists")
def test_tempfile_creation_and_move(
mock_exists, mock_rename, mock_chown, mock_chmod, mock_tempfile, mock_lock_file, connection
):
"""Test tempfile creation and move during close"""
connection._any_keys_added = MagicMock(return_value=True)
connection._connected = True
connection._save_ssh_host_keys = MagicMock()
connection.keyfile = "/tmp/wsl-known_hosts-test"
connection.set_option("host_key_checking", True)
connection.set_option("lock_file_timeout", 5)
connection.set_option("record_host_keys", True)
connection.ssh = MagicMock()
mock_exists.return_value = False
mock_lock_file_instance = MagicMock()
mock_lock_file.return_value = mock_lock_file_instance
mock_lock_file_instance.__enter__.return_value = None
mock_tempfile_instance = MagicMock()
mock_tempfile_instance.name = "/tmp/mock_tempfile"
mock_tempfile.return_value.__enter__.return_value = mock_tempfile_instance
mode = 0o644
uid = 1000
gid = 1000
key_dir = os.path.dirname(connection.keyfile)
with patch("os.getuid", return_value=uid), patch("os.getgid", return_value=gid):
connection.close()
connection._save_ssh_host_keys.assert_called_once_with("/tmp/mock_tempfile")
mock_chmod.assert_called_once_with("/tmp/mock_tempfile", mode)
mock_chown.assert_called_once_with("/tmp/mock_tempfile", uid, gid)
mock_rename.assert_called_once_with("/tmp/mock_tempfile", connection.keyfile)
mock_tempfile.assert_called_once_with(dir=key_dir, delete=False)
@patch("pathlib.Path.unlink")
@patch("tempfile.NamedTemporaryFile")
@patch("ansible_collections.community.general.plugins.module_utils._filelock.FileLock.lock_file")
@patch("os.path.exists")
def test_close_tempfile_error_handling(mock_exists, mock_lock_file, mock_tempfile, mock_unlink, connection):
"""Test tempfile creation error"""
connection._any_keys_added = MagicMock(return_value=True)
connection._connected = True
connection._save_ssh_host_keys = MagicMock()
connection.keyfile = "/tmp/wsl-known_hosts-test"
connection.set_option("host_key_checking", True)
connection.set_option("lock_file_timeout", 5)
connection.set_option("record_host_keys", True)
connection.ssh = MagicMock()
mock_exists.return_value = False
mock_lock_file_instance = MagicMock()
mock_lock_file.return_value = mock_lock_file_instance
mock_lock_file_instance.__enter__.return_value = None
mock_tempfile_instance = MagicMock()
mock_tempfile_instance.name = "/tmp/mock_tempfile"
mock_tempfile.return_value.__enter__.return_value = mock_tempfile_instance
with pytest.raises(AnsibleError, match="error occurred while writing SSH host keys!"):
with patch.object(os, "chmod", side_effect=Exception()):
connection.close()
mock_unlink.assert_called_with(missing_ok=True)
@patch("ansible_collections.community.general.plugins.module_utils._filelock.FileLock.lock_file")
@patch("os.path.exists")
def test_close_with_invalid_host_key(mock_exists, mock_lock_file, connection):
"""Test load_system_host_keys on close with InvalidHostKey error"""
connection._any_keys_added = MagicMock(return_value=True)
connection._connected = True
connection._save_ssh_host_keys = MagicMock()
connection.keyfile = "/tmp/wsl-known_hosts-test"
connection.set_option("host_key_checking", True)
connection.set_option("lock_file_timeout", 5)
connection.set_option("record_host_keys", True)
connection.ssh = MagicMock()
connection.ssh.load_system_host_keys.side_effect = paramiko.hostkeys.InvalidHostKey(
"Bad Line!", Exception("Something crashed!")
)
mock_exists.return_value = False
mock_lock_file_instance = MagicMock()
mock_lock_file.return_value = mock_lock_file_instance
mock_lock_file_instance.__enter__.return_value = None
with pytest.raises(AnsibleConnectionFailure, match="Invalid host key: Bad Line!"):
connection.close()
def test_reset(connection):
"""Test connection reset"""
connection._connected = True
connection.close = MagicMock()
connection._connect = MagicMock()
connection.reset()
connection.close.assert_called_once()
connection._connect.assert_called_once()
connection._connected = False
connection.reset()
assert connection.close.call_count == 1
@@ -0,0 +1,14 @@
# 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
import unittest
from ansible_collections.community.general.plugins.filter.crc32 import crc32s
class TestFilterCrc32(unittest.TestCase):
def test_checksum(self):
self.assertEqual(crc32s("test"), "d87f7e0c")
@@ -0,0 +1,296 @@
# Copyright (c) Stanislav Meduna (@numo68)
# 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 unittest
from ansible.errors import AnsibleFilterError
from ansible_collections.community.general.plugins.filter.json_patch import FilterModule
class TestJsonPatch(unittest.TestCase):
def setUp(self):
self.filter = FilterModule()
self.json_patch = self.filter.filters()["json_patch"]
self.json_diff = self.filter.filters()["json_diff"]
self.json_patch_recipe = self.filter.filters()["json_patch_recipe"]
# json_patch
def test_patch_add_to_empty(self):
result = self.json_patch({}, "add", "/a", 1)
self.assertEqual(result, {"a": 1})
def test_patch_add_to_dict(self):
result = self.json_patch({"b": 2}, "add", "/a", 1)
self.assertEqual(result, {"a": 1, "b": 2})
def test_patch_add_to_array_index(self):
result = self.json_patch([1, 2, 3], "add", "/1", 99)
self.assertEqual(result, [1, 99, 2, 3])
def test_patch_add_to_array_last(self):
result = self.json_patch({"a": [1, 2, 3]}, "add", "/a/-", 99)
self.assertEqual(result, {"a": [1, 2, 3, 99]})
def test_patch_add_from_string(self):
result = self.json_patch("[1, 2, 3]", "add", "/-", 99)
self.assertEqual(result, [1, 2, 3, 99])
def test_patch_path_escape(self):
result = self.json_patch({}, "add", "/x~0~1y", 99)
self.assertEqual(result, {"x~/y": 99})
def test_patch_remove(self):
result = self.json_patch({"a": 1, "b": {"c": 2}, "d": 3}, "remove", "/b")
self.assertEqual(result, {"a": 1, "d": 3})
def test_patch_replace(self):
result = self.json_patch({"a": 1, "b": {"c": 2}, "d": 3}, "replace", "/b", {"x": 99})
self.assertEqual(result, {"a": 1, "b": {"x": 99}, "d": 3})
def test_patch_copy(self):
result = self.json_patch({"a": 1, "b": {"c": 2}, "d": 3}, "copy", "/d", **{"from": "/b"})
self.assertEqual(result, {"a": 1, "b": {"c": 2}, "d": {"c": 2}})
def test_patch_move(self):
result = self.json_patch({"a": 1, "b": {"c": 2}, "d": 3}, "move", "/d", **{"from": "/b"})
self.assertEqual(result, {"a": 1, "d": {"c": 2}})
def test_patch_test_pass(self):
result = self.json_patch({"a": 1, "b": {"c": 2}, "d": 3}, "test", "/b/c", 2)
self.assertEqual(result, {"a": 1, "b": {"c": 2}, "d": 3})
def test_patch_test_fail_none(self):
result = self.json_patch({"a": 1, "b": {"c": 2}, "d": 3}, "test", "/b/c", 99)
self.assertIsNone(result)
def test_patch_test_fail_fail(self):
with self.assertRaises(AnsibleFilterError) as context:
self.json_patch({"a": 1, "b": {"c": 2}, "d": 3}, "test", "/b/c", 99, fail_test=True)
self.assertTrue("json_patch: test operation failed" in str(context.exception))
def test_patch_remove_nonexisting(self):
with self.assertRaises(AnsibleFilterError) as context:
self.json_patch({"a": 1, "b": {"c": 2}, "d": 3}, "remove", "/e")
self.assertEqual(
str(context.exception),
"json_patch: patch failed: can't remove a non-existent object 'e'",
)
def test_patch_missing_lib(self):
with unittest.mock.patch(
"ansible_collections.community.general.plugins.filter.json_patch.HAS_LIB",
False,
):
with self.assertRaises(AnsibleFilterError) as context:
self.json_patch({}, "add", "/a", 1)
self.assertEqual(
str(context.exception),
"You need to install 'jsonpatch' package prior to running 'json_patch' filter",
)
def test_patch_invalid_operation(self):
with self.assertRaises(AnsibleFilterError) as context:
self.json_patch({}, "invalid", "/a", 1)
self.assertEqual(
str(context.exception),
"json_patch: unsupported 'op' argument: invalid",
)
def test_patch_arg_checking(self):
with self.assertRaises(AnsibleFilterError) as context:
self.json_patch(1, "add", "/a", 1)
self.assertEqual(
str(context.exception),
"json_patch: input is not dictionary, list or string",
)
with self.assertRaises(AnsibleFilterError) as context:
self.json_patch({}, 1, "/a", 1)
self.assertEqual(
str(context.exception),
"json_patch: 'op' argument is not a string",
)
with self.assertRaises(AnsibleFilterError) as context:
self.json_patch({}, None, "/a", 1)
self.assertEqual(
str(context.exception),
"json_patch: 'op' argument is not a string",
)
with self.assertRaises(AnsibleFilterError) as context:
self.json_patch({}, "add", 1, 1)
self.assertEqual(
str(context.exception),
"json_patch: 'path' argument is not a string",
)
with self.assertRaises(AnsibleFilterError) as context:
self.json_patch({}, "copy", "/a", **{"from": 1})
self.assertEqual(
str(context.exception),
"json_patch: 'from' argument is not a string",
)
def test_patch_extra_kwarg(self):
with self.assertRaises(AnsibleFilterError) as context:
self.json_patch({}, "add", "/a", 1, invalid=True)
self.assertEqual(
str(context.exception),
"json_patch: unexpected keywords arguments: invalid",
)
def test_patch_missing_from(self):
with self.assertRaises(AnsibleFilterError) as context:
self.json_patch({}, "copy", "/a", 1)
self.assertEqual(
str(context.exception),
"json_patch: 'from' argument missing for 'copy' operation",
)
with self.assertRaises(AnsibleFilterError) as context:
self.json_patch({}, "move", "/a", 1)
self.assertEqual(
str(context.exception),
"json_patch: 'from' argument missing for 'move' operation",
)
def test_patch_add_to_dict_binary(self):
result = self.json_patch(b'{"b": 2}', "add", "/a", 1)
self.assertEqual(result, {"a": 1, "b": 2})
result = self.json_patch(bytearray(b'{"b": 2}'), "add", "/a", 1)
self.assertEqual(result, {"a": 1, "b": 2})
# json_patch_recipe
def test_patch_recipe_process(self):
result = self.json_patch_recipe(
{},
[
{"op": "add", "path": "/foo", "value": 1},
{"op": "add", "path": "/bar", "value": []},
{"op": "add", "path": "/bar/-", "value": 2},
{"op": "add", "path": "/bar/0", "value": 1},
{"op": "remove", "path": "/bar/0"},
{"op": "move", "from": "/foo", "path": "/baz"},
{"op": "copy", "from": "/baz", "path": "/bax"},
{"op": "copy", "from": "/baz", "path": "/bay"},
{"op": "replace", "path": "/baz", "value": [10, 20, 30]},
{"op": "add", "path": "/foo", "value": 1},
{"op": "add", "path": "/foo", "value": 1},
{"op": "test", "path": "/baz/1", "value": 20},
],
)
self.assertEqual(result, {"bar": [2], "bax": 1, "bay": 1, "baz": [10, 20, 30], "foo": 1})
def test_patch_recipe_test_fail(self):
result = self.json_patch_recipe(
{},
[
{"op": "add", "path": "/bar", "value": []},
{"op": "add", "path": "/bar/-", "value": 2},
{"op": "test", "path": "/bar/0", "value": 20},
{"op": "add", "path": "/bar/0", "value": 1},
],
)
self.assertIsNone(result)
def test_patch_recipe_missing_lib(self):
with unittest.mock.patch(
"ansible_collections.community.general.plugins.filter.json_patch.HAS_LIB",
False,
):
with self.assertRaises(AnsibleFilterError) as context:
self.json_patch_recipe({}, [])
self.assertEqual(
str(context.exception),
"You need to install 'jsonpatch' package prior to running 'json_patch_recipe' filter",
)
def test_patch_recipe_missing_from(self):
with self.assertRaises(AnsibleFilterError) as context:
self.json_patch_recipe({}, [{"op": "copy", "path": "/a"}])
self.assertEqual(
str(context.exception),
"json_patch_recipe: 'from' argument missing for 'copy' operation",
)
def test_patch_recipe_incorrect_type(self):
with self.assertRaises(AnsibleFilterError) as context:
self.json_patch_recipe({}, "copy")
self.assertEqual(
str(context.exception),
"json_patch_recipe: 'operations' needs to be a list",
)
def test_patch_recipe_test_fail_none(self):
result = self.json_patch_recipe(
{"a": 1, "b": {"c": 2}, "d": 3},
[{"op": "test", "path": "/b/c", "value": 99}],
)
self.assertIsNone(result)
def test_patch_recipe_test_fail_fail_pos(self):
with self.assertRaises(AnsibleFilterError) as context:
self.json_patch_recipe(
{"a": 1, "b": {"c": 2}, "d": 3},
[{"op": "test", "path": "/b/c", "value": 99}],
True,
)
self.assertTrue("json_patch_recipe: test operation failed" in str(context.exception))
def test_patch_recipe_test_fail_fail_kw(self):
with self.assertRaises(AnsibleFilterError) as context:
self.json_patch_recipe(
{"a": 1, "b": {"c": 2}, "d": 3},
[{"op": "test", "path": "/b/c", "value": 99}],
fail_test=True,
)
self.assertTrue("json_patch_recipe: test operation failed" in str(context.exception))
# json_diff
def test_diff_process(self):
result = self.json_diff(
{"foo": 1, "bar": {"baz": 2}, "baw": [1, 2, 3], "hello": "day"},
{
"foo": 1,
"bar": {"baz": 2},
"baw": [1, 3],
"baq": {"baz": 2},
"hello": "night",
},
)
# Sort as the order is unstable
self.assertEqual(
sorted(result, key=lambda k: k["path"]),
[
{"op": "add", "path": "/baq", "value": {"baz": 2}},
{"op": "remove", "path": "/baw/1"},
{"op": "replace", "path": "/hello", "value": "night"},
],
)
def test_diff_missing_lib(self):
with unittest.mock.patch(
"ansible_collections.community.general.plugins.filter.json_patch.HAS_LIB",
False,
):
with self.assertRaises(AnsibleFilterError) as context:
self.json_diff({}, {})
self.assertEqual(
str(context.exception),
"You need to install 'jsonpatch' package prior to running 'json_diff' filter",
)
def test_diff_arg_checking(self):
with self.assertRaises(AnsibleFilterError) as context:
self.json_diff(1, {})
self.assertEqual(str(context.exception), "json_diff: input is not dictionary, list or string")
with self.assertRaises(AnsibleFilterError) as context:
self.json_diff({}, 1)
self.assertEqual(
str(context.exception),
"json_diff: target is not dictionary, list or string",
)
@@ -0,0 +1,478 @@
all:
children:
test:
hosts:
test_101:
iocage_basejail: 'yes'
iocage_boot: 'off'
iocage_ip4_dict:
ip4:
- ifc: vnet0
ip: 10.1.0.101
mask: '24'
msg: ''
iocage_ip4: 10.1.0.101
iocage_ip6: '-'
iocage_jid: '-'
iocage_properties:
CONFIG_VERSION: '28'
allow_chflags: '0'
allow_mlock: '0'
allow_mount: '0'
allow_mount_devfs: '0'
allow_mount_fusefs: '0'
allow_mount_nullfs: '0'
allow_mount_procfs: '0'
allow_mount_tmpfs: '0'
allow_mount_zfs: '0'
allow_quotas: '0'
allow_raw_sockets: '0'
allow_set_hostname: '1'
allow_socket_af: '0'
allow_sysvipc: '0'
allow_tun: '0'
allow_vmm: '0'
assign_localhost: '0'
available: readonly
basejail: '1'
boot: '0'
bpf: '0'
children_max: '0'
comment: none
compression: lz4
compressratio: readonly
coredumpsize: 'off'
count: '1'
cpuset: 'off'
cputime: 'off'
datasize: 'off'
dedup: 'off'
defaultrouter: 10.1.0.10
defaultrouter6: auto
depends: none
devfs_ruleset: '4'
dhcp: '0'
enforce_statfs: '2'
exec_clean: '1'
exec_created: /usr/bin/true
exec_fib: '0'
exec_jail_user: root
exec_poststart: /usr/bin/true
exec_poststop: /usr/bin/true
exec_prestart: /usr/bin/true
exec_prestop: /usr/bin/true
exec_start: /bin/sh /etc/rc
exec_stop: /bin/sh /etc/rc.shutdown
exec_system_jail_user: '0'
exec_system_user: root
exec_timeout: '60'
host_domainname: none
host_hostname: ansible-client
host_hostuuid: test_101
host_time: '1'
hostid: 34333834-3734-5a43-3331-313342464631
hostid_strict_check: '0'
interfaces: vnet0:bridge0
ip4: new
ip4_addr: vnet0|10.1.0.101/24
ip4_saddrsel: '1'
ip6: new
ip6_addr: none
ip6_saddrsel: '1'
ip_hostname: '0'
jail_zfs: '0'
jail_zfs_dataset: iocage/jails/test_101/data
jail_zfs_mountpoint: none
last_started: none
localhost_ip: none
login_flags: -f root
mac_prefix: 3e4a92
maxproc: 'off'
memorylocked: 'off'
memoryuse: 'off'
min_dyn_devfs_ruleset: '1000'
mount_devfs: '1'
mount_fdescfs: '1'
mount_linprocfs: '0'
mount_procfs: '0'
mountpoint: readonly
msgqqueued: 'off'
msgqsize: 'off'
nat: '0'
nat_backend: ipfw
nat_forwards: none
nat_interface: none
nat_prefix: '172.16'
nmsgq: 'off'
notes: vmm=iocage_01
nsem: 'off'
nsemop: 'off'
nshm: 'off'
nthr: 'off'
openfiles: 'off'
origin: readonly
owner: root
pcpu: 'off'
plugin_name: none
plugin_repository: none
priority: '99'
pseudoterminals: 'off'
quota: none
readbps: 'off'
readiops: 'off'
release: 13.4-RELEASE-p2
reservation: none
resolver: /etc/resolv.conf
rlimits: 'off'
rtsold: '0'
securelevel: '2'
shmsize: 'off'
stacksize: 'off'
state: down
stop_timeout: '30'
swapuse: 'off'
sync_state: none
sync_target: none
sync_tgt_zpool: none
sysvmsg: new
sysvsem: new
sysvshm: new
template: '0'
type: jail
used: readonly
vmemoryuse: 'off'
vnet: '1'
vnet0_mac: none
vnet0_mtu: auto
vnet1_mac: none
vnet1_mtu: auto
vnet2_mac: none
vnet2_mtu: auto
vnet3_mac: none
vnet3_mtu: auto
vnet_default_interface: auto
vnet_default_mtu: '1500'
vnet_interfaces: none
wallclock: 'off'
writebps: 'off'
writeiops: 'off'
iocage_release: 13.4-RELEASE-p2
iocage_state: down
iocage_template: ansible_client
iocage_type: jail
test_102:
iocage_basejail: 'yes'
iocage_boot: 'off'
iocage_ip4_dict:
ip4:
- ifc: vnet0
ip: 10.1.0.102
mask: '24'
msg: ''
iocage_ip4: 10.1.0.102
iocage_ip6: '-'
iocage_jid: '-'
iocage_properties:
CONFIG_VERSION: '28'
allow_chflags: '0'
allow_mlock: '0'
allow_mount: '0'
allow_mount_devfs: '0'
allow_mount_fusefs: '0'
allow_mount_nullfs: '0'
allow_mount_procfs: '0'
allow_mount_tmpfs: '0'
allow_mount_zfs: '0'
allow_quotas: '0'
allow_raw_sockets: '0'
allow_set_hostname: '1'
allow_socket_af: '0'
allow_sysvipc: '0'
allow_tun: '0'
allow_vmm: '0'
assign_localhost: '0'
available: readonly
basejail: '1'
boot: '0'
bpf: '0'
children_max: '0'
comment: none
compression: lz4
compressratio: readonly
coredumpsize: 'off'
count: '1'
cpuset: 'off'
cputime: 'off'
datasize: 'off'
dedup: 'off'
defaultrouter: 10.1.0.10
defaultrouter6: auto
depends: none
devfs_ruleset: '4'
dhcp: '0'
enforce_statfs: '2'
exec_clean: '1'
exec_created: /usr/bin/true
exec_fib: '0'
exec_jail_user: root
exec_poststart: /usr/bin/true
exec_poststop: /usr/bin/true
exec_prestart: /usr/bin/true
exec_prestop: /usr/bin/true
exec_start: /bin/sh /etc/rc
exec_stop: /bin/sh /etc/rc.shutdown
exec_system_jail_user: '0'
exec_system_user: root
exec_timeout: '60'
host_domainname: none
host_hostname: ansible-client
host_hostuuid: test_102
host_time: '1'
hostid: 34333834-3734-5a43-3331-313342464631
hostid_strict_check: '0'
interfaces: vnet0:bridge0
ip4: new
ip4_addr: vnet0|10.1.0.102/24
ip4_saddrsel: '1'
ip6: new
ip6_addr: none
ip6_saddrsel: '1'
ip_hostname: '0'
jail_zfs: '0'
jail_zfs_dataset: iocage/jails/test_102/data
jail_zfs_mountpoint: none
last_started: none
localhost_ip: none
login_flags: -f root
mac_prefix: 3e4a92
maxproc: 'off'
memorylocked: 'off'
memoryuse: 'off'
min_dyn_devfs_ruleset: '1000'
mount_devfs: '1'
mount_fdescfs: '1'
mount_linprocfs: '0'
mount_procfs: '0'
mountpoint: readonly
msgqqueued: 'off'
msgqsize: 'off'
nat: '0'
nat_backend: ipfw
nat_forwards: none
nat_interface: none
nat_prefix: '172.16'
nmsgq: 'off'
notes: vmm=iocage_01
nsem: 'off'
nsemop: 'off'
nshm: 'off'
nthr: 'off'
openfiles: 'off'
origin: readonly
owner: root
pcpu: 'off'
plugin_name: none
plugin_repository: none
priority: '99'
pseudoterminals: 'off'
quota: none
readbps: 'off'
readiops: 'off'
release: 13.4-RELEASE-p2
reservation: none
resolver: /etc/resolv.conf
rlimits: 'off'
rtsold: '0'
securelevel: '2'
shmsize: 'off'
stacksize: 'off'
state: down
stop_timeout: '30'
swapuse: 'off'
sync_state: none
sync_target: none
sync_tgt_zpool: none
sysvmsg: new
sysvsem: new
sysvshm: new
template: '0'
type: jail
used: readonly
vmemoryuse: 'off'
vnet: '1'
vnet0_mac: none
vnet0_mtu: auto
vnet1_mac: none
vnet1_mtu: auto
vnet2_mac: none
vnet2_mtu: auto
vnet3_mac: none
vnet3_mtu: auto
vnet_default_interface: auto
vnet_default_mtu: '1500'
vnet_interfaces: none
wallclock: 'off'
writebps: 'off'
writeiops: 'off'
iocage_release: 13.4-RELEASE-p2
iocage_state: down
iocage_template: ansible_client
iocage_type: jail
test_103:
iocage_basejail: 'yes'
iocage_boot: 'off'
iocage_ip4_dict:
ip4:
- ifc: vnet0
ip: 10.1.0.103
mask: '24'
msg: ''
iocage_ip4: 10.1.0.103
iocage_ip6: '-'
iocage_jid: '-'
iocage_properties:
CONFIG_VERSION: '28'
allow_chflags: '0'
allow_mlock: '0'
allow_mount: '0'
allow_mount_devfs: '0'
allow_mount_fusefs: '0'
allow_mount_nullfs: '0'
allow_mount_procfs: '0'
allow_mount_tmpfs: '0'
allow_mount_zfs: '0'
allow_quotas: '0'
allow_raw_sockets: '0'
allow_set_hostname: '1'
allow_socket_af: '0'
allow_sysvipc: '0'
allow_tun: '0'
allow_vmm: '0'
assign_localhost: '0'
available: readonly
basejail: '1'
boot: '0'
bpf: '0'
children_max: '0'
comment: none
compression: lz4
compressratio: readonly
coredumpsize: 'off'
count: '1'
cpuset: 'off'
cputime: 'off'
datasize: 'off'
dedup: 'off'
defaultrouter: 10.1.0.10
defaultrouter6: auto
depends: none
devfs_ruleset: '4'
dhcp: '0'
enforce_statfs: '2'
exec_clean: '1'
exec_created: /usr/bin/true
exec_fib: '0'
exec_jail_user: root
exec_poststart: /usr/bin/true
exec_poststop: /usr/bin/true
exec_prestart: /usr/bin/true
exec_prestop: /usr/bin/true
exec_start: /bin/sh /etc/rc
exec_stop: /bin/sh /etc/rc.shutdown
exec_system_jail_user: '0'
exec_system_user: root
exec_timeout: '60'
host_domainname: none
host_hostname: ansible-client
host_hostuuid: test_103
host_time: '1'
hostid: 34333834-3734-5a43-3331-313342464631
hostid_strict_check: '0'
interfaces: vnet0:bridge0
ip4: new
ip4_addr: vnet0|10.1.0.103/24
ip4_saddrsel: '1'
ip6: new
ip6_addr: none
ip6_saddrsel: '1'
ip_hostname: '0'
jail_zfs: '0'
jail_zfs_dataset: iocage/jails/test_103/data
jail_zfs_mountpoint: none
last_started: none
localhost_ip: none
login_flags: -f root
mac_prefix: 3e4a92
maxproc: 'off'
memorylocked: 'off'
memoryuse: 'off'
min_dyn_devfs_ruleset: '1000'
mount_devfs: '1'
mount_fdescfs: '1'
mount_linprocfs: '0'
mount_procfs: '0'
mountpoint: readonly
msgqqueued: 'off'
msgqsize: 'off'
nat: '0'
nat_backend: ipfw
nat_forwards: none
nat_interface: none
nat_prefix: '172.16'
nmsgq: 'off'
notes: vmm=iocage_01
nsem: 'off'
nsemop: 'off'
nshm: 'off'
nthr: 'off'
openfiles: 'off'
origin: readonly
owner: root
pcpu: 'off'
plugin_name: none
plugin_repository: none
priority: '99'
pseudoterminals: 'off'
quota: none
readbps: 'off'
readiops: 'off'
release: 13.4-RELEASE-p2
reservation: none
resolver: /etc/resolv.conf
rlimits: 'off'
rtsold: '0'
securelevel: '2'
shmsize: 'off'
stacksize: 'off'
state: down
stop_timeout: '30'
swapuse: 'off'
sync_state: none
sync_target: none
sync_tgt_zpool: none
sysvmsg: new
sysvsem: new
sysvshm: new
template: '0'
type: jail
used: readonly
vmemoryuse: 'off'
vnet: '1'
vnet0_mac: none
vnet0_mtu: auto
vnet1_mac: none
vnet1_mtu: auto
vnet2_mac: none
vnet2_mtu: auto
vnet3_mac: none
vnet3_mtu: auto
vnet_default_interface: auto
vnet_default_mtu: '1500'
vnet_interfaces: none
wallclock: 'off'
writebps: 'off'
writeiops: 'off'
iocage_release: 13.4-RELEASE-p2
iocage_state: down
iocage_template: ansible_client
iocage_type: jail
@@ -0,0 +1,3 @@
GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
SPDX-License-Identifier: GPL-3.0-or-later
SPDX-FileCopyrightText: Ansible Project
@@ -0,0 +1,9 @@
+------+----------+------+-------+------+-----------------+---------------------+-----+----------------+----------+
| JID | NAME | BOOT | STATE | TYPE | RELEASE | IP4 | IP6 | TEMPLATE | BASEJAIL |
+======+==========+======+=======+======+=================+=====================+=====+================+==========+
| - | test_101 | off | down | jail | 13.4-RELEASE-p2 | vnet0|10.1.0.101/24 | - | ansible_client | yes |
+------+----------------+------+-------+------+-----------------+--------------------+-----+----------------+-----+
| - | test_102 | off | down | jail | 13.4-RELEASE-p2 | vnet0|10.1.0.102/24 | - | ansible_client | yes |
+------+----------------+------+-------+------+-----------------+--------------------+-----+----------------+-----+
| - | test_103 | off | down | jail | 13.4-RELEASE-p2 | vnet0|10.1.0.103/24 | - | ansible_client | yes |
+------+----------------+------+-------+------+-----------------+--------------------+-----+----------------+-----+
@@ -0,0 +1,3 @@
GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
SPDX-License-Identifier: GPL-3.0-or-later
SPDX-FileCopyrightText: Ansible Project
@@ -0,0 +1,50 @@
_meta:
hostvars:
test_101:
iocage_basejail: 'yes'
iocage_boot: 'off'
iocage_ip4_dict:
ip4:
- ifc: vnet0
ip: 10.1.0.101
mask: '24'
msg: ''
iocage_ip4: 10.1.0.101
iocage_ip6: '-'
iocage_jid: '-'
iocage_release: 13.4-RELEASE-p2
iocage_state: down
iocage_template: ansible_client
iocage_type: jail
test_102:
iocage_basejail: 'yes'
iocage_boot: 'off'
iocage_ip4_dict:
ip4:
- ifc: vnet0
ip: 10.1.0.102
mask: '24'
msg: ''
iocage_ip4: 10.1.0.102
iocage_ip6: '-'
iocage_jid: '-'
iocage_release: 13.4-RELEASE-p2
iocage_state: down
iocage_template: ansible_client
iocage_type: jail
test_103:
iocage_basejail: 'yes'
iocage_boot: 'off'
iocage_ip4_dict:
ip4:
- ifc: vnet0
ip: 10.1.0.103
mask: '24'
msg: ''
iocage_ip4: 10.1.0.103
iocage_ip6: '-'
iocage_jid: '-'
iocage_release: 13.4-RELEASE-p2
iocage_state: down
iocage_template: ansible_client
iocage_type: jail
@@ -0,0 +1,3 @@
GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
SPDX-License-Identifier: GPL-3.0-or-later
SPDX-FileCopyrightText: Ansible Project
@@ -0,0 +1,9 @@
+------+----------------+------+-------+------+-----------------+--------------------+-----+----------------+----------+
| JID | NAME | BOOT | STATE | TYPE | RELEASE | IP4 | IP6 | TEMPLATE | BASEJAIL |
+======+================+======+=======+======+=================+====================+=====+================+==========+
| 268 | test_111 | off | up | jail | 14.1-RELEASE-p6 | epair0b|10.1.0.174 | - | ansible_client | yes |
+------+----------------+------+-------+------+-----------------+--------------------+-----+----------------+----------+
| 269 | test_112 | off | up | jail | 14.1-RELEASE-p6 | epair0b|10.1.0.147 | - | ansible_client | yes |
+------+----------------+------+-------+------+-----------------+--------------------+-----+----------------+----------+
| 270 | test_113 | off | up | jail | 14.1-RELEASE-p6 | epair0b|10.1.0.231 | - | ansible_client | yes |
+------+----------------+------+-------+------+-----------------+--------------------+-----+----------------+----------+
@@ -0,0 +1,3 @@
GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
SPDX-License-Identifier: GPL-3.0-or-later
SPDX-FileCopyrightText: Ansible Project
@@ -0,0 +1,50 @@
_meta:
hostvars:
test_111:
iocage_basejail: 'yes'
iocage_boot: 'off'
iocage_ip4_dict:
ip4:
- ifc: epair0b
ip: 10.1.0.174
mask: '-'
msg: ''
iocage_ip4: 10.1.0.174
iocage_ip6: '-'
iocage_jid: '268'
iocage_release: 14.1-RELEASE-p6
iocage_state: up
iocage_template: ansible_client
iocage_type: jail
test_112:
iocage_basejail: 'yes'
iocage_boot: 'off'
iocage_ip4_dict:
ip4:
- ifc: epair0b
ip: 10.1.0.147
mask: '-'
msg: ''
iocage_ip4: 10.1.0.147
iocage_ip6: '-'
iocage_jid: '269'
iocage_release: 14.1-RELEASE-p6
iocage_state: up
iocage_template: ansible_client
iocage_type: jail
test_113:
iocage_basejail: 'yes'
iocage_boot: 'off'
iocage_ip4_dict:
ip4:
- ifc: epair0b
ip: 10.1.0.231
mask: '-'
msg: ''
iocage_ip4: 10.1.0.231
iocage_ip6: '-'
iocage_jid: '270'
iocage_release: 14.1-RELEASE-p6
iocage_state: up
iocage_template: ansible_client
iocage_type: jail
@@ -0,0 +1,3 @@
GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
SPDX-License-Identifier: GPL-3.0-or-later
SPDX-FileCopyrightText: Ansible Project
@@ -0,0 +1,9 @@
+------+----------------+------+-------+------+-----------------+--------------------+-----+----------------+----------+
| JID | NAME | BOOT | STATE | TYPE | RELEASE | IP4 | IP6 | TEMPLATE | BASEJAIL |
+======+================+======+=======+======+=================+====================+=====+================+==========+
| None | test_111 | off | down | jail | 14.1-RELEASE-p6 | DHCP (not running) | - | ansible_client | yes |
+------+----------------+------+-------+------+-----------------+--------------------+-----+----------------+----------+
| None | test_112 | off | down | jail | 14.1-RELEASE-p6 | DHCP (not running) | - | ansible_client | yes |
+------+----------------+------+-------+------+-----------------+--------------------+-----+----------------+----------+
| None | test_113 | off | down | jail | 14.1-RELEASE-p6 | DHCP (not running) | - | ansible_client | yes |
+------+----------------+------+-------+------+-----------------+--------------------+-----+----------------+----------+
@@ -0,0 +1,3 @@
GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
SPDX-License-Identifier: GPL-3.0-or-later
SPDX-FileCopyrightText: Ansible Project
@@ -0,0 +1,41 @@
_meta:
hostvars:
test_111:
iocage_basejail: 'yes'
iocage_boot: 'off'
iocage_ip4_dict:
ip4: []
msg: 'DHCP (not running)'
iocage_ip4: '-'
iocage_ip6: '-'
iocage_jid: 'None'
iocage_release: 14.1-RELEASE-p6
iocage_state: down
iocage_template: ansible_client
iocage_type: jail
test_112:
iocage_basejail: 'yes'
iocage_boot: 'off'
iocage_ip4_dict:
ip4: []
msg: 'DHCP (not running)'
iocage_ip4: '-'
iocage_ip6: '-'
iocage_jid: 'None'
iocage_release: 14.1-RELEASE-p6
iocage_state: down
iocage_template: ansible_client
iocage_type: jail
test_113:
iocage_basejail: 'yes'
iocage_boot: 'off'
iocage_ip4_dict:
ip4: []
msg: 'DHCP (not running)'
iocage_ip4: '-'
iocage_ip6: '-'
iocage_jid: 'None'
iocage_release: 14.1-RELEASE-p6
iocage_state: down
iocage_template: ansible_client
iocage_type: jail
@@ -0,0 +1,3 @@
GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
SPDX-License-Identifier: GPL-3.0-or-later
SPDX-FileCopyrightText: Ansible Project
@@ -0,0 +1,11 @@
CONFIG_VERSION:28
notes:abbridged_properties
allow_chflags:0
allow_mlock:0
allow_mount:0
allow_mount_devfs:0
allow_mount_fusefs:0
allow_mount_nullfs:0
allow_mount_procfs:0
allow_mount_tmpfs:0
allow_mount_zfs:0
@@ -0,0 +1,3 @@
GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
SPDX-License-Identifier: GPL-3.0-or-later
SPDX-FileCopyrightText: Ansible Project
@@ -0,0 +1,476 @@
_meta:
hostvars:
test_101:
iocage_basejail: 'yes'
iocage_boot: 'off'
iocage_ip4_dict:
ip4:
- ifc: vnet0
ip: 10.1.0.101
mask: '24'
msg: ''
iocage_ip4: 10.1.0.101
iocage_ip6: '-'
iocage_jid: '-'
iocage_properties:
CONFIG_VERSION: '28'
allow_chflags: '0'
allow_mlock: '0'
allow_mount: '0'
allow_mount_devfs: '0'
allow_mount_fusefs: '0'
allow_mount_nullfs: '0'
allow_mount_procfs: '0'
allow_mount_tmpfs: '0'
allow_mount_zfs: '0'
allow_quotas: '0'
allow_raw_sockets: '0'
allow_set_hostname: '1'
allow_socket_af: '0'
allow_sysvipc: '0'
allow_tun: '0'
allow_vmm: '0'
assign_localhost: '0'
available: readonly
basejail: '1'
boot: '0'
bpf: '0'
children_max: '0'
comment: none
compression: lz4
compressratio: readonly
coredumpsize: 'off'
count: '1'
cpuset: 'off'
cputime: 'off'
datasize: 'off'
dedup: 'off'
defaultrouter: 10.1.0.10
defaultrouter6: auto
depends: none
devfs_ruleset: '4'
dhcp: '0'
enforce_statfs: '2'
exec_clean: '1'
exec_created: /usr/bin/true
exec_fib: '0'
exec_jail_user: root
exec_poststart: /usr/bin/true
exec_poststop: /usr/bin/true
exec_prestart: /usr/bin/true
exec_prestop: /usr/bin/true
exec_start: /bin/sh /etc/rc
exec_stop: /bin/sh /etc/rc.shutdown
exec_system_jail_user: '0'
exec_system_user: root
exec_timeout: '60'
host_domainname: none
host_hostname: ansible-client
host_hostuuid: test_101
host_time: '1'
hostid: 34333834-3734-5a43-3331-313342464631
hostid_strict_check: '0'
interfaces: vnet0:bridge0
ip4: new
ip4_addr: vnet0|10.1.0.101/24
ip4_saddrsel: '1'
ip6: new
ip6_addr: none
ip6_saddrsel: '1'
ip_hostname: '0'
jail_zfs: '0'
jail_zfs_dataset: iocage/jails/test_101/data
jail_zfs_mountpoint: none
last_started: none
localhost_ip: none
login_flags: -f root
mac_prefix: 3e4a92
maxproc: 'off'
memorylocked: 'off'
memoryuse: 'off'
min_dyn_devfs_ruleset: '1000'
mount_devfs: '1'
mount_fdescfs: '1'
mount_linprocfs: '0'
mount_procfs: '0'
mountpoint: readonly
msgqqueued: 'off'
msgqsize: 'off'
nat: '0'
nat_backend: ipfw
nat_forwards: none
nat_interface: none
nat_prefix: '172.16'
nmsgq: 'off'
notes: vmm=iocage_01
nsem: 'off'
nsemop: 'off'
nshm: 'off'
nthr: 'off'
openfiles: 'off'
origin: readonly
owner: root
pcpu: 'off'
plugin_name: none
plugin_repository: none
priority: '99'
pseudoterminals: 'off'
quota: none
readbps: 'off'
readiops: 'off'
release: 13.4-RELEASE-p2
reservation: none
resolver: /etc/resolv.conf
rlimits: 'off'
rtsold: '0'
securelevel: '2'
shmsize: 'off'
stacksize: 'off'
state: down
stop_timeout: '30'
swapuse: 'off'
sync_state: none
sync_target: none
sync_tgt_zpool: none
sysvmsg: new
sysvsem: new
sysvshm: new
template: '0'
type: jail
used: readonly
vmemoryuse: 'off'
vnet: '1'
vnet0_mac: none
vnet0_mtu: auto
vnet1_mac: none
vnet1_mtu: auto
vnet2_mac: none
vnet2_mtu: auto
vnet3_mac: none
vnet3_mtu: auto
vnet_default_interface: auto
vnet_default_mtu: '1500'
vnet_interfaces: none
wallclock: 'off'
writebps: 'off'
writeiops: 'off'
iocage_release: 13.4-RELEASE-p2
iocage_state: down
iocage_template: ansible_client
iocage_type: jail
test_102:
iocage_basejail: 'yes'
iocage_boot: 'off'
iocage_ip4_dict:
ip4:
- ifc: vnet0
ip: 10.1.0.102
mask: '24'
msg: ''
iocage_ip4: 10.1.0.102
iocage_ip6: '-'
iocage_jid: '-'
iocage_properties:
CONFIG_VERSION: '28'
allow_chflags: '0'
allow_mlock: '0'
allow_mount: '0'
allow_mount_devfs: '0'
allow_mount_fusefs: '0'
allow_mount_nullfs: '0'
allow_mount_procfs: '0'
allow_mount_tmpfs: '0'
allow_mount_zfs: '0'
allow_quotas: '0'
allow_raw_sockets: '0'
allow_set_hostname: '1'
allow_socket_af: '0'
allow_sysvipc: '0'
allow_tun: '0'
allow_vmm: '0'
assign_localhost: '0'
available: readonly
basejail: '1'
boot: '0'
bpf: '0'
children_max: '0'
comment: none
compression: lz4
compressratio: readonly
coredumpsize: 'off'
count: '1'
cpuset: 'off'
cputime: 'off'
datasize: 'off'
dedup: 'off'
defaultrouter: 10.1.0.10
defaultrouter6: auto
depends: none
devfs_ruleset: '4'
dhcp: '0'
enforce_statfs: '2'
exec_clean: '1'
exec_created: /usr/bin/true
exec_fib: '0'
exec_jail_user: root
exec_poststart: /usr/bin/true
exec_poststop: /usr/bin/true
exec_prestart: /usr/bin/true
exec_prestop: /usr/bin/true
exec_start: /bin/sh /etc/rc
exec_stop: /bin/sh /etc/rc.shutdown
exec_system_jail_user: '0'
exec_system_user: root
exec_timeout: '60'
host_domainname: none
host_hostname: ansible-client
host_hostuuid: test_102
host_time: '1'
hostid: 34333834-3734-5a43-3331-313342464631
hostid_strict_check: '0'
interfaces: vnet0:bridge0
ip4: new
ip4_addr: vnet0|10.1.0.102/24
ip4_saddrsel: '1'
ip6: new
ip6_addr: none
ip6_saddrsel: '1'
ip_hostname: '0'
jail_zfs: '0'
jail_zfs_dataset: iocage/jails/test_102/data
jail_zfs_mountpoint: none
last_started: none
localhost_ip: none
login_flags: -f root
mac_prefix: 3e4a92
maxproc: 'off'
memorylocked: 'off'
memoryuse: 'off'
min_dyn_devfs_ruleset: '1000'
mount_devfs: '1'
mount_fdescfs: '1'
mount_linprocfs: '0'
mount_procfs: '0'
mountpoint: readonly
msgqqueued: 'off'
msgqsize: 'off'
nat: '0'
nat_backend: ipfw
nat_forwards: none
nat_interface: none
nat_prefix: '172.16'
nmsgq: 'off'
notes: vmm=iocage_01
nsem: 'off'
nsemop: 'off'
nshm: 'off'
nthr: 'off'
openfiles: 'off'
origin: readonly
owner: root
pcpu: 'off'
plugin_name: none
plugin_repository: none
priority: '99'
pseudoterminals: 'off'
quota: none
readbps: 'off'
readiops: 'off'
release: 13.4-RELEASE-p2
reservation: none
resolver: /etc/resolv.conf
rlimits: 'off'
rtsold: '0'
securelevel: '2'
shmsize: 'off'
stacksize: 'off'
state: down
stop_timeout: '30'
swapuse: 'off'
sync_state: none
sync_target: none
sync_tgt_zpool: none
sysvmsg: new
sysvsem: new
sysvshm: new
template: '0'
type: jail
used: readonly
vmemoryuse: 'off'
vnet: '1'
vnet0_mac: none
vnet0_mtu: auto
vnet1_mac: none
vnet1_mtu: auto
vnet2_mac: none
vnet2_mtu: auto
vnet3_mac: none
vnet3_mtu: auto
vnet_default_interface: auto
vnet_default_mtu: '1500'
vnet_interfaces: none
wallclock: 'off'
writebps: 'off'
writeiops: 'off'
iocage_release: 13.4-RELEASE-p2
iocage_state: down
iocage_template: ansible_client
iocage_type: jail
test_103:
iocage_basejail: 'yes'
iocage_boot: 'off'
iocage_ip4_dict:
ip4:
- ifc: vnet0
ip: 10.1.0.103
mask: '24'
msg: ''
iocage_ip4: 10.1.0.103
iocage_ip6: '-'
iocage_jid: '-'
iocage_properties:
CONFIG_VERSION: '28'
allow_chflags: '0'
allow_mlock: '0'
allow_mount: '0'
allow_mount_devfs: '0'
allow_mount_fusefs: '0'
allow_mount_nullfs: '0'
allow_mount_procfs: '0'
allow_mount_tmpfs: '0'
allow_mount_zfs: '0'
allow_quotas: '0'
allow_raw_sockets: '0'
allow_set_hostname: '1'
allow_socket_af: '0'
allow_sysvipc: '0'
allow_tun: '0'
allow_vmm: '0'
assign_localhost: '0'
available: readonly
basejail: '1'
boot: '0'
bpf: '0'
children_max: '0'
comment: none
compression: lz4
compressratio: readonly
coredumpsize: 'off'
count: '1'
cpuset: 'off'
cputime: 'off'
datasize: 'off'
dedup: 'off'
defaultrouter: 10.1.0.10
defaultrouter6: auto
depends: none
devfs_ruleset: '4'
dhcp: '0'
enforce_statfs: '2'
exec_clean: '1'
exec_created: /usr/bin/true
exec_fib: '0'
exec_jail_user: root
exec_poststart: /usr/bin/true
exec_poststop: /usr/bin/true
exec_prestart: /usr/bin/true
exec_prestop: /usr/bin/true
exec_start: /bin/sh /etc/rc
exec_stop: /bin/sh /etc/rc.shutdown
exec_system_jail_user: '0'
exec_system_user: root
exec_timeout: '60'
host_domainname: none
host_hostname: ansible-client
host_hostuuid: test_103
host_time: '1'
hostid: 34333834-3734-5a43-3331-313342464631
hostid_strict_check: '0'
interfaces: vnet0:bridge0
ip4: new
ip4_addr: vnet0|10.1.0.103/24
ip4_saddrsel: '1'
ip6: new
ip6_addr: none
ip6_saddrsel: '1'
ip_hostname: '0'
jail_zfs: '0'
jail_zfs_dataset: iocage/jails/test_103/data
jail_zfs_mountpoint: none
last_started: none
localhost_ip: none
login_flags: -f root
mac_prefix: 3e4a92
maxproc: 'off'
memorylocked: 'off'
memoryuse: 'off'
min_dyn_devfs_ruleset: '1000'
mount_devfs: '1'
mount_fdescfs: '1'
mount_linprocfs: '0'
mount_procfs: '0'
mountpoint: readonly
msgqqueued: 'off'
msgqsize: 'off'
nat: '0'
nat_backend: ipfw
nat_forwards: none
nat_interface: none
nat_prefix: '172.16'
nmsgq: 'off'
notes: vmm=iocage_01
nsem: 'off'
nsemop: 'off'
nshm: 'off'
nthr: 'off'
openfiles: 'off'
origin: readonly
owner: root
pcpu: 'off'
plugin_name: none
plugin_repository: none
priority: '99'
pseudoterminals: 'off'
quota: none
readbps: 'off'
readiops: 'off'
release: 13.4-RELEASE-p2
reservation: none
resolver: /etc/resolv.conf
rlimits: 'off'
rtsold: '0'
securelevel: '2'
shmsize: 'off'
stacksize: 'off'
state: down
stop_timeout: '30'
swapuse: 'off'
sync_state: none
sync_target: none
sync_tgt_zpool: none
sysvmsg: new
sysvsem: new
sysvshm: new
template: '0'
type: jail
used: readonly
vmemoryuse: 'off'
vnet: '1'
vnet0_mac: none
vnet0_mtu: auto
vnet1_mac: none
vnet1_mtu: auto
vnet2_mac: none
vnet2_mtu: auto
vnet3_mac: none
vnet3_mtu: auto
vnet_default_interface: auto
vnet_default_mtu: '1500'
vnet_interfaces: none
wallclock: 'off'
writebps: 'off'
writeiops: 'off'
iocage_release: 13.4-RELEASE-p2
iocage_state: down
iocage_template: ansible_client
iocage_type: jail
@@ -0,0 +1,3 @@
GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
SPDX-License-Identifier: GPL-3.0-or-later
SPDX-FileCopyrightText: Ansible Project
@@ -0,0 +1,141 @@
CONFIG_VERSION:28
allow_chflags:0
allow_mlock:0
allow_mount:0
allow_mount_devfs:0
allow_mount_fusefs:0
allow_mount_nullfs:0
allow_mount_procfs:0
allow_mount_tmpfs:0
allow_mount_zfs:0
allow_quotas:0
allow_raw_sockets:0
allow_set_hostname:1
allow_socket_af:0
allow_sysvipc:0
allow_tun:0
allow_vmm:0
assign_localhost:0
available:readonly
basejail:1
boot:0
bpf:0
children_max:0
comment:none
compression:lz4
compressratio:readonly
coredumpsize:off
count:1
cpuset:off
cputime:off
datasize:off
dedup:off
defaultrouter:10.1.0.10
defaultrouter6:auto
depends:none
devfs_ruleset:4
dhcp:0
enforce_statfs:2
exec_clean:1
exec_created:/usr/bin/true
exec_fib:0
exec_jail_user:root
exec_poststart:/usr/bin/true
exec_poststop:/usr/bin/true
exec_prestart:/usr/bin/true
exec_prestop:/usr/bin/true
exec_start:/bin/sh /etc/rc
exec_stop:/bin/sh /etc/rc.shutdown
exec_system_jail_user:0
exec_system_user:root
exec_timeout:60
host_domainname:none
host_hostname:ansible-client
host_hostuuid:test_101
host_time:1
hostid:34333834-3734-5a43-3331-313342464631
hostid_strict_check:0
interfaces:vnet0:bridge0
ip4:new
ip4_addr:vnet0|10.1.0.101/24
ip4_saddrsel:1
ip6:new
ip6_addr:none
ip6_saddrsel:1
ip_hostname:0
jail_zfs:0
jail_zfs_dataset:iocage/jails/test_101/data
jail_zfs_mountpoint:none
last_started:none
localhost_ip:none
login_flags:-f root
mac_prefix:3e4a92
maxproc:off
memorylocked:off
memoryuse:off
min_dyn_devfs_ruleset:1000
mount_devfs:1
mount_fdescfs:1
mount_linprocfs:0
mount_procfs:0
mountpoint:readonly
msgqqueued:off
msgqsize:off
nat:0
nat_backend:ipfw
nat_forwards:none
nat_interface:none
nat_prefix:172.16
nmsgq:off
notes:vmm=iocage_01
nsem:off
nsemop:off
nshm:off
nthr:off
openfiles:off
origin:readonly
owner:root
pcpu:off
plugin_name:none
plugin_repository:none
priority:99
pseudoterminals:off
quota:none
readbps:off
readiops:off
release:13.4-RELEASE-p2
reservation:none
resolver:/etc/resolv.conf
rlimits:off
rtsold:0
securelevel:2
shmsize:off
stacksize:off
state:down
stop_timeout:30
swapuse:off
sync_state:none
sync_target:none
sync_tgt_zpool:none
sysvmsg:new
sysvsem:new
sysvshm:new
template:0
type:jail
used:readonly
vmemoryuse:off
vnet:1
vnet0_mac:none
vnet0_mtu:auto
vnet1_mac:none
vnet1_mtu:auto
vnet2_mac:none
vnet2_mtu:auto
vnet3_mac:none
vnet3_mtu:auto
vnet_default_interface:auto
vnet_default_mtu:1500
vnet_interfaces:none
wallclock:off
writebps:off
writeiops:off
@@ -0,0 +1,3 @@
GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
SPDX-License-Identifier: GPL-3.0-or-later
SPDX-FileCopyrightText: Ansible Project
@@ -0,0 +1,141 @@
CONFIG_VERSION:28
allow_chflags:0
allow_mlock:0
allow_mount:0
allow_mount_devfs:0
allow_mount_fusefs:0
allow_mount_nullfs:0
allow_mount_procfs:0
allow_mount_tmpfs:0
allow_mount_zfs:0
allow_quotas:0
allow_raw_sockets:0
allow_set_hostname:1
allow_socket_af:0
allow_sysvipc:0
allow_tun:0
allow_vmm:0
assign_localhost:0
available:readonly
basejail:1
boot:0
bpf:0
children_max:0
comment:none
compression:lz4
compressratio:readonly
coredumpsize:off
count:1
cpuset:off
cputime:off
datasize:off
dedup:off
defaultrouter:10.1.0.10
defaultrouter6:auto
depends:none
devfs_ruleset:4
dhcp:0
enforce_statfs:2
exec_clean:1
exec_created:/usr/bin/true
exec_fib:0
exec_jail_user:root
exec_poststart:/usr/bin/true
exec_poststop:/usr/bin/true
exec_prestart:/usr/bin/true
exec_prestop:/usr/bin/true
exec_start:/bin/sh /etc/rc
exec_stop:/bin/sh /etc/rc.shutdown
exec_system_jail_user:0
exec_system_user:root
exec_timeout:60
host_domainname:none
host_hostname:ansible-client
host_hostuuid:test_102
host_time:1
hostid:34333834-3734-5a43-3331-313342464631
hostid_strict_check:0
interfaces:vnet0:bridge0
ip4:new
ip4_addr:vnet0|10.1.0.102/24
ip4_saddrsel:1
ip6:new
ip6_addr:none
ip6_saddrsel:1
ip_hostname:0
jail_zfs:0
jail_zfs_dataset:iocage/jails/test_102/data
jail_zfs_mountpoint:none
last_started:none
localhost_ip:none
login_flags:-f root
mac_prefix:3e4a92
maxproc:off
memorylocked:off
memoryuse:off
min_dyn_devfs_ruleset:1000
mount_devfs:1
mount_fdescfs:1
mount_linprocfs:0
mount_procfs:0
mountpoint:readonly
msgqqueued:off
msgqsize:off
nat:0
nat_backend:ipfw
nat_forwards:none
nat_interface:none
nat_prefix:172.16
nmsgq:off
notes:vmm=iocage_01
nsem:off
nsemop:off
nshm:off
nthr:off
openfiles:off
origin:readonly
owner:root
pcpu:off
plugin_name:none
plugin_repository:none
priority:99
pseudoterminals:off
quota:none
readbps:off
readiops:off
release:13.4-RELEASE-p2
reservation:none
resolver:/etc/resolv.conf
rlimits:off
rtsold:0
securelevel:2
shmsize:off
stacksize:off
state:down
stop_timeout:30
swapuse:off
sync_state:none
sync_target:none
sync_tgt_zpool:none
sysvmsg:new
sysvsem:new
sysvshm:new
template:0
type:jail
used:readonly
vmemoryuse:off
vnet:1
vnet0_mac:none
vnet0_mtu:auto
vnet1_mac:none
vnet1_mtu:auto
vnet2_mac:none
vnet2_mtu:auto
vnet3_mac:none
vnet3_mtu:auto
vnet_default_interface:auto
vnet_default_mtu:1500
vnet_interfaces:none
wallclock:off
writebps:off
writeiops:off
@@ -0,0 +1,3 @@
GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
SPDX-License-Identifier: GPL-3.0-or-later
SPDX-FileCopyrightText: Ansible Project
@@ -0,0 +1,141 @@
CONFIG_VERSION:28
allow_chflags:0
allow_mlock:0
allow_mount:0
allow_mount_devfs:0
allow_mount_fusefs:0
allow_mount_nullfs:0
allow_mount_procfs:0
allow_mount_tmpfs:0
allow_mount_zfs:0
allow_quotas:0
allow_raw_sockets:0
allow_set_hostname:1
allow_socket_af:0
allow_sysvipc:0
allow_tun:0
allow_vmm:0
assign_localhost:0
available:readonly
basejail:1
boot:0
bpf:0
children_max:0
comment:none
compression:lz4
compressratio:readonly
coredumpsize:off
count:1
cpuset:off
cputime:off
datasize:off
dedup:off
defaultrouter:10.1.0.10
defaultrouter6:auto
depends:none
devfs_ruleset:4
dhcp:0
enforce_statfs:2
exec_clean:1
exec_created:/usr/bin/true
exec_fib:0
exec_jail_user:root
exec_poststart:/usr/bin/true
exec_poststop:/usr/bin/true
exec_prestart:/usr/bin/true
exec_prestop:/usr/bin/true
exec_start:/bin/sh /etc/rc
exec_stop:/bin/sh /etc/rc.shutdown
exec_system_jail_user:0
exec_system_user:root
exec_timeout:60
host_domainname:none
host_hostname:ansible-client
host_hostuuid:test_103
host_time:1
hostid:34333834-3734-5a43-3331-313342464631
hostid_strict_check:0
interfaces:vnet0:bridge0
ip4:new
ip4_addr:vnet0|10.1.0.103/24
ip4_saddrsel:1
ip6:new
ip6_addr:none
ip6_saddrsel:1
ip_hostname:0
jail_zfs:0
jail_zfs_dataset:iocage/jails/test_103/data
jail_zfs_mountpoint:none
last_started:none
localhost_ip:none
login_flags:-f root
mac_prefix:3e4a92
maxproc:off
memorylocked:off
memoryuse:off
min_dyn_devfs_ruleset:1000
mount_devfs:1
mount_fdescfs:1
mount_linprocfs:0
mount_procfs:0
mountpoint:readonly
msgqqueued:off
msgqsize:off
nat:0
nat_backend:ipfw
nat_forwards:none
nat_interface:none
nat_prefix:172.16
nmsgq:off
notes:vmm=iocage_01
nsem:off
nsemop:off
nshm:off
nthr:off
openfiles:off
origin:readonly
owner:root
pcpu:off
plugin_name:none
plugin_repository:none
priority:99
pseudoterminals:off
quota:none
readbps:off
readiops:off
release:13.4-RELEASE-p2
reservation:none
resolver:/etc/resolv.conf
rlimits:off
rtsold:0
securelevel:2
shmsize:off
stacksize:off
state:down
stop_timeout:30
swapuse:off
sync_state:none
sync_target:none
sync_tgt_zpool:none
sysvmsg:new
sysvsem:new
sysvshm:new
template:0
type:jail
used:readonly
vmemoryuse:off
vnet:1
vnet0_mac:none
vnet0_mtu:auto
vnet1_mac:none
vnet1_mtu:auto
vnet2_mac:none
vnet2_mtu:auto
vnet3_mac:none
vnet3_mtu:auto
vnet_default_interface:auto
vnet_default_mtu:1500
vnet_interfaces:none
wallclock:off
writebps:off
writeiops:off
@@ -0,0 +1,3 @@
GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
SPDX-License-Identifier: GPL-3.0-or-later
SPDX-FileCopyrightText: Ansible Project
@@ -0,0 +1,174 @@
{
"instances":{
"vlantest":{
"instances":{
"metadata":{
"config":{
"image.os":"ubuntu",
"image.release":"focal",
"image.version":"20.04",
"volatile.last_state.power":"RUNNING"
},
"devices":{
"eth0":{
"name":"eth0",
"network":"my-macvlan",
"type":"nic"
}
},
"profiles":[
"default"
],
"expanded_devices":{
"eth0":{
"name":"eth0",
"network":"my-macvlan",
"type":"nic"
}
},
"name":"vlantest",
"status":"Running",
"location":"Berlin"
}
},
"state":{
"metadata":{
"status":"Running",
"network":{
"eth0":{
"addresses":[
{
"family":"inet",
"address":"10.98.143.199",
"netmask":"24",
"scope":"global"
},
{
"family":"inet6",
"address":"fd42:bd00:7b11:2167:216:3eff:fe78:2ef3",
"netmask":"64",
"scope":"global"
},
{
"family":"inet6",
"address":"fe80::216:3eff:fed3:7af3",
"netmask":"64",
"scope":"link"
}
]
},
"lo":{
"addresses":[
{
"family":"inet",
"address":"127.0.0.1",
"netmask":"8",
"scope":"local"
},
{
"family":"inet6",
"address":"::1",
"netmask":"128",
"scope":"local"
}
]
}
}
}
}
}
},
"networks":{
"my-macvlan":{
"state":{
"metadata":{
"addresses":[
{
"family":"inet",
"address":"192.168.178.199",
"netmask":"24",
"scope":"global"
},
{
"family":"inet6",
"address":"fd42:bd00:7b11:2167:216:3eff:fe78:2ef3",
"netmask":"64",
"scope":"global"
},
{
"family":"inet6",
"address":"fe80::216:3eff:fed3:7af3",
"netmask":"64",
"scope":"link"
}
],
"vlan":{
"lower_device":"eno1",
"vid":666
}
}
}
},
"lo":{
"state":{
"metadata":{
"addresses":[
{
"family":"inet",
"address":"127.0.0.1",
"netmask":"8",
"scope":"local"
},
{
"family":"inet6",
"address":"::1",
"netmask":"128",
"scope":"local"
}
],
"vlan":null
}
}
},
"eno1":{
"state":{
"metadata":{
"addresses":[
{
"family":"inet",
"address":"192.168.178.126",
"netmask":"24",
"scope":"global"
},
{
"family":"inet6",
"address":"fe80::3c0b:7da9:3cc7:9e40",
"netmask":"64",
"scope":"link"
}
],
"vlan":null
}
}
},
"eno1.666":{
"state":{
"metadata":{
"addresses":[
{
"family":"inet6",
"address":"fe80::de4a:3eff:fe8d:f356",
"netmask":"64",
"scope":"link"
}
],
"vlan":{
"lower_device":"eno1",
"vid":666
}
}
}
}
}
}
@@ -0,0 +1,3 @@
GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
SPDX-License-Identifier: GPL-3.0-or-later
SPDX-FileCopyrightText: Ansible Project
@@ -0,0 +1,222 @@
[
{
"DEPLOY_ID": "bcfec9d9-c0d0-4523-b5e7-62993947e94c",
"ETIME": 0,
"GID": 105,
"GNAME": "SW",
"HISTORY_RECORDS": {},
"ID": 451,
"LAST_POLL": 0,
"LCM_STATE": 3,
"MONITORING": {},
"NAME": "terraform_demo_00",
"RESCHED": 0,
"STATE": 3,
"STIME": 1649886492,
"TEMPLATE": {
"NIC": [
{
"AR_ID": "0",
"BRIDGE": "mgmt0",
"BRIDGE_TYPE": "linux",
"CLUSTER_ID": "0",
"IP": "192.168.11.248",
"MAC": "02:00:c0:a8:2b:bb",
"MODEL": "virtio",
"NAME": "NIC0",
"NETWORK": "Infrastructure",
"NETWORK_ID": "0",
"NIC_ID": "0",
"SECURITY_GROUPS": "0,101",
"TARGET": "one-453-0",
"VLAN_ID": "12",
"VN_MAD": "802.1Q"
}
],
"NIC_DEFAULT": {
"MODEL": "virtio"
},
"TEMPLATE_ID": "28",
"TM_MAD_SYSTEM": "shared",
"VCPU": "4",
"VMID": "453"
},
"USER_TEMPLATE": {
"GUEST_OS": "linux",
"INPUTS_ORDER": "",
"LABELS": "foo,bench",
"LOGO": "images/logos/linux.png",
"MEMORY_UNIT_COST": "MB",
"SCHED_REQUIREMENTS": "ARCH=\"x86_64\"",
"TGROUP": "bench_clients"
}
},
{
"DEPLOY_ID": "25895435-5e3a-4d50-a025-e03a7a463abd",
"ETIME": 0,
"GID": 105,
"GNAME": "SW",
"HISTORY_RECORDS": {},
"ID": 451,
"LAST_POLL": 0,
"LCM_STATE": 3,
"MONITORING": {},
"NAME": "terraform_demo_01",
"RESCHED": 0,
"STATE": 3,
"STIME": 1649886492,
"TEMPLATE": {
"NIC": [
{
"AR_ID": "0",
"BRIDGE": "mgmt0",
"BRIDGE_TYPE": "linux",
"CLUSTER_ID": "0",
"IP": "192.168.11.241",
"MAC": "02:00:c0:a8:4b:bb",
"MODEL": "virtio",
"NAME": "NIC0",
"NETWORK": "Infrastructure",
"NETWORK_ID": "0",
"NIC_ID": "0",
"SECURITY_GROUPS": "0,101",
"TARGET": "one-451-0",
"VLAN_ID": "12",
"VN_MAD": "802.1Q"
}
],
"NIC_DEFAULT": {
"MODEL": "virtio"
},
"TEMPLATE_ID": "28",
"TM_MAD_SYSTEM": "shared",
"VCPU": "4",
"VMID": "451"
},
"USER_TEMPLATE": {
"GUEST_OS": "linux",
"INPUTS_ORDER": "",
"LABELS": "foo,bench",
"LOGO": "images/logos/linux.png",
"MEMORY_UNIT_COST": "MB",
"SCHED_REQUIREMENTS": "ARCH=\"x86_64\"",
"TESTATTR": "testvar",
"TGROUP": "bench_clients"
}
},
{
"DEPLOY_ID": "2b00c379-3601-45ee-acf5-e7b3ff2b7bca",
"ETIME": 0,
"GID": 105,
"GNAME": "SW",
"HISTORY_RECORDS": {},
"ID": 451,
"LAST_POLL": 0,
"LCM_STATE": 3,
"MONITORING": {},
"NAME": "terraform_demo_srv_00",
"RESCHED": 0,
"STATE": 3,
"STIME": 1649886492,
"TEMPLATE": {
"NIC": [
{
"AR_ID": "0",
"BRIDGE": "mgmt0",
"BRIDGE_TYPE": "linux",
"CLUSTER_ID": "0",
"IP": "192.168.11.247",
"MAC": "02:00:c0:a8:0b:cc",
"MODEL": "virtio",
"NAME": "NIC0",
"NETWORK": "Infrastructure",
"NETWORK_ID": "0",
"NIC_ID": "0",
"SECURITY_GROUPS": "0,101",
"TARGET": "one-452-0",
"VLAN_ID": "12",
"VN_MAD": "802.1Q"
}
],
"NIC_DEFAULT": {
"MODEL": "virtio"
},
"TEMPLATE_ID": "28",
"TM_MAD_SYSTEM": "shared",
"VCPU": "4",
"VMID": "452"
},
"USER_TEMPLATE": {
"GUEST_OS": "linux",
"INPUTS_ORDER": "",
"LABELS": "serv,bench",
"LOGO": "images/logos/linux.png",
"MEMORY_UNIT_COST": "MB",
"SCHED_REQUIREMENTS": "ARCH=\"x86_64\"",
"TGROUP": "bench_server"
}
},
{
"DEPLOY_ID": "97037f55-dd2c-4549-8d24-561a6569e870",
"ETIME": 0,
"GID": 105,
"GNAME": "SW",
"HISTORY_RECORDS": {},
"ID": 311,
"LAST_POLL": 0,
"LCM_STATE": 3,
"MONITORING": {},
"NAME": "bs-windows",
"RESCHED": 0,
"STATE": 3,
"STIME": 1648076254,
"TEMPLATE": {
"NIC": [
{
"AR_ID": "0",
"BRIDGE": "mgmt0",
"BRIDGE_TYPE": "linux",
"CLUSTER_ID": "0",
"IP": "192.168.11.209",
"MAC": "02:00:c0:a8:0b:dd",
"MODEL": "virtio",
"NAME": "NIC0",
"NETWORK": "Infrastructure",
"NETWORK_ID": "0",
"NETWORK_UNAME": "admin",
"NIC_ID": "0",
"SECURITY_GROUPS": "0,101",
"TARGET": "one-311-0",
"VLAN_ID": "12",
"VN_MAD": "802.1Q"
},
[
"TEMPLATE_ID",
"23"
],
[
"TM_MAD_SYSTEM",
"shared"
],
[
"VCPU",
"4"
],
[
"VMID",
"311"
]
]
},
"UID": 22,
"UNAME": "bsanders",
"USER_TEMPLATE": {
"GUEST_OS": "windows",
"INPUTS_ORDER": "",
"LABELS": "serv",
"HYPERVISOR": "kvm",
"SCHED_REQUIREMENTS": "ARCH=\"x86_64\"",
"SET_HOSTNAME": "windows"
}
}
]
@@ -0,0 +1,3 @@
GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
SPDX-License-Identifier: GPL-3.0-or-later
SPDX-FileCopyrightText: Ansible Project
@@ -0,0 +1,133 @@
# Copyright 2020 Orion Poplawski <orion@nwra.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 http.client
import pytest
from ansible.inventory.data import InventoryData
from ansible.parsing.dataloader import DataLoader
from ansible.plugins.loader import inventory_loader
from ansible_collections.community.general.plugins.inventory.cobbler import (
InventoryModule,
TimeoutSafeTransport,
TimeoutTransport,
)
@pytest.fixture(scope="module")
def inventory():
return InventoryModule()
PROFILES = [{"name": "web", "parent": None}]
SYSTEMS = [
{
"name": "host1",
"hostname": "host1",
"profile": "web",
"interfaces": {},
"mgmt_classes": [],
"owners": [],
"status": "",
}
]
@pytest.fixture
def server(mocker):
server = mocker.patch("ansible_collections.community.general.plugins.inventory.cobbler.xmlrpc_client.Server")
server.return_value.get_profiles.return_value = PROFILES
server.return_value.get_systems.return_value = SYSTEMS
return server.return_value
def _parse(tmp_path, config):
path = tmp_path / "test.cobbler.yml"
path.write_text(config)
plugin = inventory_loader.get("community.general.cobbler")
inventory = InventoryData()
plugin.parse(inventory, DataLoader(), str(path))
return plugin, inventory
def test_parse_without_cache(tmp_path, server):
plugin, inventory = _parse(tmp_path, "plugin: community.general.cobbler\nurl: http://cobbler/cobbler_api\n")
assert plugin.cache_key not in getattr(plugin, "_cache", {})
assert "host1" in inventory.hosts
assert "cobbler_web" in inventory.groups
@pytest.mark.parametrize("method", ["get_profiles", "get_systems"])
def test_parse_without_cache_connection_error(tmp_path, server, method):
getattr(server, method).side_effect = ConnectionRefusedError(111, "Connection refused")
with pytest.raises(ConnectionRefusedError):
_parse(tmp_path, "plugin: community.general.cobbler\nurl: http://cobbler/cobbler_api\n")
def test_parse_with_cache(tmp_path, server):
config = (
"plugin: community.general.cobbler\n"
"url: http://cobbler/cobbler_api\n"
"cache: true\n"
"cache_plugin: ansible.builtin.jsonfile\n"
f"cache_connection: {tmp_path / 'cache'}\n"
)
plugin, inventory = _parse(tmp_path, config)
plugin.update_cache_if_changed()
assert "host1" in inventory.hosts
server.reset_mock()
plugin, inventory = _parse(tmp_path, config)
server.get_profiles.assert_not_called()
server.get_systems.assert_not_called()
assert "host1" in inventory.hosts
def test_verify_file(tmp_path, inventory):
file = tmp_path / "foobar.cobbler.yml"
file.touch()
assert inventory.verify_file(str(file)) is True
def test_verify_file_bad_config(inventory):
assert inventory.verify_file("foobar.cobbler.yml") is False
def _server_call(mocker, url, connection_timeout):
"""Run parse() and return the arguments the XML-RPC server proxy was created with."""
options = {"url": url, "connection_timeout": connection_timeout, "cache_plugin": "memory"}
plugin = InventoryModule()
# Ansible populates every declared option, so an unset connection_timeout is present as None.
plugin._options = options
mocker.patch.object(plugin, "_read_config_data")
mocker.patch.object(plugin, "get_option", side_effect=options.get)
mocker.patch.object(plugin, "_get_profiles", return_value=[])
mocker.patch.object(plugin, "_get_systems", return_value=[])
server = mocker.patch("ansible_collections.community.general.plugins.inventory.cobbler.xmlrpc_client.Server")
plugin.parse(InventoryData(), None, "dummy.cobbler.yml")
return server.call_args
@pytest.mark.parametrize(
"url, transport_cls, connection_cls, port",
[
("http://cobbler/cobbler_api", TimeoutTransport, http.client.HTTPConnection, 80),
("https://cobbler/cobbler_api", TimeoutSafeTransport, http.client.HTTPSConnection, 443),
("HTTPS://cobbler/cobbler_api", TimeoutSafeTransport, http.client.HTTPSConnection, 443),
],
)
def test_parse_connection_timeout_transport(mocker, url, transport_cls, connection_cls, port):
transport = _server_call(mocker, url, 30).kwargs["transport"]
assert isinstance(transport, transport_cls)
conn = transport.make_connection("cobbler")
assert isinstance(conn, connection_cls)
assert conn.port == port
assert conn.timeout == 30
def test_parse_without_connection_timeout_uses_default_transport(mocker):
assert "transport" not in _server_call(mocker, "http://cobbler/cobbler_api", None).kwargs
@@ -0,0 +1,150 @@
# Copyright (c) 2021, Cliff Hults <cliff.hlts@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
#
# The API responses used in these tests were recorded from PVE version 6.2.
from __future__ import annotations
import pytest
from ansible.inventory.data import InventoryData
from ansible_collections.community.general.plugins.inventory.icinga2 import InventoryModule
@pytest.fixture(scope="module")
def inventory():
r = InventoryModule()
r.inventory = InventoryData()
return r
def test_verify_file_bad_config(inventory):
assert inventory.verify_file("foobar.icinga2.yml") is False
def check_api():
return True
# NOTE: when updating/adding replies to this function,
# be sure to only add only the _contents_ of the 'data' dict in the API reply
def query_hosts(hosts=None, attrs=None, joins=None, host_filter=None):
# _get_hosts - list of dicts
json_host_data = [
{
"attrs": {
"address": "test-host1.home.local",
"groups": ["home_servers", "servers_dell"],
"display_name": "Test Host 1",
"state": 0.0,
"state_type": 1.0,
},
"joins": {},
"meta": {},
"name": "test-host1",
"type": "Host",
},
{
"attrs": {
"address": "test-host2.home.local",
"display_name": "Test Host 2",
"groups": ["home_servers", "servers_hp"],
"state": 1.0,
"state_type": 1.0,
},
"joins": {},
"meta": {},
"name": "test-host2",
"type": "Host",
},
{
"attrs": {
"address": "",
"display_name": "Test Host 3",
"groups": ["not_home_servers", "servers_hp"],
"state": 1.0,
"state_type": 1.0,
},
"joins": {},
"meta": {},
"name": "test-host3.example.com",
"type": "Host",
},
]
return json_host_data
def get_option(option):
if option == "groups":
return {}
elif option == "keyed_groups":
return []
elif option == "compose":
return {}
elif option == "strict":
return False
elif option == "group_by_hostgroups":
return True
else:
return None
def test_populate(inventory, mocker):
# module settings
inventory.icinga2_user = "ansible"
inventory.icinga2_password = "password"
inventory.icinga2_url = "https://localhost:5665/v1"
inventory.inventory_attr = "address"
inventory.group_by_hostgroups = True
# bypass authentication and API fetch calls
inventory._check_api = mocker.MagicMock(side_effect=check_api)
inventory._query_hosts = mocker.MagicMock(side_effect=query_hosts)
inventory.get_option = mocker.MagicMock(side_effect=get_option)
inventory._populate()
# get different hosts
host1_info = inventory.inventory.get_host("test-host1.home.local")
print(host1_info)
host2_info = inventory.inventory.get_host("test-host2.home.local")
print(host2_info)
host3_info = inventory.inventory.get_host("test-host3.example.com")
assert inventory.inventory.get_host("test-host3.example.com") is not None
print(host3_info)
# check if host in the home_servers group
assert "home_servers" in inventory.inventory.groups
group1_data = inventory.inventory.groups["home_servers"]
group1_test_data = [host1_info, host2_info]
print(group1_data.hosts)
print(group1_test_data)
assert group1_data.hosts == group1_test_data
# Test servers_hp group
group2_data = inventory.inventory.groups["servers_hp"]
group2_test_data = [host2_info, host3_info]
print(group2_data.hosts)
print(group2_test_data)
assert group2_data.hosts == group2_test_data
# check if host state rules apply properly
assert host1_info.get_vars()["state"] == "on"
assert host1_info.get_vars()["display_name"] == "Test Host 1"
assert host2_info.get_vars()["state"] == "off"
assert host3_info.get_vars().get("ansible_host") is None
# Confirm attribute options switcher
inventory.inventory_attr = "name"
inventory._populate()
assert inventory.inventory.get_host("test-host3.example.com") is not None
host2_info = inventory.inventory.get_host("test-host2")
assert host2_info is not None
assert host2_info.get_vars().get("ansible_host") == "test-host2.home.local"
# Confirm attribute options switcher
inventory.inventory_attr = "display_name"
inventory._populate()
assert inventory.inventory.get_host("Test Host 3") is not None
host2_info = inventory.inventory.get_host("Test Host 2")
assert host2_info is not None
assert host2_info.get_vars().get("ansible_host") == "test-host2.home.local"
@@ -0,0 +1,183 @@
# Copyright (c) 2025 Stéphane Graber <stgraber@stgraber.org>
# 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 pytest
from ansible.inventory.data import InventoryData
from ansible.parsing.dataloader import DataLoader
from ansible.template import Templar
from ansible_collections.community.general.plugins.inventory.incus import (
InventoryModule,
)
@pytest.fixture(scope="module")
def inventory():
plugin = InventoryModule()
plugin.inventory = InventoryData()
plugin.templar = Templar(loader=DataLoader())
return plugin
def test_verify_file_yml(tmp_path, inventory):
file = tmp_path / "foobar.incus.yml"
file.touch()
assert inventory.verify_file(str(file)) is True
def test_verify_file_yaml(tmp_path, inventory):
file = tmp_path / "foobar.incus.yaml"
file.touch()
assert inventory.verify_file(str(file)) is True
def test_verify_file_bad_config_yml(inventory):
assert inventory.verify_file("foobar.incus.yml") is False
def test_verify_file_bad_config_yaml(inventory):
assert inventory.verify_file("foobar.incus.yaml") is False
def test_verify_file_bad_config(inventory):
assert inventory.verify_file("foobar.wrongcloud.yml") is False
def _build_get_option(options):
def _get_option(option):
return options.get(option, False)
return _get_option
def _make_host(name):
entry = {}
entry["name"] = name
for prop in (
"architecture",
"config",
"description",
"devices",
"ephemeral",
"expanded_config",
"expanded_devices",
"location",
"profiles",
"status",
"type",
):
entry[prop] = ""
return entry
def run_incus(*args):
if args == ("project", "list", "r1:"):
return [{"name": "default"}]
if args == ("project", "list", "r2:"):
return [{"name": "foo"}]
if args == ("list", "r1:", "--project", "default", "status=running"):
return [_make_host("c1")]
if args == ("list", "r2:", "--project", "foo", "status=running"):
return [_make_host("c2")]
if args == ("list", "r3:", "--project", "proj1", "status=running"):
return [_make_host("c3")]
if args == ("list", "r3:", "--project", "proj2", "status=running"):
return [_make_host("c4"), _make_host("c5")]
return []
def test_build_inventory(inventory, mocker):
get_option = _build_get_option(
{
"default_groups": True,
"remotes": ["r1", "r2", "r3:proj1", "r3:proj2"],
"filters": ["status=running"],
"host_fqdn": True,
"host_domain": "example.net",
},
)
inventory.get_option = mocker.MagicMock(side_effect=get_option)
inventory._run_incus = mocker.MagicMock(side_effect=run_incus)
inventory.populate()
c1 = inventory.inventory.get_host("c1.default.r1.example.net")
assert c1
assert "ansible_incus_status" in c1.get_vars()
c2 = inventory.inventory.get_host("c2.foo.r2.example.net")
assert c2
assert "ansible_incus_status" in c2.get_vars()
c3 = inventory.inventory.get_host("c3.proj1.r3.example.net")
assert c3
assert "ansible_incus_status" in c3.get_vars()
c4 = inventory.inventory.get_host("c4.proj2.r3.example.net")
assert c4
assert "ansible_incus_status" in c4.get_vars()
c5 = inventory.inventory.get_host("c5.proj2.r3.example.net")
assert c5
assert "ansible_incus_status" in c5.get_vars()
assert len(inventory.inventory.groups["all"].hosts) == 5
assert len(inventory.inventory.groups["incus"].child_groups) == 3
assert len(inventory.inventory.groups["incus_r1"].child_groups) == 1
assert len(inventory.inventory.groups["incus_r2"].child_groups) == 1
assert len(inventory.inventory.groups["incus_r3"].child_groups) == 2
assert len(inventory.inventory.groups["incus_r3_proj1"].hosts) == 1
assert len(inventory.inventory.groups["incus_r3_proj2"].hosts) == 2
def test_build_inventory_fqdn_from_host_domain(inventory, mocker):
get_option = _build_get_option(
{
"default_groups": True,
"remotes": ["r1", "r2", "r3:proj1", "r3:proj2"],
"filters": ["status=running"],
"host_fqdn": False,
"host_domain": "example.net",
},
)
inventory.get_option = mocker.MagicMock(side_effect=get_option)
inventory._run_incus = mocker.MagicMock(side_effect=run_incus)
inventory.populate()
c1 = inventory.inventory.get_host("c1.example.net")
assert c1
assert "ansible_incus_status" in c1.get_vars()
c2 = inventory.inventory.get_host("c2.example.net")
assert c2
assert "ansible_incus_status" in c2.get_vars()
c3 = inventory.inventory.get_host("c3.example.net")
assert c3
assert "ansible_incus_status" in c3.get_vars()
c4 = inventory.inventory.get_host("c4.example.net")
assert c4
assert "ansible_incus_status" in c4.get_vars()
c5 = inventory.inventory.get_host("c5.example.net")
assert c5
assert "ansible_incus_status" in c5.get_vars()
assert len(inventory.inventory.groups["all"].hosts) == 5
assert len(inventory.inventory.groups["incus"].child_groups) == 3
assert len(inventory.inventory.groups["incus_r1"].child_groups) == 1
assert len(inventory.inventory.groups["incus_r2"].child_groups) == 1
assert len(inventory.inventory.groups["incus_r3"].child_groups) == 2
assert len(inventory.inventory.groups["incus_r3_proj1"].hosts) == 1
assert len(inventory.inventory.groups["incus_r3_proj2"].hosts) == 2
@@ -0,0 +1,132 @@
# Copyright (c) 2024 Vladimir Botka <vbotka@gmail.com>
# 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 pytest
import yaml
from ansible.inventory.data import InventoryData
from ansible.template import Templar
from ansible_collections.community.internal_test_tools.tests.unit.utils.trust import make_trusted
from ansible_collections.community.general.plugins.inventory.iocage import InventoryModule
@pytest.fixture
def inventory():
inv = InventoryModule()
inv.inventory = InventoryData()
inv.templar = Templar(None)
inv.jails = load_txt_data("tests/unit/plugins/inventory/fixtures/iocage/iocage_jails.txt")
inv.js_ok = load_yml_data("tests/unit/plugins/inventory/fixtures/iocage/iocage_jails.yml")
inv.jails_dhcp = load_txt_data("tests/unit/plugins/inventory/fixtures/iocage/iocage_jails_dhcp.txt")
inv.js_dhcp_ok = load_yml_data("tests/unit/plugins/inventory/fixtures/iocage/iocage_jails_dhcp.yml")
inv.jails_dhcp_nr = load_txt_data("tests/unit/plugins/inventory/fixtures/iocage/iocage_jails_dhcp_not_running.txt")
inv.js_dhcp_nr_ok = load_yml_data("tests/unit/plugins/inventory/fixtures/iocage/iocage_jails_dhcp_not_running.yml")
prpts_101 = load_txt_data("tests/unit/plugins/inventory/fixtures/iocage/iocage_properties_test_101.txt")
prpts_102 = load_txt_data("tests/unit/plugins/inventory/fixtures/iocage/iocage_properties_test_102.txt")
prpts_103 = load_txt_data("tests/unit/plugins/inventory/fixtures/iocage/iocage_properties_test_103.txt")
inv.prpts = {"test_101": prpts_101, "test_102": prpts_102, "test_103": prpts_103}
inv.ps_ok = load_yml_data("tests/unit/plugins/inventory/fixtures/iocage/iocage_properties.yml")
inv.ok = load_yml_data("tests/unit/plugins/inventory/fixtures/iocage/iocage_inventory.yml")
return inv
def load_txt_data(path):
with open(path) as f:
s = f.read()
return s
def load_yml_data(path):
with open(path) as f:
d = yaml.safe_load(f)
return d
def get_option(option):
groups = {}
groups["test"] = make_trusted("inventory_hostname.startswith('test')")
if option == "groups":
return groups
elif option == "keyed_groups":
return []
elif option == "compose":
return {}
elif option == "strict":
return False
else:
return None
def test_verify_file_bad_config(inventory):
assert inventory.verify_file("foobar.iocage.yml") is False
def test_verify_file(tmp_path, inventory):
file = tmp_path / "foobar.iocage.yml"
file.touch()
assert inventory.verify_file(str(file))
def test_get_jails(inventory):
# jails
results = {"_meta": {"hostvars": {}}}
inventory.get_jails(inventory.jails, results)
assert results == inventory.js_ok
# jails_dhcp
results = {"_meta": {"hostvars": {}}}
inventory.get_jails(inventory.jails_dhcp, results)
assert results == inventory.js_dhcp_ok
# jails_dhcp_not_running
results = {"_meta": {"hostvars": {}}}
inventory.get_jails(inventory.jails_dhcp_nr, results)
assert results == inventory.js_dhcp_nr_ok
def test_get_properties(inventory):
results = {"_meta": {"hostvars": {}}}
inventory.get_jails(inventory.jails, results)
for hostname in results["_meta"]["hostvars"]:
inventory.get_properties(inventory.prpts[hostname], results, hostname)
assert results == inventory.ps_ok
def test_populate(inventory, mocker):
results = {"_meta": {"hostvars": {}}}
inventory.get_jails(inventory.jails, results)
for hostname in results["_meta"]["hostvars"]:
inventory.get_properties(inventory.prpts[hostname], results, hostname)
inventory.get_option = mocker.MagicMock(side_effect=get_option)
inventory.populate(results)
# test
hosts = ("test_101", "test_102", "test_103")
vars = (
"iocage_basejail",
"iocage_boot",
"iocage_ip4",
"iocage_ip6",
"iocage_properties",
"iocage_release",
"iocage_state",
"iocage_template",
"iocage_type",
)
# test host_vars
for host in hosts:
h = inventory.inventory.get_host(host)
for var in vars:
assert inventory.ok["all"]["children"]["test"]["hosts"][host][var] == h.get_vars()[var]
# test groups
test_101_info = inventory.inventory.get_host("test_101")
test_102_info = inventory.inventory.get_host("test_102")
test_103_info = inventory.inventory.get_host("test_103")
g = inventory.inventory.groups["test"]
assert g.hosts == [test_101_info, test_102_info, test_103_info]
@@ -0,0 +1,54 @@
# Copyright 2018 Luke Murphy <lukewm@riseup.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
import pytest
linode_apiv4 = pytest.importorskip("linode_api4")
from ansible.errors import AnsibleError
from ansible.parsing.dataloader import DataLoader
from ansible.template import Templar
from ansible_collections.community.general.plugins.inventory.linode import InventoryModule
@pytest.fixture(scope="module")
def inventory():
plugin = InventoryModule()
plugin.templar = Templar(loader=DataLoader())
return plugin
def test_missing_access_token_lookup(inventory):
loader = DataLoader()
inventory._options = {"access_token": None}
with pytest.raises(AnsibleError) as error_message:
inventory._build_client(loader)
assert "Could not retrieve Linode access token" in error_message
def test_verify_file_yml(tmp_path, inventory):
file = tmp_path / "foobar.linode.yml"
file.touch()
assert inventory.verify_file(str(file)) is True
def test_verify_file_yaml(tmp_path, inventory):
file = tmp_path / "foobar.linode.yaml"
file.touch()
assert inventory.verify_file(str(file)) is True
def test_verify_file_bad_config_yml(inventory):
assert inventory.verify_file("foobar.linode.yml") is False
def test_verify_file_bad_config_yaml(inventory):
assert inventory.verify_file("foobar.linode.yaml") is False
def test_verify_file_bad_config(inventory):
assert inventory.verify_file("foobar.wrongcloud.yml") is False
@@ -0,0 +1,122 @@
# Copyright (c) 2021, Frank Dornheim <dornheim@posteo.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
import pytest
from ansible.inventory.data import InventoryData
from ansible_collections.community.general.plugins.inventory.lxd import InventoryModule
HOST_COMPARATIVE_DATA = {
"ansible_connection": "ssh",
"ansible_host": "10.98.143.199",
"ansible_lxd_os": "ubuntu",
"ansible_lxd_release": "focal",
"ansible_lxd_profile": ["default"],
"ansible_lxd_state": "running",
"ansible_lxd_location": "Berlin",
"ansible_lxd_vlan_ids": {"my-macvlan": 666},
"inventory_hostname": "vlantest",
"inventory_hostname_short": "vlantest",
}
GROUP_COMPARATIVE_DATA = {
"all": [],
"ungrouped": [],
"testpattern": ["vlantest"],
"vlan666": ["vlantest"],
"locationBerlin": ["vlantest"],
"osUbuntu": ["vlantest"],
"releaseFocal": ["vlantest"],
"releaseBionic": [],
"profileDefault": ["vlantest"],
"profileX11": [],
"netRangeIPv4": ["vlantest"],
"netRangeIPv6": ["vlantest"],
}
GROUP_Config = {
"testpattern": {"type": "pattern", "attribute": "test"},
"vlan666": {"type": "vlanid", "attribute": 666},
"locationBerlin": {"type": "location", "attribute": "Berlin"},
"osUbuntu": {"type": "os", "attribute": "ubuntu"},
"releaseFocal": {"type": "release", "attribute": "focal"},
"releaseBionic": {"type": "release", "attribute": "bionic"},
"profileDefault": {"type": "profile", "attribute": "default"},
"profileX11": {"type": "profile", "attribute": "x11"},
"netRangeIPv4": {"type": "network_range", "attribute": "10.98.143.0/24"},
"netRangeIPv6": {"type": "network_range", "attribute": "fd42:bd00:7b11:2167:216:3eff::/96"},
}
@pytest.fixture
def inventory():
inv = InventoryModule()
inv.inventory = InventoryData()
# Test Values
inv.data = inv.load_json_data("tests/unit/plugins/inventory/fixtures/lxd_inventory.atd") # Load Test Data
inv.groupby = GROUP_Config
inv.prefered_instance_network_interface = "eth"
inv.prefered_instance_network_family = "inet"
inv.filter = "running"
inv.dump_data = False
inv.type_filter = "both"
return inv
def test_verify_file(tmp_path, inventory):
file = tmp_path / "foobar.lxd.yml"
file.touch()
assert inventory.verify_file(str(file)) is True
def test_verify_file_bad_config(inventory):
assert inventory.verify_file("foobar.lxd.yml") is False
def test_build_inventory_hosts(inventory):
"""Load example data and start the inventoryto test the host generation.
After the inventory plugin has run with the test data, the result of the host is checked."""
inventory._populate()
generated_data = inventory.inventory.get_host("vlantest").get_vars()
eq = True
for key, value in HOST_COMPARATIVE_DATA.items():
if generated_data[key] != value:
eq = False
assert eq
def test_build_inventory_groups(inventory):
"""Load example data and start the inventory to test the group generation.
After the inventory plugin has run with the test data, the result of the host is checked."""
inventory._populate()
generated_data = inventory.inventory.get_groups_dict()
eq = True
for key, value in GROUP_COMPARATIVE_DATA.items():
if generated_data[key] != value:
eq = False
assert eq
def test_build_inventory_groups_with_no_groupselection(inventory):
"""Load example data and start the inventory to test the group generation with groupby is none.
After the inventory plugin has run with the test data, the result of the host is checked."""
inventory.groupby = None
inventory._populate()
generated_data = inventory.inventory.get_groups_dict()
group_comparative_data = {"all": [], "ungrouped": []}
eq = True
print(f"data: {generated_data}")
for key, value in group_comparative_data.items():
if generated_data[key] != value:
eq = False
assert eq
@@ -0,0 +1,590 @@
# Copyright (c) 2020, FELDSAM s.r.o. - FeldHost™ <support@feldhost.cz>
# 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
#
# The API responses used in these tests were recorded from OpenNebula version 5.10.
from __future__ import annotations
import json
import os
from collections import OrderedDict
import pytest
from ansible import constants as C
from ansible.inventory.data import InventoryData
from ansible.inventory.manager import InventoryManager
from ansible.module_utils.common.text.converters import to_native
from ansible_collections.community.internal_test_tools.tests.unit.mock.loader import DictDataLoader
from ansible_collections.community.internal_test_tools.tests.unit.mock.path import mock_unfrackpath_noop
from ansible_collections.community.internal_test_tools.tests.unit.utils.trust import (
make_trusted,
)
from ansible_collections.community.general.plugins.inventory.opennebula import InventoryModule
original_exists = os.path.exists
original_access = os.access
def exists_mock(path, exists=True):
def exists(f):
if to_native(f) == path:
return exists
return original_exists(f)
return exists
def access_mock(path, can_access=True):
def access(f, m, *args, **kwargs):
if to_native(f) == path:
return can_access
return original_access(f, m, *args, **kwargs) # pragma: no cover
return access
class HistoryEntry:
def __init__(self):
self.SEQ = "384"
self.HOSTNAME = "sam-691-sam"
self.HID = "10"
self.CID = "0"
self.DS_ID = "100"
self.VM_MAD = "kvm"
self.TM_MAD = "3par"
self.ACTION = "0"
class HistoryRecords:
def __init__(self):
self.HISTORY = [HistoryEntry()]
@pytest.fixture
def inventory():
r = InventoryModule()
r.inventory = InventoryData()
return r
def test_verify_file(tmp_path, inventory):
file = tmp_path / "foobar.opennebula.yml"
file.touch()
assert inventory.verify_file(str(file)) is True
def test_verify_file_bad_config(inventory):
assert inventory.verify_file("foobar.opennebula.yml") is False
def get_vm_pool_json():
with open("tests/unit/plugins/inventory/fixtures/opennebula_inventory.json") as json_file:
jsondata = json.load(json_file)
data = type("pyone.bindings.VM_POOLSub", (object,), {"VM": []})()
for fake_server in jsondata:
data.VM.append(type("pyone.bindings.VMType90Sub", (object,), fake_server)())
return data
def get_vm_pool():
data = type("pyone.bindings.VM_POOLSub", (object,), {"VM": []})()
vm = type(
"pyone.bindings.VMType90Sub",
(object,),
{
"DEPLOY_ID": "one-7157",
"ETIME": 0,
"GID": 132,
"GNAME": "CSApparelVDC",
"UNAME": "sam-admin",
"HISTORY_RECORDS": HistoryRecords(),
"ID": 7157,
"LAST_POLL": 1632762935,
"LCM_STATE": 3,
"MONITORING": {},
"NAME": "sam-691-sam",
"RESCHED": 0,
"SNAPSHOTS": [],
"STATE": 3,
"STIME": 1632755245,
"TEMPLATE": OrderedDict(
{
"NIC": OrderedDict(
{
"AR_ID": "0",
"BRIDGE": "onebr80",
"BRIDGE_TYPE": "linux",
"CLUSTER_ID": "0",
"IP": "172.22.4.187",
"MAC": "02:00:ac:16:04:bb",
"MTU": "8192",
"NAME": "NIC0",
"NETWORK": "Private Net CSApparel",
"NETWORK_ID": "80",
"NETWORK_UNAME": "CSApparelVDC-admin",
"NIC_ID": "0",
"PHYDEV": "team0",
"SECURITY_GROUPS": "0",
"TARGET": "one-7157-0",
"VLAN_ID": "480",
"VN_MAD": "802.1Q",
}
)
}
),
"USER_TEMPLATE": OrderedDict(
{
"HYPERVISOR": "kvm",
"INPUTS_ORDER": "",
"LOGO": "images/logos/centos.png",
"MEMORY_UNIT_COST": "MB",
"SCHED_REQUIREMENTS": 'CLUSTER_ID="0"',
}
),
},
)()
data.VM.append(vm)
vm = type(
"pyone.bindings.VMType90Sub",
(object,),
{
"DEPLOY_ID": "one-327",
"ETIME": 0,
"GID": 0,
"GNAME": "oneadmin",
"UNAME": "oneadmin",
"HISTORY_RECORDS": [],
"ID": 327,
"LAST_POLL": 1632763543,
"LCM_STATE": 3,
"MONITORING": {},
"NAME": "zabbix-327",
"RESCHED": 0,
"SNAPSHOTS": [],
"STATE": 3,
"STIME": 1575410106,
"TEMPLATE": OrderedDict(
{
"NIC": [
OrderedDict(
{
"AR_ID": "0",
"BRIDGE": "onerb.103",
"BRIDGE_TYPE": "linux",
"IP": "185.165.1.1",
"IP6_GLOBAL": "2000:a001::b9ff:feae:aa0d",
"IP6_LINK": "fe80::b9ff:feae:aa0d",
"MAC": "02:00:b9:ae:aa:0d",
"NAME": "NIC0",
"NETWORK": "Public",
"NETWORK_ID": "7",
"NIC_ID": "0",
"PHYDEV": "team0",
"SECURITY_GROUPS": "0",
"TARGET": "one-327-0",
"VLAN_ID": "100",
"VN_MAD": "802.1Q",
}
),
OrderedDict(
{
"AR_ID": "0",
"BRIDGE": "br0",
"BRIDGE_TYPE": "linux",
"CLUSTER_ID": "0",
"IP": "192.168.1.1",
"MAC": "02:00:c0:a8:3b:01",
"NAME": "NIC1",
"NETWORK": "Management",
"NETWORK_ID": "11",
"NIC_ID": "1",
"SECURITY_GROUPS": "0",
"TARGET": "one-327-1",
"VN_MAD": "bridge",
}
),
]
}
),
"USER_TEMPLATE": OrderedDict(
{
"HYPERVISOR": "kvm",
"INPUTS_ORDER": "",
"LABELS": "Oracle Linux",
"LOGO": "images/logos/centos.png",
"MEMORY_UNIT_COST": "MB",
"SAVED_TEMPLATE_ID": "29",
}
),
},
)()
data.VM.append(vm)
vm = type(
"pyone.bindings.VMType90Sub",
(object,),
{
"DEPLOY_ID": "one-107",
"ETIME": 0,
"GID": 0,
"GNAME": "oneadmin",
"UNAME": "gitlab-admin",
"HISTORY_RECORDS": [],
"ID": 107,
"LAST_POLL": 1632764186,
"LCM_STATE": 3,
"MONITORING": {},
"NAME": "gitlab-107",
"RESCHED": 0,
"SNAPSHOTS": [],
"STATE": 3,
"STIME": 1572485522,
"TEMPLATE": OrderedDict(
{
"NIC": OrderedDict(
{
"AR_ID": "0",
"BRIDGE": "onerb.103",
"BRIDGE_TYPE": "linux",
"IP": "185.165.1.3",
"IP6_GLOBAL": "2000:a001::b9ff:feae:aa03",
"IP6_LINK": "fe80::b9ff:feae:aa03",
"MAC": "02:00:b9:ae:aa:03",
"NAME": "NIC0",
"NETWORK": "Public",
"NETWORK_ID": "7",
"NIC_ID": "0",
"PHYDEV": "team0",
"SECURITY_GROUPS": "0",
"TARGET": "one-107-0",
"VLAN_ID": "100",
"VN_MAD": "802.1Q",
}
)
}
),
"USER_TEMPLATE": OrderedDict(
{
"HYPERVISOR": "kvm",
"INPUTS_ORDER": "",
"LABELS": "Gitlab,Centos",
"LOGO": "images/logos/centos.png",
"MEMORY_UNIT_COST": "MB",
"SCHED_REQUIREMENTS": 'ID="0" | ID="1" | ID="2"',
"SSH_PORT": "8822",
}
),
},
)()
data.VM.append(vm)
return data
options_base_test = {
"api_url": "https://opennebula:2633/RPC2",
"api_username": "username",
"api_password": "password",
"api_authfile": "~/.one/one_auth",
"hostname": "v4_first_ip",
"prefer_existing_ansible_host": False,
"set_name_variable": True,
"group_by_labels": True,
"filter_by_label": None,
"filters": None,
}
# given a dictionary `opts_dict`, return a function that behaves like ansible's inventory get_options
def mk_get_options(opts_dict):
def inner(opt):
return opts_dict.get(opt, False)
return inner
def test_get_connection_info(inventory, mocker):
inventory.get_option = mocker.MagicMock(side_effect=mk_get_options(options_base_test))
auth = inventory._get_connection_info()
assert auth.username and auth.password
def test_populate_constructable_templating(mocker):
inventory_filename = "/fake/opennebula.yml"
mocker.patch.object(InventoryModule, "_get_vm_pool", side_effect=get_vm_pool_json)
mocker.patch("ansible_collections.community.general.plugins.inventory.opennebula.HAS_PYONE", True)
mocker.patch("ansible.inventory.manager.unfrackpath", mock_unfrackpath_noop)
mocker.patch("os.path.exists", exists_mock(inventory_filename))
mocker.patch("os.access", access_mock(inventory_filename))
# the templating engine is needed for the constructable groups/vars
# so give that some fake data and instantiate it.
C.INVENTORY_ENABLED = ["community.general.opennebula"]
inventory_file = {
inventory_filename: r"""
---
plugin: community.general.opennebula
api_url: https://opennebula:2633/RPC2
api_username: username
api_password: password
api_authfile: '~/.one/one_auth'
hostname: v4_first_ip
group_by_labels: true
compose:
is_linux: GUEST_OS == 'linux'
filter_by_label: bench
groups:
benchmark_clients: TGROUP.endswith('clients')
lin: is_linux == true
keyed_groups:
- key: TGROUP
prefix: tgroup
"""
}
im = InventoryManager(loader=DictDataLoader(inventory_file), sources=inventory_filename)
# note the vm_pool (and json data file) has four hosts,
# but the options above asks ansible to filter one out
assert len(get_vm_pool_json().VM) == 4
assert {vm.NAME for vm in get_vm_pool_json().VM} == {
"terraform_demo_00",
"terraform_demo_01",
"terraform_demo_srv_00",
"bs-windows",
}
assert set(im._inventory.hosts) == {"terraform_demo_00", "terraform_demo_01", "terraform_demo_srv_00"}
host_demo00 = im._inventory.get_host("terraform_demo_00")
host_demo01 = im._inventory.get_host("terraform_demo_01")
host_demosrv = im._inventory.get_host("terraform_demo_srv_00")
assert "benchmark_clients" in im._inventory.groups
assert "lin" in im._inventory.groups
assert im._inventory.groups["benchmark_clients"].hosts == [host_demo00, host_demo01]
assert im._inventory.groups["lin"].hosts == [host_demo00, host_demo01, host_demosrv]
# test group by label:
assert "bench" in im._inventory.groups
assert "foo" in im._inventory.groups
assert im._inventory.groups["bench"].hosts == [host_demo00, host_demo01, host_demosrv]
assert im._inventory.groups["serv"].hosts == [host_demosrv]
assert im._inventory.groups["foo"].hosts == [host_demo00, host_demo01]
# test `compose` transforms GUEST_OS=Linux to is_linux == True
assert host_demo00.get_vars()["GUEST_OS"] == "linux"
assert host_demo00.get_vars()["is_linux"] is True
# test `keyed_groups`
assert im._inventory.groups["tgroup_bench_clients"].hosts == [host_demo00, host_demo01]
assert im._inventory.groups["tgroup_bench_server"].hosts == [host_demosrv]
def test_populate(inventory, mocker):
# bypass API fetch call
inventory._get_vm_pool = mocker.MagicMock(side_effect=get_vm_pool)
inventory.get_option = mocker.MagicMock(side_effect=mk_get_options(options_base_test))
inventory._populate()
# get different hosts
host_sam = inventory.inventory.get_host("sam-691-sam")
host_zabbix = inventory.inventory.get_host("zabbix-327")
host_gitlab = inventory.inventory.get_host("gitlab-107")
# test if groups exists
assert "Gitlab" in inventory.inventory.groups
assert "Centos" in inventory.inventory.groups
assert "Oracle_Linux" in inventory.inventory.groups
# check if host_zabbix is in Oracle_Linux group
group_oracle_linux = inventory.inventory.groups["Oracle_Linux"]
assert group_oracle_linux.hosts == [host_zabbix]
# check if host_gitlab is in Gitlab and Centos group
group_gitlab = inventory.inventory.groups["Gitlab"]
group_centos = inventory.inventory.groups["Centos"]
assert group_gitlab.hosts == [host_gitlab]
assert group_centos.hosts == [host_gitlab]
# check IPv4 address
assert host_sam.get_vars()["v4_first_ip"] == "172.22.4.187"
# check IPv6 address
assert host_zabbix.get_vars()["v6_first_ip"] == "2000:a001::b9ff:feae:aa0d"
# check ansible_hosts
assert host_sam.get_vars()["ansible_host"] == "172.22.4.187"
assert host_zabbix.get_vars()["ansible_host"] == "185.165.1.1"
assert host_gitlab.get_vars()["ansible_host"] == "185.165.1.3"
# check for custom ssh port
assert host_gitlab.get_vars()["ansible_port"] == 8822
# check that the 'name' variable is set by default
assert host_sam.get_vars()["name"] == "sam-691-sam"
def test_coerce_ssh_port():
coerce = InventoryModule._coerce_ssh_port
assert coerce("22") == 22
assert coerce(22) == 22
assert coerce({"#text": "8822"}) == 8822
assert coerce({"text": "443"}) == 443
assert coerce(None) is None
assert coerce("") is None
assert coerce(False) is None
assert coerce({"unexpected": ""}) is None
assert coerce("0") is None
assert coerce("99999") is None
assert coerce("not_a_port") is None
def test_populate_uname_gname(inventory, mocker):
inventory._get_vm_pool = mocker.MagicMock(side_effect=get_vm_pool)
inventory.get_option = mocker.MagicMock(side_effect=mk_get_options(options_base_test))
inventory._populate()
host_sam = inventory.inventory.get_host("sam-691-sam")
host_zabbix = inventory.inventory.get_host("zabbix-327")
assert host_sam.get_vars()["UNAME"] == "sam-admin"
assert host_sam.get_vars()["GNAME"] == "CSApparelVDC"
assert host_zabbix.get_vars()["UNAME"] == "oneadmin"
assert host_zabbix.get_vars()["GNAME"] == "oneadmin"
def test_populate_hostname_name(inventory, mocker):
opts = options_base_test.copy()
opts["hostname"] = "name"
inventory._get_vm_pool = mocker.MagicMock(side_effect=get_vm_pool)
inventory.get_option = mocker.MagicMock(side_effect=mk_get_options(opts))
inventory._populate()
host_sam = inventory.inventory.get_host("sam-691-sam")
assert "ansible_host" not in host_sam.get_vars()
def test_populate_set_name_variable_false(inventory, mocker):
opts = options_base_test.copy()
opts["set_name_variable"] = False
inventory._get_vm_pool = mocker.MagicMock(side_effect=get_vm_pool)
inventory.get_option = mocker.MagicMock(side_effect=mk_get_options(opts))
inventory._populate()
host_sam = inventory.inventory.get_host("sam-691-sam")
assert "name" not in host_sam.get_vars()
# inventory_hostname is unaffected by set_name_variable
assert host_sam.name == "sam-691-sam"
def test_populate_respects_existing_ansible_host(inventory, mocker):
opts = options_base_test.copy()
opts["hostname"] = "v4_first_ip"
opts["prefer_existing_ansible_host"] = True
inventory._get_vm_pool = mocker.MagicMock(side_effect=get_vm_pool)
inventory.get_option = mocker.MagicMock(side_effect=mk_get_options(opts))
inventory.inventory.add_host("sam-691-sam")
inventory.inventory.set_variable("sam-691-sam", "ansible_host", "10.99.99.99")
inventory._populate()
host_sam = inventory.inventory.get_host("sam-691-sam")
assert host_sam.get_vars()["ansible_host"] == "10.99.99.99"
host_zabbix = inventory.inventory.get_host("zabbix-327")
assert host_zabbix.get_vars()["ansible_host"] == "185.165.1.1"
def test_populate_overwrites_existing_ansible_host_by_default(inventory, mocker):
opts = options_base_test.copy()
opts["hostname"] = "v4_first_ip"
inventory._get_vm_pool = mocker.MagicMock(side_effect=get_vm_pool)
inventory.get_option = mocker.MagicMock(side_effect=mk_get_options(opts))
inventory.inventory.add_host("sam-691-sam")
inventory.inventory.set_variable("sam-691-sam", "ansible_host", "10.99.99.99")
inventory._populate()
host_sam = inventory.inventory.get_host("sam-691-sam")
assert host_sam.get_vars()["ansible_host"] == "172.22.4.187"
def test_populate_vm_without_nic(inventory, mocker):
vm_pool = type("pyone.bindings.VM_POOLSub", (object,), {"VM": []})()
vm = type(
"pyone.bindings.VMType90Sub",
(object,),
{
"DEPLOY_ID": "one-999",
"ETIME": 0,
"GID": 0,
"GNAME": "oneadmin",
"UNAME": "testuser",
"HISTORY_RECORDS": [],
"ID": 999,
"LAST_POLL": 0,
"LCM_STATE": 3,
"MONITORING": {},
"NAME": "no-nic-vm",
"RESCHED": 0,
"SNAPSHOTS": [],
"STATE": 3,
"STIME": 0,
"TEMPLATE": OrderedDict({}),
"USER_TEMPLATE": OrderedDict({"HYPERVISOR": "kvm"}),
},
)()
vm_pool.VM.append(vm)
inventory._get_vm_pool = mocker.MagicMock(return_value=vm_pool)
inventory.get_option = mocker.MagicMock(side_effect=mk_get_options(options_base_test))
inventory._populate()
host = inventory.inventory.get_host("no-nic-vm")
assert host is not None
assert host.get_vars()["v4_first_ip"] is False
assert host.get_vars()["v6_first_ip"] is False
def test_populate_filters(inventory, mocker):
opts = options_base_test.copy()
opts["filters"] = [
{
"include": make_trusted("v4_first_ip == '172.22.4.187'"),
},
{
"exclude": True,
},
]
# bypass API fetch call
inventory._get_vm_pool = mocker.MagicMock(side_effect=get_vm_pool)
inventory.get_option = mocker.MagicMock(side_effect=mk_get_options(opts))
assert "zabbix-327" not in inventory.inventory.hosts
inventory._populate()
assert "zabbix-327" not in inventory.inventory.hosts
# get different hosts
host_sam = inventory.inventory.get_host("sam-691-sam")
assert inventory.inventory.get_host("zabbix-327") is None
assert inventory.inventory.get_host("gitlab-107") is None
# test if groups exists
assert "Gitlab" not in inventory.inventory.groups
assert "Centos" not in inventory.inventory.groups
assert "Oracle_Linux" not in inventory.inventory.groups
# check IPv4 address
assert host_sam.get_vars()["v4_first_ip"] == "172.22.4.187"
# check ansible_hosts
assert host_sam.get_vars()["ansible_host"] == "172.22.4.187"
@@ -0,0 +1,207 @@
# Copyright (c) 2020, Jeffrey van Pelt <jeff@vanpelt.one>
# 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
#
# The API responses used in these tests were recorded from PVE version 6.2.
from __future__ import annotations
import pytest
from ansible.inventory.data import InventoryData
from ansible_collections.community.general.plugins.inventory.xen_orchestra import InventoryModule
objects = {
"vms": {
"0e64588-2bea-2d82-e922-881654b0a48f": {
"type": "VM",
"addresses": {},
"CPUs": {"max": 4, "number": 4},
"memory": {"dynamic": [1073741824, 2147483648], "static": [536870912, 4294967296], "size": 2147483648},
"name_description": "",
"name_label": "XCP-NG lab 2",
"os_version": {},
"parent": "d3af89b2-d846-0874-6acb-031ccf11c560",
"power_state": "Running",
"tags": [],
"id": "0e645898-2bea-2d82-e922-881654b0a48f",
"uuid": "0e645898-2bea-2d82-e922-881654b0a48f",
"$pool": "3d315997-73bd-5a74-8ca7-289206cb03ab",
"$poolId": "3d315997-73bd-5a74-8ca7-289206cb03ab",
"$container": "222d8594-9426-468a-ad69-7a6f02330fa3",
},
"b0d25e70-019d-6182-2f7c-b0f5d8ef9331": {
"type": "VM",
"addresses": {"0/ipv4/0": "192.168.1.55", "1/ipv4/0": "10.0.90.1"},
"CPUs": {"max": 4, "number": 4},
"mainIpAddress": "192.168.1.55",
"memory": {"dynamic": [2147483648, 2147483648], "static": [134217728, 2147483648], "size": 2147483648},
"name_description": "",
"name_label": "XCP-NG lab 3",
"os_version": {"name": "FreeBSD 11.3-STABLE", "uname": "11.3-STABLE", "distro": "FreeBSD"},
"power_state": "Halted",
"tags": [],
"id": "b0d25e70-019d-6182-2f7c-b0f5d8ef9331",
"uuid": "b0d25e70-019d-6182-2f7c-b0f5d8ef9331",
"$pool": "3d315997-73bd-5a74-8ca7-289206cb03ab",
"$poolId": "3d315997-73bd-5a74-8ca7-289206cb03ab",
"$container": "c96ec4dd-28ac-4df4-b73c-4371bd202728",
},
},
"pools": {
"3d315997-73bd-5a74-8ca7-289206cb03ab": {
"master": "222d8594-9426-468a-ad69-7a6f02330fa3",
"tags": [],
"name_description": "",
"name_label": "Storage Lab",
"cpus": {"cores": 120, "sockets": 6},
"id": "3d315997-73bd-5a74-8ca7-289206cb03ab",
"type": "pool",
"uuid": "3d315997-73bd-5a74-8ca7-289206cb03ab",
"$pool": "3d315997-73bd-5a74-8ca7-289206cb03ab",
"$poolId": "3d315997-73bd-5a74-8ca7-289206cb03ab",
}
},
"hosts": {
"c96ec4dd-28ac-4df4-b73c-4371bd202728": {
"type": "host",
"uuid": "c96ec4dd-28ac-4df4-b73c-4371bd202728",
"enabled": True,
"CPUs": {
"cpu_count": "40",
"socket_count": "2",
"vendor": "GenuineIntel",
"speed": "1699.998",
"modelname": "Intel(R) Xeon(R) CPU E5-2650L v2 @ 1.70GHz",
"family": "6",
"model": "62",
"stepping": "4",
},
"address": "172.16.210.14",
"build": "release/stockholm/master/7",
"cpus": {"cores": 40, "sockets": 2},
"hostname": "r620-s1",
"name_description": "Default install",
"name_label": "R620-S1",
"memory": {"usage": 45283590144, "size": 137391292416},
"power_state": "Running",
"tags": [],
"version": "8.2.0",
"productBrand": "XCP-ng",
"id": "c96ec4dd-28ac-4df4-b73c-4371bd202728",
"$pool": "3d315997-73bd-5a74-8ca7-289206cb03ab",
"$poolId": "3d315997-73bd-5a74-8ca7-289206cb03ab",
},
"222d8594-9426-468a-ad69-7a6f02330fa3": {
"type": "host",
"uuid": "222d8594-9426-468a-ad69-7a6f02330fa3",
"enabled": True,
"CPUs": {
"cpu_count": "40",
"socket_count": "2",
"vendor": "GenuineIntel",
"speed": "1700.007",
"modelname": "Intel(R) Xeon(R) CPU E5-2650L v2 @ 1.70GHz",
"family": "6",
"model": "62",
"stepping": "4",
},
"address": "172.16.210.16",
"build": "release/stockholm/master/7",
"cpus": {"cores": 40, "sockets": 2},
"hostname": "r620-s2",
"name_description": "Default install",
"name_label": "R620-S2",
"memory": {"usage": 10636521472, "size": 137391292416},
"power_state": "Running",
"tags": ["foo", "bar", "baz"],
"version": "8.2.0",
"productBrand": "XCP-ng",
"id": "222d8594-9426-468a-ad69-7a6f02330fa3",
"$pool": "3d315997-73bd-5a74-8ca7-289206cb03ab",
"$poolId": "3d315997-73bd-5a74-8ca7-289206cb03ab",
},
},
}
def get_option(option):
if option == "groups":
return {}
elif option == "keyed_groups":
return []
elif option == "compose":
return {}
elif option == "strict":
return False
else:
return None
@pytest.fixture(scope="module")
def inventory():
r = InventoryModule()
r.inventory = InventoryData()
return r
def test_verify_file_bad_config(inventory):
assert inventory.verify_file("foobar.xen_orchestra.yml") is False
def test_populate(inventory, mocker):
inventory.host_entry_name_type = "uuid"
inventory.vm_entry_name_type = "uuid"
inventory.get_option = mocker.MagicMock(side_effect=get_option)
inventory._populate(objects)
actual = sorted(inventory.inventory.hosts.keys())
expected = sorted(
[
"c96ec4dd-28ac-4df4-b73c-4371bd202728",
"222d8594-9426-468a-ad69-7a6f02330fa3",
"0e64588-2bea-2d82-e922-881654b0a48f",
"b0d25e70-019d-6182-2f7c-b0f5d8ef9331",
]
)
assert actual == expected
# Host with ip assertions
host_with_ip = inventory.inventory.get_host("b0d25e70-019d-6182-2f7c-b0f5d8ef9331")
host_with_ip_vars = host_with_ip.vars
assert host_with_ip_vars["ansible_host"] == "192.168.1.55"
assert host_with_ip_vars["power_state"] == "halted"
assert host_with_ip_vars["type"] == "VM"
assert host_with_ip in inventory.inventory.groups["with_ip"].hosts
# Host without ip
host_without_ip = inventory.inventory.get_host("0e64588-2bea-2d82-e922-881654b0a48f")
host_without_ip_vars = host_without_ip.vars
assert host_without_ip_vars["ansible_host"] is None
assert host_without_ip_vars["power_state"] == "running"
assert host_without_ip in inventory.inventory.groups["without_ip"].hosts
assert host_with_ip in inventory.inventory.groups["xo_host_r620_s1"].hosts
assert host_without_ip in inventory.inventory.groups["xo_host_r620_s2"].hosts
r620_s1 = inventory.inventory.get_host("c96ec4dd-28ac-4df4-b73c-4371bd202728")
r620_s2 = inventory.inventory.get_host("222d8594-9426-468a-ad69-7a6f02330fa3")
assert r620_s1.vars["address"] == "172.16.210.14"
assert r620_s1.vars["tags"] == []
assert r620_s2.vars["address"] == "172.16.210.16"
assert r620_s2.vars["tags"] == ["foo", "bar", "baz"]
storage_lab = inventory.inventory.groups["xo_pool_storage_lab"]
# Check that hosts are in their corresponding pool
assert r620_s1 in storage_lab.hosts
assert r620_s2 in storage_lab.hosts
# Check that hosts are in their corresponding pool
assert host_without_ip in storage_lab.hosts
assert host_with_ip in storage_lab.hosts
@@ -0,0 +1,35 @@
# Copyright (c) 2020 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 pytest
from ansible_collections.community.general.plugins.module_utils._onepassword_cli import OnePass
@pytest.fixture
def fake_op(mocker):
def _fake_op(version):
mocker.patch(
"ansible_collections.community.general.plugins.module_utils._onepassword_cli.OnePassCLIBase.get_current_version",
return_value=version,
)
op = OnePass()
op._config._config_file_path = "/home/jin/.op/config"
mocker.patch.object(op._cli, "_run")
return op
return _fake_op
@pytest.fixture
def opv1(fake_op):
return fake_op("1.17.2")
@pytest.fixture
def opv2(fake_op):
return fake_op("2.27.2")
@@ -0,0 +1,291 @@
# Copyright (c) 2022 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
import json
import os
from ansible_collections.community.general.plugins.module_utils._onepassword_cli import (
OnePassCLIv2,
)
def load_file(file):
with open(os.path.join(os.path.dirname(__file__), "onepassword_fixtures", file)) as f:
return json.loads(f.read())
# Intentionally excludes metadata leaf nodes that would exist in real output if not relevant.
MOCK_ENTRIES = {
OnePassCLIv2: [
{
"vault_name": "Test Vault",
"queries": [
"ywvdbojsguzgrgnokmcxtydgdv",
"Authy Backup",
],
"expected": ["OctoberPoppyNuttyDraperySabbath", "OctoberPoppyNuttyDraperySabbath"],
"output": load_file("v2_out_01.json"),
},
{
# Request a custom field where ID and label are different
"vault_name": "Test Vault",
"queries": ["Dummy Login"],
"kwargs": {
"field": "password1",
},
"expected": ["data in custom field"],
"output": load_file("v2_out_02.json"),
},
{
# Request data from a custom section
"vault_name": "Test Vault",
"queries": ["Duplicate Sections"],
"kwargs": {
"field": "s2 text",
"section": "Section 2",
},
"expected": ["first value"],
"output": load_file("v2_out_03.json"),
},
{
# Request data from an omitted value (label lookup, no section)
"vault_name": "Test Vault",
"queries": ["Omitted values"],
"kwargs": {
"field": "label-without-value",
},
"expected": [""],
"output": load_file("v2_out_04.json"),
},
{
# Request data from an omitted value (id lookup, no section)
"vault_name": "Test Vault",
"queries": ["Omitted values"],
"kwargs": {
"field": "67890q7mspf4x6zrlw3qejn7m",
},
"expected": [""],
"output": load_file("v2_out_04.json"),
},
{
# Request data from an omitted value (label lookup, with section)
"vault_name": "Test Vault",
"queries": ["Omitted values"],
"kwargs": {"field": "section-label-without-value", "section": "Section-Without-Values"},
"expected": [""],
"output": load_file("v2_out_04.json"),
},
{
# Request data from an omitted value (id lookup, with section)
"vault_name": "Test Vault",
"queries": ["Omitted values"],
"kwargs": {
"field": "123345q7mspf4x6zrlw3qejn7m",
"section": "section-without-values",
},
"expected": [""],
"output": load_file("v2_out_04.json"),
},
{
# Query item without section by lowercase id (case matching)
"vault_name": "Test Vault",
"queries": ["LabelCasing"],
"kwargs": {
"field": "lowercaseid",
},
"expected": ["lowercaseid"],
"output": load_file("v2_out_05.json"),
},
{
# Query item without section by lowercase id (case not matching)
"vault_name": "Test Vault",
"queries": ["LabelCasing"],
"kwargs": {
"field": "LOWERCASEID",
},
"expected": ["lowercaseid"],
"output": load_file("v2_out_05.json"),
},
{
# Query item without section by lowercase label (case matching)
"vault_name": "Test Vault",
"queries": ["LabelCasing"],
"kwargs": {
"field": "lowercaselabel",
},
"expected": ["lowercaselabel"],
"output": load_file("v2_out_05.json"),
},
{
# Query item without section by lowercase label (case not matching)
"vault_name": "Test Vault",
"queries": ["LabelCasing"],
"kwargs": {
"field": "LOWERCASELABEL",
},
"expected": ["lowercaselabel"],
"output": load_file("v2_out_05.json"),
},
{
# Query item without section by mixed case id (case matching)
"vault_name": "Test Vault",
"queries": ["LabelCasing"],
"kwargs": {
"field": "MiXeDcAsEiD",
},
"expected": ["mixedcaseid"],
"output": load_file("v2_out_05.json"),
},
{
# Query item without section by mixed case id (case not matching)
"vault_name": "Test Vault",
"queries": ["LabelCasing"],
"kwargs": {
"field": "mixedcaseid",
},
"expected": ["mixedcaseid"],
"output": load_file("v2_out_05.json"),
},
{
# Query item without section by mixed case label (case matching)
"vault_name": "Test Vault",
"queries": ["LabelCasing"],
"kwargs": {
"field": "MiXeDcAsElAbEl",
},
"expected": ["mixedcaselabel"],
"output": load_file("v2_out_05.json"),
},
{
# Query item without section by mixed case label (case not matching)
"vault_name": "Test Vault",
"queries": ["LabelCasing"],
"kwargs": {
"field": "mixedcaselabel",
},
"expected": ["mixedcaselabel"],
"output": load_file("v2_out_05.json"),
},
{
# Query item with section by lowercase id (case matching)
"vault_name": "Test Vault",
"queries": ["LabelCasing"],
"kwargs": {
"field": "sectionlowercaseid",
"section": "section-with-values",
},
"expected": ["sectionlowercaseid"],
"output": load_file("v2_out_05.json"),
},
{
# Query item with section by lowercase id (case not matching)
"vault_name": "Test Vault",
"queries": ["LabelCasing"],
"kwargs": {
"field": "SECTIONLOWERCASEID",
"section": "section-with-values",
},
"expected": ["sectionlowercaseid"],
"output": load_file("v2_out_05.json"),
},
{
# Query item with section by lowercase label (case matching)
"vault_name": "Test Vault",
"queries": ["LabelCasing"],
"kwargs": {
"field": "sectionlowercaselabel",
"section": "section-with-values",
},
"expected": ["sectionlowercaselabel"],
"output": load_file("v2_out_05.json"),
},
{
# Query item with section by lowercase label (case not matching)
"vault_name": "Test Vault",
"queries": ["LabelCasing"],
"kwargs": {
"field": "SECTIONLOWERCASELABEL",
"section": "section-with-values",
},
"expected": ["sectionlowercaselabel"],
"output": load_file("v2_out_05.json"),
},
{
# Query item with section by lowercase id (case matching)
"vault_name": "Test Vault",
"queries": ["LabelCasing"],
"kwargs": {
"field": "SeCtIoNmIxEdCaSeId",
"section": "section-with-values",
},
"expected": ["sectionmixedcaseid"],
"output": load_file("v2_out_05.json"),
},
{
# Query item with section by lowercase id (case not matching)
"vault_name": "Test Vault",
"queries": ["LabelCasing"],
"kwargs": {
"field": "sectionmixedcaseid",
"section": "section-with-values",
},
"expected": ["sectionmixedcaseid"],
"output": load_file("v2_out_05.json"),
},
{
# Query item with section by lowercase label (case matching)
"vault_name": "Test Vault",
"queries": ["LabelCasing"],
"kwargs": {
"field": "SeCtIoNmIxEdCaSeLaBeL",
"section": "section-with-values",
},
"expected": ["sectionmixedcaselabel"],
"output": load_file("v2_out_05.json"),
},
{
# Query item with section by lowercase label (case not matching)
"vault_name": "Test Vault",
"queries": ["LabelCasing"],
"kwargs": {
"field": "sectionmixedcaselabel",
"section": "section-with-values",
},
"expected": ["sectionmixedcaselabel"],
"output": load_file("v2_out_05.json"),
},
],
}
SSH_KEY_MOCK_ENTRIES = [
# loads private key in PKCS#8 format by default
{
"vault_name": "Personal",
"queries": ["ssh key"],
"expected": ["-----BEGIN PRIVATE KEY-----\n..........=\n-----END PRIVATE KEY-----\n"],
"output": load_file("ssh_key_output.json"),
},
# loads private key in PKCS#8 format becasue ssh_format=false
{
"vault_name": "Personal",
"queries": ["ssh key"],
"kwargs": {
"ssh_format": False,
},
"expected": ["-----BEGIN PRIVATE KEY-----\n..........=\n-----END PRIVATE KEY-----\n"],
"output": load_file("ssh_key_output.json"),
},
# loads private key in ssh format
{
"vault_name": "Personal",
"queries": ["ssh key"],
"kwargs": {
"ssh_format": True,
},
"expected": ["-----BEGIN OPENSSH PRIVATE KEY-----\r\n.....\r\n-----END OPENSSH PRIVATE KEY-----\r\n"],
"output": load_file("ssh_key_output.json"),
},
]
@@ -0,0 +1,57 @@
{
"id": "wdtryfeh3jlx2dlanqgg4dqxmy",
"title": "ssh key",
"version": 1,
"vault": {
"id": "5auhrjy66hc7ndhe2wvym6gadv",
"name": "Personal"
},
"category": "SSH_KEY",
"last_edited_by": "LSGPJERUYBH7BFPHMZ2KKGL6AU",
"created_at": "2025-01-10T16:57:16Z",
"updated_at": "2025-01-10T16:57:16Z",
"additional_information": "SHA256:frHmQAgblahD5HHgNj2O714",
"fields": [
{
"id": "public_key",
"type": "STRING",
"label": "public key",
"value": "ssh-ed255.....",
"reference": "op://Personal/ssh key/public key"
},
{
"id": "fingerprint",
"type": "STRING",
"label": "fingerprint",
"value": "SHA256:frHmQAgy7zBKeFDxHMW0QltZ/5O4N8gD5HHgNj2O614",
"reference": "op://Personal/ssh key/fingerprint"
},
{
"id": "private_key",
"type": "SSHKEY",
"label": "private key",
"value": "-----BEGIN PRIVATE KEY-----\n..........=\n-----END PRIVATE KEY-----\n",
"reference": "op://Personal/ssh key/private key",
"ssh_formats": {
"openssh": {
"reference": "op://Personal/ssh key/private key?ssh-format=openssh",
"value": "-----BEGIN OPENSSH PRIVATE KEY-----\r\n.....\r\n-----END OPENSSH PRIVATE KEY-----\r\n"
}
}
},
{
"id": "key_type",
"type": "STRING",
"label": "key type",
"value": "ed25519",
"reference": "op://Personal/ssh key/key type"
},
{
"id": "notesPlain",
"type": "STRING",
"purpose": "NOTES",
"label": "notesPlain",
"reference": "op://Personal/ssh key/notesPlain"
}
]
}
@@ -0,0 +1,3 @@
GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
SPDX-License-Identifier: GPL-3.0-or-later
SPDX-FileCopyrightText: 2025, Ansible Project
@@ -0,0 +1,18 @@
{
"uuid": "0123456789",
"vaultUuid": "2468",
"overview": {
"title": "Mock \"Quot'd\" Server"
},
"details": {
"sections": [{
"title": "",
"fields": [
{"t": "username", "v": "jamesbond"},
{"t": "password", "v": "t0pS3cret"},
{"t": "notes", "v": "Test note with\nmultiple lines and trailing space.\n\n"},
{"t": "tricksy \"quot'd\" field\\", "v": "\"quot'd\" value"}
]
}]
}
}
@@ -0,0 +1,3 @@
GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
SPDX-License-Identifier: GPL-3.0-or-later
SPDX-FileCopyrightText: 2022, Ansible Project
@@ -0,0 +1,18 @@
{
"uuid": "9876543210",
"vaultUuid": "1357",
"overview": {
"title": "Mock Website",
"URLs": [
{"l": "website", "u": "https://acme.com/login"}
]
},
"details": {
"sections": [{
"title": "",
"fields": [
{"t": "password", "v": "t0pS3cret"}
]
}]
}
}
@@ -0,0 +1,3 @@
GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
SPDX-License-Identifier: GPL-3.0-or-later
SPDX-FileCopyrightText: 2022, Ansible Project
@@ -0,0 +1,20 @@
{
"uuid": "864201357",
"vaultUuid": "1357",
"overview": {
"title": "Mock Something"
},
"details": {
"fields": [
{
"value": "jbond@mi6.gov.uk",
"name": "emailAddress"
},
{
"name": "password",
"value": "vauxhall"
},
{}
]
}
}
@@ -0,0 +1,3 @@
GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
SPDX-License-Identifier: GPL-3.0-or-later
SPDX-FileCopyrightText: 2022, Ansible Project
@@ -0,0 +1,35 @@
{
"id": "ywvdbojsguzgrgnokmcxtydgdv",
"title": "Authy Backup",
"version": 1,
"vault": {
"id": "bcqxysvcnejjrwzoqrwzcqjqxc",
"name": "test vault"
},
"category": "PASSWORD",
"last_edited_by": "7FUPZ8ZNE02KSHMAIMKHIVUE17",
"created_at": "2015-01-18T13:13:38Z",
"updated_at": "2016-02-20T16:23:54Z",
"additional_information": "Jan 18, 2015, 08:13:38",
"fields": [
{
"id": "Password",
"type": "CONCEALED",
"purpose": "PASSWORD",
"label": "Password",
"value": "OctoberPoppyNuttyDraperySabbath",
"reference": "op://Test Vault/Authy Backup/password",
"password_details": {
"strength": "FANTASTIC"
}
},
{
"id": "notesPlain",
"type": "STRING",
"purpose": "NOTES",
"label": "notesPlain",
"value": "Backup password to restore Authy",
"reference": "op://Test Vault/Authy Backup/notesPlain"
}
]
}
@@ -0,0 +1,3 @@
GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
SPDX-License-Identifier: GPL-3.0-or-later
SPDX-FileCopyrightText: 2022, Ansible Project
@@ -0,0 +1,85 @@
{
"id": "awk4s2u44fhnrgppszcsvc663i",
"title": "Dummy Login",
"version": 4,
"vault": {
"id": "stpebbaccrq72xulgouxsk4p7y",
"name": "Personal"
},
"category": "LOGIN",
"last_edited_by": "LSGPJERUYBH7BFPHMZ2KKGL6AU",
"created_at": "2018-04-25T21:55:19Z",
"updated_at": "2022-09-02T17:51:21Z",
"additional_information": "agent.smith",
"urls": [
{
"primary": true,
"href": "https://acme.com"
}
],
"sections": [
{
"id": "add more"
},
{
"id": "gafaeg7vnqmgrklw5r6yrufyxy",
"label": "COMMANDS"
},
{
"id": "linked items",
"label": "Related Items"
}
],
"fields": [
{
"id": "username",
"type": "STRING",
"purpose": "USERNAME",
"label": "username",
"value": "agent.smith",
"reference": "op://Personal/Dummy Login/username"
},
{
"id": "password",
"type": "CONCEALED",
"purpose": "PASSWORD",
"label": "password",
"value": "FootworkDegreeReverence",
"entropy": 159.60836791992188,
"reference": "op://Personal/Dummy Login/password",
"password_details": {
"entropy": 159,
"generated": true,
"strength": "FANTASTIC"
}
},
{
"id": "notesPlain",
"type": "STRING",
"purpose": "NOTES",
"label": "notesPlain",
"reference": "op://Personal/Dummy Login/notesPlain"
},
{
"id": "7gyjekelk24ghgd4rvafspjbli",
"section": {
"id": "add more"
},
"type": "STRING",
"label": "title",
"value": "value of the field",
"reference": "op://Personal/Dummy Login/add more/title"
},
{
"id": "fx4wpzokrxn7tlb3uwpdjfptgm",
"section": {
"id": "gafaeg7vnqmgrklw5r6yrufyxy",
"label": "COMMANDS"
},
"type": "CONCEALED",
"label": "password1",
"value": "data in custom field",
"reference": "op://Personal/Dummy Login/COMMANDS/password1"
}
]
}
@@ -0,0 +1,3 @@
GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
SPDX-License-Identifier: GPL-3.0-or-later
SPDX-FileCopyrightText: 2022, Ansible Project
@@ -0,0 +1,103 @@
{
"id": "7t7qu2r35qyvqj3crujd4dqxmy",
"title": "Duplicate Sections",
"version": 3,
"vault": {
"id": "stpebbaccrq72xulgouxsk4p7y",
"name": "Personal"
},
"category": "LOGIN",
"last_edited_by": "LSGPJERUYBH7BFPHMZ2KKGL6AU",
"created_at": "2022-11-04T17:09:18Z",
"updated_at": "2022-11-04T17:22:19Z",
"additional_information": "flora",
"urls": [
{
"label": "website",
"primary": true,
"href": "https://acme.com/login"
}
],
"sections": [
{
"id": "add more"
},
{
"id": "7osqcvd43i75teocdzbb6d7mie",
"label": "Section 2"
}
],
"fields": [
{
"id": "username",
"type": "STRING",
"purpose": "USERNAME",
"label": "username",
"value": "flora",
"reference": "op://Personal/Duplicate Sections/username"
},
{
"id": "password",
"type": "CONCEALED",
"purpose": "PASSWORD",
"label": "password",
"value": "PtZGFLAibx-erTo7ywywEvh-n4syas97n-tuF2D.b8DdqA2vCjrvRGkNQxj!Gi9R",
"entropy": 379.564697265625,
"reference": "op://Personal/Duplicate Sections/password",
"password_details": {
"entropy": 379,
"generated": true,
"strength": "FANTASTIC"
}
},
{
"id": "notesPlain",
"type": "STRING",
"purpose": "NOTES",
"label": "notesPlain",
"reference": "op://Personal/Duplicate Sections/notesPlain"
},
{
"id": "4saaazkb7arwisj6ysctb4jmm4",
"section": {
"id": "add more"
},
"type": "STRING",
"label": "text",
"value": "text field the first",
"reference": "op://Personal/Duplicate Sections/add more/text"
},
{
"id": "4vtfkj4bwcmg7d5uf62wnpkp3a",
"section": {
"id": "add more"
},
"type": "STRING",
"label": "text",
"value": "text field the second",
"reference": "op://Personal/Duplicate Sections/add more/text"
},
{
"id": "wbrjnowkrgavpooomtht36gjqu",
"section": {
"id": "7osqcvd43i75teocdzbb6d7mie",
"label": "Section 2"
},
"type": "STRING",
"label": "s2 text",
"value": "first value",
"reference": "op://Personal/Duplicate Sections/Section 2/s2 text"
},
{
"id": "bddlz2fj2pebmtfhksbmcexy7m",
"section": {
"id": "7osqcvd43i75teocdzbb6d7mie",
"label": "Section 2"
},
"type": "STRING",
"label": "s2 text",
"value": "second value",
"reference": "op://Personal/Duplicate Sections/Section 2/s2 text"
}
]
}
@@ -0,0 +1,3 @@
GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
SPDX-License-Identifier: GPL-3.0-or-later
SPDX-FileCopyrightText: 2022, Ansible Project
@@ -0,0 +1,67 @@
{
"id": "bgqegp3xcxnpfkb45olwigpkpi",
"title": "OmittedValues",
"version": 1,
"vault": {
"id": "stpebbaccrq72xulgouxsk4p7y",
"name": "Private"
},
"category": "LOGIN",
"last_edited_by": "WOUTERRUYBH7BFPHMZ2KKGL6AU",
"created_at": "2023-09-12T08:30:07Z",
"updated_at": "2023-09-12T08:30:07Z",
"additional_information": "fluxility",
"sections": [
{
"id": "7osqcvd43i75teocdzbb6d7mie",
"label": "section-without-values"
}
],
"fields": [
{
"id": "username",
"type": "STRING",
"purpose": "USERNAME",
"label": "username",
"value": "fluxility",
"reference": "op://Testcase/OmittedValues/username"
},
{
"id": "password",
"type": "CONCEALED",
"purpose": "PASSWORD",
"label": "password",
"value": "j89Dyb7psat*hkbkyLUQyq@GR.a-g2pQH_V_xtMhrn37rQ_2uRYoRiozj6TjWVLy2pbfEvjnse",
"entropy": 427.01202392578125,
"reference": "op://Testcase/OmittedValues/password",
"password_details": {
"entropy": 427,
"generated": true,
"strength": "FANTASTIC"
}
},
{
"id": "notesPlain",
"type": "STRING",
"purpose": "NOTES",
"label": "notesPlain",
"reference": "op://Testcase/OmittedValues/notesPlain"
},
{
"id": "67890q7mspf4x6zrlw3qejn7m",
"type": "URL",
"label": "label-without-value",
"reference": "op://01202392578125/OmittedValues/section-without-values/section-without-value"
},
{
"id": "123345q7mspf4x6zrlw3qejn7m",
"section": {
"id": "6hbtca5yrlmoptgy3nw74222",
"label": "section-without-values"
},
"type": "URL",
"label": "section-label-without-value",
"reference": "op://01202392578125/OmittedValues/section-without-values/section-without-value"
}
]
}
@@ -0,0 +1,3 @@
GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
SPDX-License-Identifier: GPL-3.0-or-later
SPDX-FileCopyrightText: 2022, Ansible Project
@@ -0,0 +1,102 @@
{
"id": "bgqegp3xcxnpfkb45olwigpkpi",
"title": "LabelCasing",
"version": 1,
"vault": {
"id": "stpebbaccrq72xulgouxsk4p7y",
"name": "Private"
},
"category": "LOGIN",
"last_edited_by": "WOUTERRUYBH7BFPHMZ2KKGL6AU",
"created_at": "2023-09-12T08:30:07Z",
"updated_at": "2023-09-12T08:30:07Z",
"additional_information": "fluxility",
"sections": [
{
"id": "7osqcvd43i75teocdzbb6d7mie",
"label": "section-with-values"
}
],
"fields": [
{
"id": "lowercaseid",
"type": "STRING",
"purpose": "USERNAME",
"label": "label0",
"value": "lowercaseid",
"reference": "op://Testcase/LabelCasing/lowercase"
},
{
"id": "MiXeDcAsEiD",
"type": "STRING",
"purpose": "USERNAME",
"label": "label1",
"value": "mixedcaseid",
"reference": "op://Testcase/LabelCasing/lowercase"
},
{
"id": "id1",
"type": "STRING",
"purpose": "USERNAME",
"label": "lowercaselabel",
"value": "lowercaselabel",
"reference": "op://Testcase/LabelCasing/lowercase"
},
{
"id": "id2",
"type": "STRING",
"purpose": "USERNAME",
"label": "MiXeDcAsElAbEl",
"value": "mixedcaselabel",
"reference": "op://Testcase/LabelCasing/lowercase"
},
{
"id": "sectionlowercaseid",
"type": "STRING",
"purpose": "USERNAME",
"label": "label2",
"value": "sectionlowercaseid",
"reference": "op://Testcase/LabelCasing/lowercase",
"section": {
"id": "7osqcvd43i75teocdzbb6d7mie",
"label": "section-with-values"
}
},
{
"id": "SeCtIoNmIxEdCaSeId",
"type": "STRING",
"purpose": "USERNAME",
"label": "label3",
"value": "sectionmixedcaseid",
"reference": "op://Testcase/LabelCasing/lowercase",
"section": {
"id": "7osqcvd43i75teocdzbb6d7mie",
"label": "section-with-values"
}
},
{
"id": "id3",
"type": "STRING",
"purpose": "USERNAME",
"label": "sectionlowercaselabel",
"value": "sectionlowercaselabel",
"reference": "op://Testcase/LabelCasing/lowercase",
"section": {
"id": "7osqcvd43i75teocdzbb6d7mie",
"label": "section-with-values"
}
},
{
"id": "id2",
"type": "STRING",
"purpose": "USERNAME",
"label": "SeCtIoNmIxEdCaSeLaBeL",
"value": "sectionmixedcaselabel",
"reference": "op://Testcase/LabelCasing/lowercase",
"section": {
"id": "7osqcvd43i75teocdzbb6d7mie",
"label": "section-with-values"
}
}
]
}
@@ -0,0 +1,3 @@
GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
SPDX-License-Identifier: GPL-3.0-or-later
SPDX-FileCopyrightText: 2022, Ansible Project
@@ -0,0 +1,302 @@
# Copyright (c) 2022, Jonathan Lung <lungj@heresjono.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 re
import unittest
from unittest.mock import patch
from ansible.errors import AnsibleError
from ansible.parsing.ajson import AnsibleJSONEncoder
from ansible.plugins.loader import lookup_loader
from ansible_collections.community.general.plugins.lookup.bitwarden import Bitwarden, BitwardenException
MOCK_COLLECTION_ID = "3b12a9da-7c49-40b8-ad33-aede017a7ead"
MOCK_ORGANIZATION_ID = "292ba0c6-f289-11ee-9301-ef7b639ccd2a"
MOCK_RECORDS = [
{
"collectionIds": [MOCK_COLLECTION_ID],
"deletedDate": None,
"favorite": False,
"fields": [
{"linkedId": None, "name": "a_new_secret", "type": 1, "value": "this is a new secret"},
{"linkedId": None, "name": "not so secret", "type": 0, "value": "not secret"},
],
"folderId": "3b12a9da-7c49-40b8-ad33-aede017a7ead",
"id": "90992f63-ddb6-4e76-8bfc-aede016ca5eb",
"login": {
"password": "passwordA3",
"passwordRevisionDate": "2022-07-26T23:03:23.399Z",
"totp": None,
"username": "userA",
},
"name": "a_test",
"notes": None,
"object": "item",
"organizationId": MOCK_ORGANIZATION_ID,
"passwordHistory": [
{"lastUsedDate": "2022-07-26T23:03:23.405Z", "password": "a_new_secret: this is secret"},
{"lastUsedDate": "2022-07-26T23:03:23.399Z", "password": "passwordA2"},
{"lastUsedDate": "2022-07-26T22:59:52.885Z", "password": "passwordA"},
],
"reprompt": 0,
"revisionDate": "2022-07-26T23:03:23.743Z",
"type": 1,
},
{
"collectionIds": [],
"deletedDate": None,
"favorite": False,
"folderId": None,
"id": "5ebd4d31-104c-49fc-a09c-aedf003d28ad",
"login": {"password": "b", "passwordRevisionDate": None, "totp": None, "username": "a"},
"name": "dupe_name",
"notes": None,
"object": "item",
"organizationId": None,
"reprompt": 0,
"revisionDate": "2022-07-27T03:42:40.353Z",
"type": 1,
},
{
"collectionIds": [MOCK_COLLECTION_ID],
"deletedDate": None,
"favorite": False,
"folderId": None,
"id": "90657653-6695-496d-9431-aedf003d3015",
"login": {"password": "d", "passwordRevisionDate": None, "totp": None, "username": "c"},
"name": "dupe_name",
"notes": None,
"object": "item",
"organizationId": MOCK_ORGANIZATION_ID,
"reprompt": 0,
"revisionDate": "2022-07-27T03:42:46.673Z",
"type": 1,
},
{
"collectionIds": [],
"deletedDate": None,
"favorite": False,
"folderId": None,
"id": "2bf517be-fb13-11ee-be89-a345aa369a94",
"login": {"password": "e", "passwordRevisionDate": None, "totp": None, "username": "f"},
"name": "non_collection_org_record",
"notes": None,
"object": "item",
"organizationId": MOCK_ORGANIZATION_ID,
"reprompt": 0,
"revisionDate": "2024-14-15T11:30:00.000Z",
"type": 1,
},
{
"object": "collection",
"id": MOCK_COLLECTION_ID,
"organizationId": MOCK_ORGANIZATION_ID,
"name": "MOCK_COLLECTION",
"externalId": None,
},
{
"object": "collection",
"id": "3b12a9da-7c49-40b8-ad33-aede017a8ead",
"organizationId": "3b12a9da-7c49-40b8-ad33-aede017a9ead",
"name": "some/other/collection",
"externalId": None,
},
]
class MockBitwarden(Bitwarden):
unlocked = True
synced = False
def _run(self, args, stdin=None, expected_rc=0):
if args[0] == "sync":
self.synced = True
return "Syncing complete.", ""
if args[0] == "get":
if args[1] == "item":
for item in MOCK_RECORDS:
if item.get("id") == args[2]:
return AnsibleJSONEncoder().encode(item), ""
if args[0] == "list":
if args[1] == "items":
try:
search_value = args[args.index("--search") + 1]
except ValueError:
search_value = None
try:
collection_to_filter = args[args.index("--collectionid") + 1]
except ValueError:
collection_to_filter = None
try:
organization_to_filter = args[args.index("--organizationid") + 1]
except ValueError:
organization_to_filter = None
items = []
search_re = re.compile(search_value) if search_value else None
for item in MOCK_RECORDS:
if item.get("object") != "item":
continue
if search_re and not search_re.search(item.get("name")):
continue
if collection_to_filter and collection_to_filter not in item.get("collectionIds", []):
continue
if organization_to_filter and item.get("organizationId") != organization_to_filter:
continue
items.append(item)
return AnsibleJSONEncoder().encode(items), ""
elif args[1] == "collections":
try:
search_value = args[args.index("--search") + 1]
except ValueError:
search_value = None
try:
collection_to_filter = args[args.index("--collectionid") + 1]
except ValueError:
collection_to_filter = None
try:
organization_to_filter = args[args.index("--organizationid") + 1]
except ValueError:
organization_to_filter = None
collections = []
search_re = re.compile(search_value) if search_value else None
for item in MOCK_RECORDS:
if item.get("object") != "collection":
continue
if search_re and not search_re.search(item.get("name")):
continue
if collection_to_filter and collection_to_filter not in item.get("collectionIds", []):
continue
if organization_to_filter and item.get("organizationId") != organization_to_filter:
continue
collections.append(item)
return AnsibleJSONEncoder().encode(collections), ""
return "[]", ""
class LoggedOutMockBitwarden(MockBitwarden):
unlocked = False
class TestLookupModule(unittest.TestCase):
def setUp(self):
self.lookup = lookup_loader.get("community.general.bitwarden")
@patch("ansible_collections.community.general.plugins.lookup.bitwarden._bitwarden", new=MockBitwarden())
def test_bitwarden_plugin_no_match(self):
# Entry 0, "a_test" of the test input should have no duplicates.
self.assertEqual([], self.lookup.run(["not_here"], field="password")[0])
@patch("ansible_collections.community.general.plugins.lookup.bitwarden._bitwarden", new=MockBitwarden())
def test_bitwarden_plugin_fields(self):
# Entry 0, "a_test" of the test input should have no duplicates.
record = MOCK_RECORDS[0]
record_name = record["name"]
for k, v in record["login"].items():
self.assertEqual([v], self.lookup.run([record_name], field=k)[0])
@patch("ansible_collections.community.general.plugins.lookup.bitwarden._bitwarden", new=MockBitwarden())
def test_bitwarden_plugin_duplicates(self):
# There are two records with name dupe_name; we need to be order-insensitive with
# checking what was retrieved.
self.assertEqual({"b", "d"}, set(self.lookup.run(["dupe_name"], field="password")[0]))
@patch("ansible_collections.community.general.plugins.lookup.bitwarden._bitwarden", new=MockBitwarden())
def test_bitwarden_plugin_full_item(self):
# Try to retrieve the full record of the first entry where the name is "a_name".
self.assertEqual([MOCK_RECORDS[0]], self.lookup.run(["a_test"])[0])
@patch("ansible_collections.community.general.plugins.lookup.bitwarden._bitwarden", LoggedOutMockBitwarden())
def test_bitwarden_plugin_unlocked(self):
record = MOCK_RECORDS[0]
record_name = record["name"]
with self.assertRaises(AnsibleError) as raised_error:
self.lookup.run([record_name], field="password")
self.assertEqual("Bitwarden Vault locked. Run 'bw unlock'.", str(raised_error.exception))
def test_bitwarden_plugin_without_session_option(self):
mock_bitwarden = MockBitwarden()
with patch("ansible_collections.community.general.plugins.lookup.bitwarden._bitwarden", mock_bitwarden):
record = MOCK_RECORDS[0]
record_name = record["name"]
self.lookup.run([record_name], field=None)
self.assertIsNone(mock_bitwarden.session)
def test_bitwarden_plugin_session_option(self):
mock_bitwarden = MockBitwarden()
with patch("ansible_collections.community.general.plugins.lookup.bitwarden._bitwarden", mock_bitwarden):
record = MOCK_RECORDS[0]
record_name = record["name"]
session = "session"
self.lookup.run([record_name], field=None, bw_session=session)
self.assertEqual(mock_bitwarden.session, session)
@patch("ansible_collections.community.general.plugins.lookup.bitwarden._bitwarden", new=MockBitwarden())
def test_bitwarden_plugin_full_collection(self):
# Try to retrieve the full records of the given collection.
self.assertEqual([MOCK_RECORDS[0], MOCK_RECORDS[2]], self.lookup.run(None, collection_id=MOCK_COLLECTION_ID)[0])
@patch("ansible_collections.community.general.plugins.lookup.bitwarden._bitwarden", new=MockBitwarden())
def test_bitwarden_plugin_full_organization(self):
self.assertEqual(
[MOCK_RECORDS[0], MOCK_RECORDS[2], MOCK_RECORDS[3]],
self.lookup.run(None, organization_id=MOCK_ORGANIZATION_ID)[0],
)
@patch("ansible_collections.community.general.plugins.lookup.bitwarden._bitwarden", new=MockBitwarden())
def test_bitwarden_plugin_filter_organization(self):
self.assertEqual([MOCK_RECORDS[2]], self.lookup.run(["dupe_name"], organization_id=MOCK_ORGANIZATION_ID)[0])
@patch("ansible_collections.community.general.plugins.lookup.bitwarden._bitwarden", new=MockBitwarden())
def test_bitwarden_plugin_full_collection_organization(self):
self.assertEqual(
[MOCK_RECORDS[0], MOCK_RECORDS[2]],
self.lookup.run(None, collection_id=MOCK_COLLECTION_ID, organization_id=MOCK_ORGANIZATION_ID)[0],
)
@patch("ansible_collections.community.general.plugins.lookup.bitwarden._bitwarden", new=MockBitwarden())
def test_bitwarden_plugin_collection_name_filter(self):
# all passwords from MOCK_COLLECTION
self.assertEqual(
[MOCK_RECORDS[0], MOCK_RECORDS[2]], self.lookup.run(None, collection_name="MOCK_COLLECTION")[0]
)
# Existing collection, no results
self.assertEqual([], self.lookup.run(None, collection_name="some/other/collection")[0])
# Non-Existent collection
with self.assertRaises(BitwardenException):
self.lookup.run(None, collection_name="nonexistent")
@patch("ansible_collections.community.general.plugins.lookup.bitwarden._bitwarden", new=MockBitwarden())
def test_bitwarden_plugin_result_count_check(self):
self.lookup.run(None, collection_id=MOCK_COLLECTION_ID, organization_id=MOCK_ORGANIZATION_ID, result_count=2)
with self.assertRaises(BitwardenException):
self.lookup.run(
None, collection_id=MOCK_COLLECTION_ID, organization_id=MOCK_ORGANIZATION_ID, result_count=1
)
self.lookup.run(None, organization_id=MOCK_ORGANIZATION_ID, result_count=3)
with self.assertRaises(BitwardenException):
self.lookup.run(None, organization_id=MOCK_ORGANIZATION_ID, result_count=0)
def test_bitwarden_plugin_sync_option(self):
mock_bitwarden = MockBitwarden()
with patch("ansible_collections.community.general.plugins.lookup.bitwarden._bitwarden", mock_bitwarden):
self.lookup.run([], sync=True)
self.assertTrue(mock_bitwarden.synced)
@@ -0,0 +1,90 @@
# Copyright (c) 2023, jantari (https://github.com/jantari)
# 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 json
import unittest
from unittest.mock import patch
from ansible.errors import AnsibleLookupError
from ansible.plugins.loader import lookup_loader
from ansible_collections.community.general.plugins.lookup.bitwarden_secrets_manager import BitwardenSecretsManager
MOCK_SECRETS = [
{
"object": "secret",
"id": "ababc4a8-c242-4e54-bceb-77d17cdf2e07",
"organizationId": "3c33066c-a0bf-4e70-9a3c-24cda6aaddd5",
"projectId": "81869439-bfe5-442f-8b4e-b172e68b0ab2",
"key": "TEST_SECRET",
"value": "1234supersecret5678",
"note": "A test secret to use when developing the ansible bitwarden_secrets_manager lookup plugin",
"creationDate": "2023-04-23T13:13:37.7507017Z",
"revisionDate": "2023-04-23T13:13:37.7507017Z",
},
{
"object": "secret",
"id": "d4b7c8fa-fc95-40d7-a13c-6e186ee69d53",
"organizationId": "3c33066c-a0bf-4e70-9a3c-24cda6aaddd5",
"projectId": "81869439-bfe5-442f-8b4e-b172e68b0ab2",
"key": "TEST_SECRET_2",
"value": "abcd_such_secret_very_important_efgh",
"note": "notes go here",
"creationDate": "2023-04-23T13:26:44.0392906Z",
"revisionDate": "2023-04-23T13:26:44.0392906Z",
},
]
class MockBitwardenSecretsManager(BitwardenSecretsManager):
def _run(self, args, stdin=None):
# mock the --version call
if args[0] == "--version":
return "bws 1.0.0", "", 0
# secret_id is the last argument passed to the bws CLI
secret_id = args[-1]
rc = 1
out = ""
err = ""
found_secrets = list(filter(lambda record: record["id"] == secret_id, MOCK_SECRETS))
if len(found_secrets) == 0:
err = "simulated bws CLI error: 404 no secret with such id"
elif len(found_secrets) == 1:
rc = 0
# The real bws CLI will only ever return one secret / json object for the "get secret <secret-id>" command
out = json.dumps(found_secrets[0])
else:
# This should never happen unless there's an error in the test MOCK_SECRETS.
# The real Bitwarden Secrets Manager assigns each secret a unique ID.
raise ValueError(f"More than 1 secret found with id: '{secret_id}'. Impossible!")
return out, err, rc
class TestLookupModule(unittest.TestCase):
def setUp(self):
self.lookup = lookup_loader.get("community.general.bitwarden_secrets_manager")
@patch(
"ansible_collections.community.general.plugins.lookup.bitwarden_secrets_manager._bitwarden_secrets_manager",
new=MockBitwardenSecretsManager(),
)
def test_bitwarden_secrets_manager(self):
# Getting a secret by its id should return the full secret info
self.assertEqual(
[MOCK_SECRETS[0]], self.lookup.run(["ababc4a8-c242-4e54-bceb-77d17cdf2e07"], bws_access_token="123")
)
@patch(
"ansible_collections.community.general.plugins.lookup.bitwarden_secrets_manager._bitwarden_secrets_manager",
new=MockBitwardenSecretsManager(),
)
def test_bitwarden_secrets_manager_no_match(self):
# Getting a nonexistent secret id throws exception
with self.assertRaises(AnsibleLookupError):
self.lookup.run(["nonexistant_id"], bws_access_token="123")
@@ -0,0 +1,98 @@
# 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
import json
import unittest
from unittest.mock import MagicMock, patch
from urllib.error import HTTPError
from ansible.plugins.loader import lookup_loader
def _entry(value, key="somekey"):
return {"Key": key, "Value": None if value is None else _b64(value)}
def _b64(value):
import base64
return base64.b64encode(value.encode("utf-8")).decode("utf-8")
def _response(entries):
response = MagicMock()
response.read.return_value = json.dumps(entries).encode("utf-8")
return response
def _not_found():
return HTTPError("http://localhost:8500/v1/kv/somekey", 404, "Not Found", {}, None)
class TestLookupModule(unittest.TestCase):
def setUp(self):
self.lookup = lookup_loader.get("community.general.consul_kv")
def test_simple_lookup(self):
with patch(
"ansible_collections.community.general.plugins.lookup.consul_kv.open_url",
return_value=_response([_entry("somevalue")]),
) as open_url:
result = self.lookup.run(["somekey"])
self.assertEqual(result, ["somevalue"])
args, kwargs = open_url.call_args
self.assertEqual(args[0], "http://localhost:8500/v1/kv/somekey")
self.assertEqual(kwargs["headers"], {})
def test_token_sets_header(self):
with patch(
"ansible_collections.community.general.plugins.lookup.consul_kv.open_url",
return_value=_response([_entry("somevalue")]),
) as open_url:
self.lookup.run(["somekey token=mytoken"])
self.assertEqual(open_url.call_args.kwargs["headers"], {"X-Consul-Token": "mytoken"})
def test_recurse_returns_multiple_values(self):
entries = [_entry("v1", "prefix/a"), _entry("v2", "prefix/b")]
with patch(
"ansible_collections.community.general.plugins.lookup.consul_kv.open_url",
return_value=_response(entries),
) as open_url:
result = self.lookup.run(["prefix recurse=true"])
self.assertEqual(result, ["v1", "v2"])
self.assertIn("recurse=true", open_url.call_args.args[0])
def test_missing_key_returns_empty_list(self):
with patch(
"ansible_collections.community.general.plugins.lookup.consul_kv.open_url",
side_effect=_not_found(),
):
result = self.lookup.run(["somekey"])
self.assertEqual(result, [])
def test_null_value_default_empty_value(self):
with patch(
"ansible_collections.community.general.plugins.lookup.consul_kv.open_url",
return_value=_response([_entry(None)]),
):
result = self.lookup.run(["somekey"])
self.assertEqual(result, ["None"])
def test_null_value_python_none(self):
with patch(
"ansible_collections.community.general.plugins.lookup.consul_kv.open_url",
return_value=_response([_entry(None)]),
):
result = self.lookup.run(["somekey"], empty_value="python_none")
self.assertEqual(result, [None])
def test_url_option_overrides_host_port_scheme(self):
with patch(
"ansible_collections.community.general.plugins.lookup.consul_kv.open_url",
return_value=_response([_entry("somevalue")]),
) as open_url:
self.lookup.run(["somekey"], url="https://consul.example.com:9500")
self.assertEqual(open_url.call_args.args[0], "https://consul.example.com:9500/v1/kv/somekey")
@@ -0,0 +1,38 @@
# Copyright (c) 2020-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
from unittest import TestCase
from ansible.plugins.loader import lookup_loader
from ansible.template import Templar
from ansible_collections.community.internal_test_tools.tests.unit.utils.trust import make_trusted
class TestLookupModule(TestCase):
def setUp(self):
templar = Templar(loader=None)
self.lookup = lookup_loader.get("community.general.dependent", templar=templar)
def test_empty(self):
self.assertListEqual(self.lookup.run([], None), [])
def test_simple(self):
self.assertListEqual(
self.lookup.run(
[
{"a": make_trusted("[1, 2]")},
{"b": make_trusted("[item.a + 3, item.a + 6]")},
{"c": make_trusted("[item.a + item.b * 10]")},
],
{},
),
[
{"a": 1, "b": 4, "c": 41},
{"a": 1, "b": 7, "c": 71},
{"a": 2, "b": 5, "c": 52},
{"a": 2, "b": 8, "c": 82},
],
)
@@ -0,0 +1,46 @@
# Copyright (c) 2020, Adam Migus <adam@migus.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
from unittest import TestCase
from unittest.mock import (
MagicMock,
patch,
)
from ansible.plugins.loader import lookup_loader
from ansible_collections.community.general.plugins.lookup import dsv
class MockSecretsVault(MagicMock):
RESPONSE = '{"foo": "bar"}'
def get_secret_json(self, path):
return self.RESPONSE
class TestLookupModule(TestCase):
def setUp(self):
dsv.sdk_is_missing = False
self.lookup = lookup_loader.get("community.general.dsv")
@patch(
"ansible_collections.community.general.plugins.lookup.dsv.LookupModule.Client",
MockSecretsVault(),
)
def test_get_secret_json(self):
self.assertListEqual(
[MockSecretsVault.RESPONSE],
self.lookup.run(
["/dummy"],
[],
**{
"tenant": "dummy",
"client_id": "dummy",
"client_secret": "dummy",
},
),
)
@@ -0,0 +1,52 @@
#
# Copyright (c) 2020, SCC France, Eric Belhomme <ebelhomme@fr.scc.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 unittest
from unittest.mock import MagicMock, patch
from ansible.plugins.loader import lookup_loader
from ansible_collections.community.general.plugins.lookup import etcd3
class FakeKVMetadata:
def __init__(self, keyvalue, header):
self.key = keyvalue
self.create_revision = ""
self.mod_revision = ""
self.version = ""
self.lease_id = ""
self.response_header = header
class FakeEtcd3Client(MagicMock):
def get_prefix(self, key):
for i in range(1, 4):
yield self.get(f"{key}_{i}")
def get(self, key):
return (f"{key} value", FakeKVMetadata(key, None))
class TestLookupModule(unittest.TestCase):
def setUp(self):
etcd3.HAS_ETCD = True
self.lookup = lookup_loader.get("community.general.etcd3")
@patch("ansible_collections.community.general.plugins.lookup.etcd3.etcd3_client", FakeEtcd3Client())
def test_key(self):
expected_result = [{"key": "a_key", "value": "a_key value"}]
self.assertListEqual(expected_result, self.lookup.run(["a_key"], []))
@patch("ansible_collections.community.general.plugins.lookup.etcd3.etcd3_client", FakeEtcd3Client())
def test_key_prefix(self):
expected_result = [
{"key": "a_key_1", "value": "a_key_1 value"},
{"key": "a_key_2", "value": "a_key_2 value"},
{"key": "a_key_3", "value": "a_key_3 value"},
]
self.assertListEqual(expected_result, self.lookup.run(["a_key"], [], **{"prefix": True}))
@@ -0,0 +1,154 @@
# Copyright (c) 2023, Poh Wei Sheng <weisheng-p@hotmail.sg>
# 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 json
import types
import unittest
from unittest.mock import (
MagicMock,
mock_open,
patch,
)
from ansible.plugins.loader import lookup_loader
ENCODE_RESULT = "Foobar"
PRIVATE_KEY = "private_key"
class MockJWT(MagicMock):
def encode(self, payload, key, alg):
return ENCODE_RESULT
class serialization(MagicMock):
def load_pem_private_key(self, key_bytes, password):
return PRIVATE_KEY
class MockResponse(MagicMock):
response_token = "Bar"
def read(self):
return json.dumps(
{
"token": self.response_token,
}
).encode("utf-8")
class TestLookupModule(unittest.TestCase):
def test_get_token_with_file_with_pyjwt(self):
pyjwt = types.ModuleType("jwt")
pyjwt.encode = MagicMock(return_value=ENCODE_RESULT)
with (
patch.multiple(
"ansible_collections.community.general.plugins.lookup.github_app_access_token",
create=True,
open=mock_open(read_data="foo_bar"),
open_url=MagicMock(return_value=MockResponse()),
jwt=pyjwt,
HAS_JWT=True,
HAS_PYTHON_JWT=False,
HAS_CRYPTOGRAPHY=True,
serialization=serialization(),
),
):
lookup = lookup_loader.get("community.general.github_app_access_token")
self.assertListEqual(
[MockResponse.response_token],
lookup.run([], key_path="key", app_id="app_id", installation_id="installation_id", token_expiry=600),
)
def test_get_token_with_fact_with_pyjwt(self):
pyjwt = types.ModuleType("jwt")
pyjwt.encode = MagicMock(return_value=ENCODE_RESULT)
with (
patch.multiple(
"ansible_collections.community.general.plugins.lookup.github_app_access_token",
create=True,
open=mock_open(read_data="foo_bar"),
open_url=MagicMock(return_value=MockResponse()),
jwt=pyjwt,
HAS_JWT=True,
HAS_PYTHON_JWT=False,
HAS_CRYPTOGRAPHY=True,
serialization=serialization(),
),
):
lookup = lookup_loader.get("community.general.github_app_access_token")
self.assertListEqual(
[MockResponse.response_token],
lookup.run(
[], app_id="app_id", installation_id="installation_id", private_key="foo_bar", token_expiry=600
),
)
def test_get_token_with_python_jwt(self):
with (
patch.multiple(
"ansible_collections.community.general.plugins.lookup.github_app_access_token",
create=True,
open=mock_open(read_data="foo_bar"),
open_url=MagicMock(return_value=MockResponse()),
HAS_JWT=True,
HAS_PYTHON_JWT=True,
jwk_from_pem=MagicMock(return_value="private_key"),
jwt_instance=MockJWT(),
),
):
lookup = lookup_loader.get("community.general.github_app_access_token")
self.assertListEqual(
[MockResponse.response_token],
lookup.run([], key_path="key", app_id="app_id", installation_id="installation_id", token_expiry=600),
)
def test_get_token_with_fact_with_python_jwt(self):
with (
patch.multiple(
"ansible_collections.community.general.plugins.lookup.github_app_access_token",
create=True,
open=mock_open(read_data="foo_bar"),
open_url=MagicMock(return_value=MockResponse()),
HAS_JWT=True,
HAS_PYTHON_JWT=True,
jwk_from_pem=MagicMock(return_value="private_key"),
jwt_instance=MockJWT(),
),
):
lookup = lookup_loader.get("community.general.github_app_access_token")
self.assertListEqual(
[MockResponse.response_token],
lookup.run(
[], app_id="app_id", installation_id="installation_id", private_key="foo_bar", token_expiry=600
),
)
def test_get_token_with_client_id_alias(mocker):
pyjwt = types.ModuleType("jwt")
encode_mock = MagicMock(return_value=ENCODE_RESULT)
pyjwt.encode = encode_mock
module = "ansible_collections.community.general.plugins.lookup.github_app_access_token"
mocker.patch.multiple(
module,
create=True,
open=mock_open(read_data="foo_bar"),
open_url=MagicMock(return_value=MockResponse()),
jwt=pyjwt,
HAS_JWT=True,
HAS_PYTHON_JWT=False,
HAS_CRYPTOGRAPHY=True,
serialization=serialization(),
)
lookup = lookup_loader.get("community.general.github_app_access_token")
result = lookup.run(
[], key_path="key", client_id="Iv1.a1b2c3d4e5f6g7h8", installation_id="installation_id", token_expiry=600
)
assert result == [MockResponse.response_token]
assert encode_mock.call_args.args[0]["iss"] == "Iv1.a1b2c3d4e5f6g7h8"
@@ -0,0 +1,170 @@
# Copyright (c) 2016 Andrew Zenk <azenk@umn.edu>
# 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 unittest
from argparse import ArgumentParser
from unittest.mock import patch
from ansible.errors import AnsibleError
from ansible.plugins.loader import lookup_loader
from ansible_collections.community.general.plugins.lookup.lastpass import LPass, LPassException
MOCK_ENTRIES = [
{
"username": "user",
"name": "Mock Entry",
"password": "t0pS3cret passphrase entry!",
"url": "https://localhost/login",
"notes": "Test\nnote with multiple lines.\n",
"id": "0123456789",
}
]
class MockLPass(LPass):
_mock_logged_out = False
_mock_disconnected = False
def _lookup_mock_entry(self, key):
for entry in MOCK_ENTRIES:
if key == entry["id"] or key == entry["name"]:
return entry
def _run(self, args, stdin=None, expected_rc=0):
# Mock behavior of lpass executable
base_options = ArgumentParser(add_help=False)
base_options.add_argument("--color", default="auto", choices=["auto", "always", "never"])
p = ArgumentParser()
sp = p.add_subparsers(help="command", dest="subparser_name")
sp.add_parser("logout", parents=[base_options], help="logout")
show_p = sp.add_parser("show", parents=[base_options], help="show entry details")
field_group = show_p.add_mutually_exclusive_group(required=True)
for field in MOCK_ENTRIES[0].keys():
field_group.add_argument(f"--{field}", default=False, action="store_true")
field_group.add_argument("--field", default=None)
show_p.add_argument("selector", help="Unique Name or ID")
args = p.parse_args(args)
def mock_exit(output="", error="", rc=0):
if rc != expected_rc:
raise LPassException(error)
return output, error
if args.color != "never":
return mock_exit(error="Error: Mock only supports --color=never", rc=1)
if args.subparser_name == "logout":
if self._mock_logged_out:
return mock_exit(error="Error: Not currently logged in", rc=1)
logged_in_error = "Are you sure you would like to log out? [Y/n]"
if stdin and stdin.lower() == "n\n":
return mock_exit(output="Log out: aborted.", error=logged_in_error, rc=1)
elif stdin and stdin.lower() == "y\n":
return mock_exit(output="Log out: complete.", error=logged_in_error, rc=0)
else:
return mock_exit(error="Error: aborted response", rc=1)
if args.subparser_name == "show":
if self._mock_logged_out:
return mock_exit(
error="Error: Could not find decryption key. Perhaps you need to login with `lpass login`.", rc=1
)
if self._mock_disconnected:
return mock_exit(error="Error: Couldn't resolve host name.", rc=1)
mock_entry = self._lookup_mock_entry(args.selector)
if args.field:
return mock_exit(output=mock_entry.get(args.field, ""))
elif args.password:
return mock_exit(output=mock_entry.get("password", ""))
elif args.username:
return mock_exit(output=mock_entry.get("username", ""))
elif args.url:
return mock_exit(output=mock_entry.get("url", ""))
elif args.name:
return mock_exit(output=mock_entry.get("name", ""))
elif args.id:
return mock_exit(output=mock_entry.get("id", ""))
elif args.notes:
return mock_exit(output=mock_entry.get("notes", ""))
raise LPassException("We should never get here")
class DisconnectedMockLPass(MockLPass):
_mock_disconnected = True
class LoggedOutMockLPass(MockLPass):
_mock_logged_out = True
class TestLPass(unittest.TestCase):
def setUp(self):
self.lookup = lookup_loader.get("community.general.lastpass")
def test_lastpass_cli_path(self):
lp = MockLPass(path="/dev/null")
self.assertEqual("/dev/null", lp.cli_path)
def test_lastpass_build_args_logout(self):
lp = MockLPass()
self.assertEqual(["logout", "--color=never"], lp._build_args("logout"))
def test_lastpass_logged_in_true(self):
lp = MockLPass()
self.assertTrue(lp.logged_in)
def test_lastpass_logged_in_false(self):
lp = LoggedOutMockLPass()
self.assertFalse(lp.logged_in)
def test_lastpass_show_disconnected(self):
lp = DisconnectedMockLPass()
with self.assertRaises(LPassException):
lp.get_field("0123456789", "username")
def test_lastpass_show(self):
lp = MockLPass()
for entry in MOCK_ENTRIES:
entry_id = entry.get("id")
for k, v in entry.items():
self.assertEqual(v.strip(), lp.get_field(entry_id, k))
class TestLastpassPlugin(unittest.TestCase):
def setUp(self):
self.lookup = lookup_loader.get("community.general.lastpass")
@patch("ansible_collections.community.general.plugins.lookup.lastpass.LPass", new=MockLPass)
def test_lastpass_plugin_normal(self):
for entry in MOCK_ENTRIES:
entry_id = entry.get("id")
for k, v in entry.items():
self.assertEqual(v.strip(), self.lookup.run([entry_id], field=k)[0])
@patch("ansible_collections.community.general.plugins.lookup.lastpass.LPass", LoggedOutMockLPass)
def test_lastpass_plugin_logged_out(self):
entry = MOCK_ENTRIES[0]
entry_id = entry.get("id")
with self.assertRaises(AnsibleError):
self.lookup.run([entry_id], field="password")
@patch("ansible_collections.community.general.plugins.lookup.lastpass.LPass", DisconnectedMockLPass)
def test_lastpass_plugin_disconnected(self):
entry = MOCK_ENTRIES[0]
entry_id = entry.get("id")
with self.assertRaises(AnsibleError):
self.lookup.run([entry_id], field="password")
@@ -0,0 +1,699 @@
# Copyright (c) 2020, Thales Netherlands
# 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
import unittest
from copy import deepcopy
from unittest.mock import patch
from ansible.errors import AnsibleError
from ansible.plugins import AnsiblePlugin
from ansible.template import Templar
from ansible.utils.display import Display
from ansible_collections.community.internal_test_tools.tests.unit.mock.loader import DictDataLoader
from ansible_collections.community.general.plugins.lookup import merge_variables
merge_hash_data = {
"low_dict": {"a": {"a": {"x": "low_value", "y": "low_value", "list": ["low_value"]}}, "b": [1, 1, 2, 3]},
"high_dict": {
"a": {"a": {"y": "high_value", "z": "high_value", "list": ["high_value"]}},
"b": [3, 4, 4, {"5": "value"}],
},
}
class TestMergeVariablesLookup(unittest.TestCase):
class HostVarsMock(dict):
def __getattr__(self, item):
return super().__getitem__(item)
def __setattr__(self, item, value):
return super().__setitem__(item, value)
def raw_get(self, host):
return super().__getitem__(host)
def setUp(self):
self.loader = DictDataLoader({})
self.templar = Templar(loader=self.loader, variables={})
self.merge_vars_lookup = merge_variables.LookupModule(loader=self.loader, templar=self.templar)
@patch.object(AnsiblePlugin, "set_options")
@patch.object(
AnsiblePlugin,
"get_option",
side_effect=[None, "ignore", "suffix", None, "deep", "append", "replace", "replace", []],
)
@patch.object(Templar, "template", side_effect=[["item1"], ["item3"]])
def test_merge_list(self, mock_set_options, mock_get_option, mock_template):
results = self.merge_vars_lookup.run(
["__merge_list"],
{"testlist1__merge_list": ["item1"], "testlist2": ["item2"], "testlist3__merge_list": ["item3"]},
)
self.assertEqual(results, [["item1", "item3"]])
@patch.object(AnsiblePlugin, "set_options")
@patch.object(
AnsiblePlugin,
"get_option",
side_effect=[["initial_item"], "ignore", "suffix", None, "deep", "append", "replace", "replace", []],
)
@patch.object(Templar, "template", side_effect=[["item1"], ["item3"]])
def test_merge_list_with_initial_value(self, mock_set_options, mock_get_option, mock_template):
results = self.merge_vars_lookup.run(
["__merge_list"],
{"testlist1__merge_list": ["item1"], "testlist2": ["item2"], "testlist3__merge_list": ["item3"]},
)
self.assertEqual(results, [["initial_item", "item1", "item3"]])
@patch.object(AnsiblePlugin, "set_options")
@patch.object(
AnsiblePlugin,
"get_option",
side_effect=[None, "ignore", "suffix", None, "deep", "append", "replace", "replace", []],
)
@patch.object(
Templar,
"template",
side_effect=[{"item1": "test", "list_item": ["test1"]}, {"item2": "test", "list_item": ["test2"]}],
)
def test_merge_dict(self, mock_set_options, mock_get_option, mock_template):
results = self.merge_vars_lookup.run(
["__merge_dict"],
{
"testdict1__merge_dict": {"item1": "test", "list_item": ["test1"]},
"testdict2__merge_dict": {"item2": "test", "list_item": ["test2"]},
},
)
self.assertEqual(results, [{"item1": "test", "item2": "test", "list_item": ["test1", "test2"]}])
@patch.object(AnsiblePlugin, "set_options")
@patch.object(
AnsiblePlugin,
"get_option",
side_effect=[
{"initial_item": "random value", "list_item": ["test0"]},
"ignore",
"suffix",
None,
"deep",
"append",
"replace",
"replace",
[],
],
)
@patch.object(
Templar,
"template",
side_effect=[{"item1": "test", "list_item": ["test1"]}, {"item2": "test", "list_item": ["test2"]}],
)
def test_merge_dict_with_initial_value(self, mock_set_options, mock_get_option, mock_template):
results = self.merge_vars_lookup.run(
["__merge_dict"],
{
"testdict1__merge_dict": {"item1": "test", "list_item": ["test1"]},
"testdict2__merge_dict": {"item2": "test", "list_item": ["test2"]},
},
)
self.assertEqual(
results,
[
{
"initial_item": "random value",
"item1": "test",
"item2": "test",
"list_item": ["test0", "test1", "test2"],
}
],
)
@patch.object(AnsiblePlugin, "set_options")
@patch.object(
AnsiblePlugin,
"get_option",
side_effect=[None, "warn", "suffix", None, "deep", "append", "replace", "replace", []],
)
@patch.object(Templar, "template", side_effect=[{"item": "value1"}, {"item": "value2"}])
@patch.object(Display, "warning")
def test_merge_dict_non_unique_warning(self, mock_set_options, mock_get_option, mock_template, mock_display):
results = self.merge_vars_lookup.run(
["__merge_non_unique"],
{"testdict1__merge_non_unique": {"item": "value1"}, "testdict2__merge_non_unique": {"item": "value2"}},
)
self.assertTrue(mock_display.called)
self.assertEqual(results, [{"item": "value2"}])
@patch.object(AnsiblePlugin, "set_options")
@patch.object(
AnsiblePlugin,
"get_option",
side_effect=[None, "error", "suffix", None, "deep", "append", "replace", "replace", []],
)
@patch.object(Templar, "template", side_effect=[{"item": "value1"}, {"item": "value2"}])
def test_merge_dict_non_unique_error(self, mock_set_options, mock_get_option, mock_template):
with self.assertRaises(AnsibleError):
self.merge_vars_lookup.run(
["__merge_non_unique"],
{"testdict1__merge_non_unique": {"item": "value1"}, "testdict2__merge_non_unique": {"item": "value2"}},
)
@patch.object(AnsiblePlugin, "set_options")
@patch.object(
AnsiblePlugin,
"get_option",
side_effect=[None, "ignore", "suffix", None, "deep", "append", "replace", "replace", []],
)
@patch.object(Templar, "template", side_effect=[{"item1": "test", "list_item": ["test1"]}, ["item2", "item3"]])
def test_merge_list_and_dict(self, mock_set_options, mock_get_option, mock_template):
with self.assertRaises(AnsibleError):
self.merge_vars_lookup.run(
["__merge_var"],
{
"testlist__merge_var": {"item1": "test", "list_item": ["test1"]},
"testdict__merge_var": ["item2", "item3"],
},
)
@patch.object(AnsiblePlugin, "set_options")
@patch.object(
AnsiblePlugin,
"get_option",
side_effect=[None, "ignore", "suffix", ["all"], "deep", "append", "replace", "replace", []],
)
@patch.object(
Templar,
"template",
side_effect=[
{"var": [{"item1": "value1", "item2": "value2"}]},
{"var": [{"item5": "value5", "item6": "value6"}]},
],
)
def test_merge_dict_group_all(self, mock_set_options, mock_get_option, mock_template):
hostvars = self.HostVarsMock(
{
"host1": {
"group_names": ["dummy1"],
"inventory_hostname": "host1",
"1testlist__merge_var": {"var": [{"item1": "value1", "item2": "value2"}]},
},
"host2": {
"group_names": ["dummy1"],
"inventory_hostname": "host2",
"2otherlist__merge_var": {"var": [{"item5": "value5", "item6": "value6"}]},
},
}
)
variables = {"inventory_hostname": "host1", "hostvars": hostvars}
results = self.merge_vars_lookup.run(["__merge_var"], variables)
self.assertEqual(
results, [{"var": [{"item1": "value1", "item2": "value2"}, {"item5": "value5", "item6": "value6"}]}]
)
@patch.object(AnsiblePlugin, "set_options")
@patch.object(
AnsiblePlugin,
"get_option",
side_effect=[None, "ignore", "suffix", ["dummy1"], "deep", "append", "replace", "replace", []],
)
@patch.object(
Templar,
"template",
side_effect=[
{"var": [{"item1": "value1", "item2": "value2"}]},
{"var": [{"item5": "value5", "item6": "value6"}]},
],
)
def test_merge_dict_group_single(self, mock_set_options, mock_get_option, mock_template):
hostvars = self.HostVarsMock(
{
"host1": {
"group_names": ["dummy1"],
"inventory_hostname": "host1",
"1testlist__merge_var": {"var": [{"item1": "value1", "item2": "value2"}]},
},
"host2": {
"group_names": ["dummy1"],
"inventory_hostname": "host2",
"2otherlist__merge_var": {"var": [{"item5": "value5", "item6": "value6"}]},
},
"host3": {
"group_names": ["dummy2"],
"inventory_hostname": "host3",
"3otherlist__merge_var": {"var": [{"item3": "value3", "item4": "value4"}]},
},
}
)
variables = {"inventory_hostname": "host1", "hostvars": hostvars}
results = self.merge_vars_lookup.run(["__merge_var"], variables)
self.assertEqual(
results, [{"var": [{"item1": "value1", "item2": "value2"}, {"item5": "value5", "item6": "value6"}]}]
)
@patch.object(AnsiblePlugin, "set_options")
@patch.object(
AnsiblePlugin,
"get_option",
side_effect=[None, "ignore", "suffix", ["dummy1", "dummy2"], "deep", "append", "replace", "replace", []],
)
@patch.object(
Templar,
"template",
side_effect=[
{"var": [{"item1": "value1", "item2": "value2"}]},
{"var": [{"item5": "value5", "item6": "value6"}]},
],
)
def test_merge_dict_group_multiple(self, mock_set_options, mock_get_option, mock_template):
hostvars = self.HostVarsMock(
{
"host1": {
"group_names": ["dummy1"],
"inventory_hostname": "host1",
"1testlist__merge_var": {"var": [{"item1": "value1", "item2": "value2"}]},
},
"host2": {
"group_names": ["dummy2"],
"inventory_hostname": "host2",
"2otherlist__merge_var": {"var": [{"item5": "value5", "item6": "value6"}]},
},
"host3": {
"group_names": ["dummy3"],
"inventory_hostname": "host3",
"3otherlist__merge_var": {"var": [{"item3": "value3", "item4": "value4"}]},
},
}
)
variables = {"inventory_hostname": "host1", "hostvars": hostvars}
results = self.merge_vars_lookup.run(["__merge_var"], variables)
self.assertEqual(
results, [{"var": [{"item1": "value1", "item2": "value2"}, {"item5": "value5", "item6": "value6"}]}]
)
@patch.object(AnsiblePlugin, "set_options")
@patch.object(
AnsiblePlugin,
"get_option",
side_effect=[None, "ignore", "suffix", ["dummy1", "dummy2"], "deep", "append", "replace", "replace", []],
)
@patch.object(
Templar,
"template",
side_effect=[
["item1"],
["item5"],
],
)
def test_merge_list_group_multiple(self, mock_set_options, mock_get_option, mock_template):
hostvars = self.HostVarsMock(
{
"host1": {"group_names": ["dummy1"], "inventory_hostname": "host1", "1testlist__merge_var": ["item1"]},
"host2": {"group_names": ["dummy2"], "inventory_hostname": "host2", "2otherlist__merge_var": ["item5"]},
"host3": {"group_names": ["dummy3"], "inventory_hostname": "host3", "3otherlist__merge_var": ["item3"]},
}
)
variables = {"inventory_hostname": "host1", "hostvars": hostvars}
results = self.merge_vars_lookup.run(["__merge_var"], variables)
self.assertEqual(results, [["item1", "item5"]])
@patch.object(AnsiblePlugin, "set_options")
@patch.object(
AnsiblePlugin,
"get_option",
side_effect=[None, "ignore", "suffix", None, "shallow", "replace", "replace", "replace", []],
)
@patch.object(
Templar, "template", side_effect=[deepcopy(merge_hash_data["low_dict"]), deepcopy(merge_hash_data["high_dict"])]
)
def test_merge_dict_shallow_and_list_replace(self, mock_set_options, mock_get_option, mock_template):
results = self.merge_vars_lookup.run(
["__merge_dict_shallow_and_list_replace"],
{
"testdict1__merge_dict_shallow_and_list_replace": merge_hash_data["low_dict"],
"testdict2__merge_dict_shallow_and_list_replace": merge_hash_data["high_dict"],
},
)
self.assertEqual(results, [merge_hash_data["high_dict"]])
@patch.object(AnsiblePlugin, "set_options")
@patch.object(
AnsiblePlugin,
"get_option",
side_effect=[None, "ignore", "suffix", None, "shallow", "keep", "replace", "replace", []],
)
@patch.object(
Templar, "template", side_effect=[deepcopy(merge_hash_data["low_dict"]), deepcopy(merge_hash_data["high_dict"])]
)
def test_merge_dict_shallow_and_list_keep(self, mock_set_options, mock_get_option, mock_template):
results = self.merge_vars_lookup.run(
["__merge_dict_shallow_and_list_keep"],
{
"testdict1__merge_dict_shallow_and_list_keep": merge_hash_data["low_dict"],
"testdict2__merge_dict_shallow_and_list_keep": merge_hash_data["high_dict"],
},
)
self.assertEqual(results, [{"a": merge_hash_data["high_dict"]["a"], "b": merge_hash_data["low_dict"]["b"]}])
@patch.object(AnsiblePlugin, "set_options")
@patch.object(
AnsiblePlugin,
"get_option",
side_effect=[None, "ignore", "suffix", None, "shallow", "append", "replace", "replace", []],
)
@patch.object(
Templar, "template", side_effect=[deepcopy(merge_hash_data["low_dict"]), deepcopy(merge_hash_data["high_dict"])]
)
def test_merge_dict_shallow_and_list_append(self, mock_set_options, mock_get_option, mock_template):
results = self.merge_vars_lookup.run(
["__merge_dict_shallow_and_list_append"],
{
"testdict1__merge_dict_shallow_and_list_append": merge_hash_data["low_dict"],
"testdict2__merge_dict_shallow_and_list_append": merge_hash_data["high_dict"],
},
)
self.assertEqual(
results,
[
{
"a": merge_hash_data["high_dict"]["a"],
"b": merge_hash_data["low_dict"]["b"] + merge_hash_data["high_dict"]["b"],
}
],
)
@patch.object(AnsiblePlugin, "set_options")
@patch.object(
AnsiblePlugin,
"get_option",
side_effect=[None, "ignore", "suffix", None, "shallow", "prepend", "replace", "replace", []],
)
@patch.object(
Templar, "template", side_effect=[deepcopy(merge_hash_data["low_dict"]), deepcopy(merge_hash_data["high_dict"])]
)
def test_merge_dict_shallow_and_list_prepend(self, mock_set_options, mock_get_option, mock_template):
results = self.merge_vars_lookup.run(
["__merge_dict_shallow_and_list_prepend"],
{
"testdict1__merge_dict_shallow_and_list_prepend": merge_hash_data["low_dict"],
"testdict2__merge_dict_shallow_and_list_prepend": merge_hash_data["high_dict"],
},
)
self.assertEqual(
results,
[
{
"a": merge_hash_data["high_dict"]["a"],
"b": merge_hash_data["high_dict"]["b"] + merge_hash_data["low_dict"]["b"],
}
],
)
@patch.object(AnsiblePlugin, "set_options")
@patch.object(
AnsiblePlugin,
"get_option",
side_effect=[None, "ignore", "suffix", None, "deep", "replace", "replace", "replace", []],
)
@patch.object(
Templar, "template", side_effect=[deepcopy(merge_hash_data["low_dict"]), deepcopy(merge_hash_data["high_dict"])]
)
def test_merge_dict_deep_and_list_replace(self, mock_set_options, mock_get_option, mock_template):
results = self.merge_vars_lookup.run(
["__merge_dict_deep_and_list_replace"],
{
"testdict1__merge_dict_deep_and_list_replace": merge_hash_data["low_dict"],
"testdict2__merge_dict_deep_and_list_replace": merge_hash_data["high_dict"],
},
)
self.assertEqual(
results,
[
{
"a": {"a": {"x": "low_value", "y": "high_value", "z": "high_value", "list": ["high_value"]}},
"b": merge_hash_data["high_dict"]["b"],
}
],
)
@patch.object(AnsiblePlugin, "set_options")
@patch.object(
AnsiblePlugin,
"get_option",
side_effect=[None, "ignore", "suffix", None, "deep", "keep", "replace", "replace", []],
)
@patch.object(
Templar, "template", side_effect=[deepcopy(merge_hash_data["low_dict"]), deepcopy(merge_hash_data["high_dict"])]
)
def test_merge_dict_deep_and_list_keep(self, mock_set_options, mock_get_option, mock_template):
results = self.merge_vars_lookup.run(
["__merge_dict_deep_and_list_keep"],
{
"testdict1__merge_dict_deep_and_list_keep": merge_hash_data["low_dict"],
"testdict2__merge_dict_deep_and_list_keep": merge_hash_data["high_dict"],
},
)
self.assertEqual(
results,
[
{
"a": {"a": {"x": "low_value", "y": "high_value", "z": "high_value", "list": ["low_value"]}},
"b": merge_hash_data["low_dict"]["b"],
}
],
)
@patch.object(AnsiblePlugin, "set_options")
@patch.object(
AnsiblePlugin,
"get_option",
side_effect=[None, "ignore", "suffix", None, "deep", "append", "replace", "replace", []],
)
@patch.object(
Templar, "template", side_effect=[deepcopy(merge_hash_data["low_dict"]), deepcopy(merge_hash_data["high_dict"])]
)
def test_merge_dict_deep_and_list_append(self, mock_set_options, mock_get_option, mock_template):
results = self.merge_vars_lookup.run(
["__merge_dict_deep_and_list_append"],
{
"testdict1__merge_dict_deep_and_list_append": merge_hash_data["low_dict"],
"testdict2__merge_dict_deep_and_list_append": merge_hash_data["high_dict"],
},
)
self.assertEqual(
results,
[
{
"a": {
"a": {
"x": "low_value",
"y": "high_value",
"z": "high_value",
"list": ["low_value", "high_value"],
}
},
"b": merge_hash_data["low_dict"]["b"] + merge_hash_data["high_dict"]["b"],
}
],
)
@patch.object(AnsiblePlugin, "set_options")
@patch.object(
AnsiblePlugin,
"get_option",
side_effect=[None, "ignore", "suffix", None, "deep", "prepend", "replace", "replace", []],
)
@patch.object(
Templar, "template", side_effect=[deepcopy(merge_hash_data["low_dict"]), deepcopy(merge_hash_data["high_dict"])]
)
def test_merge_dict_deep_and_list_prepend(self, mock_set_options, mock_get_option, mock_template):
results = self.merge_vars_lookup.run(
["__merge_dict_deep_and_list_prepend"],
{
"testdict1__merge_dict_deep_and_list_prepend": merge_hash_data["low_dict"],
"testdict2__merge_dict_deep_and_list_prepend": merge_hash_data["high_dict"],
},
)
self.assertEqual(
results,
[
{
"a": {
"a": {
"x": "low_value",
"y": "high_value",
"z": "high_value",
"list": ["high_value", "low_value"],
}
},
"b": merge_hash_data["high_dict"]["b"] + merge_hash_data["low_dict"]["b"],
}
],
)
@patch.object(AnsiblePlugin, "set_options")
@patch.object(
AnsiblePlugin,
"get_option",
side_effect=[None, "ignore", "suffix", None, "replace", "append", "keep", "keep", []],
)
@patch.object(
Templar, "template", side_effect=[deepcopy(merge_hash_data["low_dict"]), deepcopy(merge_hash_data["high_dict"])]
)
def test_merge_dict_replace(self, mock_set_options, mock_get_option, mock_template):
results = self.merge_vars_lookup.run(
["__merge_dict_replace"],
{
"testdict1__merge_dict_replace": merge_hash_data["low_dict"],
"testdict2__merge_dict_replace": merge_hash_data["high_dict"],
},
)
self.assertEqual(results, [merge_hash_data["high_dict"]])
@patch.object(AnsiblePlugin, "set_options")
@patch.object(
AnsiblePlugin,
"get_option",
side_effect=[None, "ignore", "suffix", None, "keep", "append", "replace", "replace", []],
)
@patch.object(
Templar, "template", side_effect=[deepcopy(merge_hash_data["low_dict"]), deepcopy(merge_hash_data["high_dict"])]
)
def test_merge_dict_keep(self, mock_set_options, mock_get_option, mock_template):
results = self.merge_vars_lookup.run(
["__merge_dict_keep"],
{
"testdict1__merge_dict_keep": merge_hash_data["low_dict"],
"testdict2__merge_dict_keep": merge_hash_data["high_dict"],
},
)
self.assertEqual(results, [merge_hash_data["low_dict"]])
@patch.object(AnsiblePlugin, "set_options")
@patch.object(
AnsiblePlugin,
"get_option",
side_effect=[None, "ignore", "suffix", None, "deep", "merge", "replace", "replace", []],
)
@patch.object(
Templar,
"template",
side_effect=[[{"a": "b", "c": "d"}, {"c": "d"}], [{"a": "x", "y": "z"}, {"c": "z"}, {"a": "y"}]],
)
def test_merge_list_deep(self, mock_set_options, mock_get_option, mock_template):
results = self.merge_vars_lookup.run(
["__merge_list_deep"],
{
"testdict1__merge_list_deep": [{"a": "b", "c": "d"}, {"c": "d"}],
"testdict2__merge_list_deep": [{"a": "x", "y": "z"}, {"c": "z"}, {"a": "y"}],
},
)
self.assertEqual(results, [[{"a": "x", "c": "d", "y": "z"}, {"c": "z"}, {"a": "y"}]])
@patch.object(AnsiblePlugin, "set_options")
@patch.object(
AnsiblePlugin,
"get_option",
side_effect=[None, "ignore", "suffix", None, "deep", "append", "replace", "replace", ["dedup"]],
)
@patch.object(
Templar, "template", side_effect=[deepcopy(merge_hash_data["low_dict"]), deepcopy(merge_hash_data["high_dict"])]
)
def test_merge_dict_deep_and_list_append_with_dedup_keep_first(
self, mock_set_options, mock_get_option, mock_template
):
results = self.merge_vars_lookup.run(
["__merge_dict_deep_and_list_append_with_dedup_keep_first"],
{
"testdict1__merge_dict_deep_and_list_append_with_dedup_keep_first": merge_hash_data["low_dict"],
"testdict2__merge_dict_deep_and_list_append_with_dedup_keep_first": merge_hash_data["high_dict"],
},
)
self.assertEqual(
results,
[
{
"a": {
"a": {
"x": "low_value",
"y": "high_value",
"z": "high_value",
"list": ["low_value", "high_value"],
}
},
"b": [1, 2, 3, 4, {"5": "value"}],
}
],
)
@patch.object(AnsiblePlugin, "set_options")
@patch.object(
AnsiblePlugin,
"get_option",
side_effect=[
None,
"ignore",
"suffix",
None,
"deep",
"prepend",
"replace",
"replace",
[{"name": "dedup", "options": {"keep": "last"}}],
],
)
@patch.object(
Templar, "template", side_effect=[deepcopy(merge_hash_data["low_dict"]), deepcopy(merge_hash_data["high_dict"])]
)
def test_merge_dict_deep_and_list_prepend_with_dedup_keep_last(
self, mock_set_options, mock_get_option, mock_template
):
results = self.merge_vars_lookup.run(
["__merge_dict_deep_and_list_prepend_with_dedup_keep_last"],
{
"testdict1__merge_dict_deep_and_list_prepend_with_dedup_keep_last": merge_hash_data["low_dict"],
"testdict2__merge_dict_deep_and_list_prepend_with_dedup_keep_last": merge_hash_data["high_dict"],
},
)
self.assertEqual(
results,
[
{
"a": {
"a": {
"x": "low_value",
"y": "high_value",
"list": ["high_value", "low_value"],
"z": "high_value",
}
},
"b": [4, {"5": "value"}, 1, 2, 3],
}
],
)
@@ -0,0 +1,300 @@
# Copyright (c) 2022 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
import itertools
import json
import operator
import pytest
from ansible.errors import AnsibleOptionsError
from ansible.plugins.loader import lookup_loader
from ansible_collections.community.general.plugins.module_utils._onepassword_cli import (
OnePassCLIv2,
OnePasswordError,
)
from .onepassword_common import MOCK_ENTRIES
OP_VERSION_FIXTURES = ["opv2"]
@pytest.mark.parametrize(
("args", "out", "expected_call_args", "expected_call_kwargs", "expected"),
(
(
[],
"list of accounts",
["account", "get"],
{"ignore_errors": True},
True,
),
(
["acme"],
"list of accounts",
["account", "get", "--account", "acme.1password.com"],
{"ignore_errors": True},
True,
),
(
[],
"",
["account", "list"],
{},
False,
),
),
)
def test_assert_logged_in_v2(mocker, args, out, expected_call_args, expected_call_kwargs, expected):
mocker.patch.object(OnePassCLIv2, "_run", return_value=[0, out, ""])
op_cli = OnePassCLIv2(*args)
result = op_cli.assert_logged_in()
op_cli._run.assert_called_with(expected_call_args, **expected_call_kwargs)
assert result == expected
def test_assert_logged_in_v2_connect():
op_cli = OnePassCLIv2(connect_host="http://localhost:8080", connect_token="foobar")
result = op_cli.assert_logged_in()
assert result
def test_full_signin_v2(mocker):
mocker.patch.object(OnePassCLIv2, "_run", return_value=[0, "", ""])
op_cli = OnePassCLIv2(
subdomain="acme",
username="bob@acme.com",
secret_key="SECRET",
master_password="ONEKEYTORULETHEMALL",
)
result = op_cli.full_signin()
op_cli._run.assert_called_with(
[
"account",
"add",
"--raw",
"--address",
"acme.1password.com",
"--email",
b"bob@acme.com",
"--signin",
],
command_input=b"ONEKEYTORULETHEMALL",
environment_update={"OP_SECRET_KEY": "SECRET"},
)
assert result == [0, "", ""]
@pytest.mark.parametrize(
("version", "version_class"),
(("2.27.4", OnePassCLIv2),),
)
def test_op_correct_cli_class(fake_op, version, version_class):
op = fake_op(version)
assert op._cli.version == version
assert isinstance(op._cli, version_class)
def test_op_unsupported_cli_version(fake_op):
with pytest.raises(OnePasswordError, match="is unsupported"):
fake_op("1.17.2")
with pytest.raises(OnePasswordError, match="is unsupported"):
fake_op("99.77.77")
@pytest.mark.parametrize("op_fixture", OP_VERSION_FIXTURES)
def test_op_set_token_with_config(op_fixture, mocker, request):
op = request.getfixturevalue(op_fixture)
token = "F5417F77529B41B595D7F9D6F76EC057"
mocker.patch("os.path.isfile", return_value=True)
mocker.patch.object(op._cli, "signin", return_value=(0, f"{token}\n", ""))
op.set_token()
assert op.token == token
@pytest.mark.parametrize(
("op_fixture", "message"),
[
(op, value)
for op in OP_VERSION_FIXTURES
for value in (
"Missing required parameters",
"The operation is unauthorized",
)
],
)
def test_op_set_token_with_config_missing_args(op_fixture, message, request, mocker):
op = request.getfixturevalue(op_fixture)
mocker.patch("os.path.isfile", return_value=True)
mocker.patch.object(op._cli, "signin", return_value=(99, "", ""), side_effect=OnePasswordError(message))
mocker.patch.object(op._cli, "full_signin", return_value=(0, "", ""))
with pytest.raises(OnePasswordError, match=message):
op.set_token()
op._cli.full_signin.assert_not_called()
@pytest.mark.parametrize("op_fixture", OP_VERSION_FIXTURES)
def test_op_set_token_with_config_full_signin(op_fixture, request, mocker):
op = request.getfixturevalue(op_fixture)
mocker.patch("os.path.isfile", return_value=True)
mocker.patch.object(
op._cli, "signin", return_value=(99, "", ""), side_effect=OnePasswordError("Raised intentionally")
)
mocker.patch.object(op._cli, "full_signin", return_value=(0, "", ""))
op.set_token()
op._cli.full_signin.assert_called()
@pytest.mark.parametrize("op_fixture", OP_VERSION_FIXTURES)
def test_op_set_token_without_config(op_fixture, request, mocker):
op = request.getfixturevalue(op_fixture)
token = "B988E8A2680A4A348962751A96861FA1"
mocker.patch("os.path.isfile", return_value=False)
mocker.patch.object(op._cli, "signin", return_value=(99, "", ""))
mocker.patch.object(op._cli, "full_signin", return_value=(0, f"{token}\n", ""))
op.set_token()
op._cli.signin.assert_not_called()
assert op.token == token
@pytest.mark.parametrize(
("op_fixture", "login_status"), [(op, value) for op in OP_VERSION_FIXTURES for value in [False, True]]
)
def test_op_assert_logged_in(mocker, login_status, op_fixture, request):
op = request.getfixturevalue(op_fixture)
mocker.patch.object(op._cli, "assert_logged_in", return_value=login_status)
mocker.patch.object(op, "set_token")
op.assert_logged_in()
op._cli.assert_logged_in.assert_called_once()
assert op.logged_in == login_status
if not login_status:
op.set_token.assert_called_once()
@pytest.mark.parametrize(
("op_fixture", "output", "expected"),
(
list(itertools.chain([op], d))
for op in OP_VERSION_FIXTURES
for d in [
("RAW OUTPUT", "RAW OUTPUT"),
(None, ""),
("", ""),
]
),
)
def test_op_get_field(mocker, op_fixture, output, expected, request):
op = request.getfixturevalue(op_fixture)
mocker.patch.object(op, "get_raw", return_value=output)
mocker.patch.object(op._cli, "_parse_field", return_value=output)
result = op.get_field("some item", "some field")
assert result == expected
# This test sometimes fails on older Python versions because the gathered tests mismatch.
# Sort the fixture data to make this reliable
# https://github.com/pytest-dev/pytest-xdist/issues/432
@pytest.mark.parametrize("op_fixture", OP_VERSION_FIXTURES)
def test_op_get_secret_reference_decodes_bytes(mocker, op_fixture, request):
op = request.getfixturevalue(op_fixture)
mocker.patch.object(op._cli, "get_secret_reference", return_value=(0, b"hunter2\n", ""))
result = op.get_secret_reference("op://vault/item/field")
assert result == "hunter2"
assert isinstance(result, str)
@pytest.mark.parametrize(
("cli_class", "vault", "queries", "kwargs", "output", "expected"),
(
(_cli_class, item["vault_name"], item["queries"], item.get("kwargs", {}), item["output"], item["expected"])
for _cli_class in sorted(MOCK_ENTRIES, key=operator.attrgetter("__name__"))
for item in MOCK_ENTRIES[_cli_class]
),
)
def test_op_lookup(mocker, cli_class, vault, queries, kwargs, output, expected):
mocker.patch(
"ansible_collections.community.general.plugins.module_utils._onepassword_cli.OnePass._get_cli_class", cli_class
)
mocker.patch(
"ansible_collections.community.general.plugins.module_utils._onepassword_cli.OnePass.assert_logged_in",
return_value=True,
)
mocker.patch(
"ansible_collections.community.general.plugins.module_utils._onepassword_cli.OnePassCLIBase._run",
return_value=(0, json.dumps(output), ""),
)
op_lookup = lookup_loader.get("community.general.onepassword")
result = op_lookup.run(queries, vault=vault, **kwargs)
assert result == expected
@pytest.mark.parametrize("op_fixture", OP_VERSION_FIXTURES)
def test_signin(op_fixture, request):
op = request.getfixturevalue(op_fixture)
op._cli.master_password = "master_pass"
op._cli.signin()
op._cli._run.assert_called_once_with(["signin", "--raw"], command_input=b"master_pass")
def test_op_doc(mocker):
document_contents = "Document Contents\n"
mocker.patch(
"ansible_collections.community.general.plugins.module_utils._onepassword_cli.OnePass.assert_logged_in",
return_value=True,
)
mocker.patch(
"ansible_collections.community.general.plugins.module_utils._onepassword_cli.OnePassCLIBase._run",
return_value=(0, document_contents, ""),
)
op_lookup = lookup_loader.get("community.general.onepassword_doc")
result = op_lookup.run(["Private key doc"])
assert result == [document_contents]
@pytest.mark.parametrize(
("plugin", "connect_host", "connect_token"),
[
(plugin, connect_host, connect_token)
for plugin in ("community.general.onepassword", "community.general.onepassword_raw")
for (connect_host, connect_token) in (
("http://localhost", None),
(None, "foobar"),
)
],
)
def test_op_connect_partial_args(plugin, connect_host, connect_token, mocker):
op_lookup = lookup_loader.get(plugin)
mocker.patch(
"ansible_collections.community.general.plugins.module_utils._onepassword_cli.OnePass._get_cli_class",
OnePassCLIv2,
)
with pytest.raises(AnsibleOptionsError):
op_lookup.run("login", vault_name="test vault", connect_host=connect_host, connect_token=connect_token)
@@ -0,0 +1,35 @@
# 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
import json
import pytest
from ansible.plugins.loader import lookup_loader
from .onepassword_common import SSH_KEY_MOCK_ENTRIES
@pytest.mark.parametrize(
("vault", "queries", "kwargs", "output", "expected"),
(
(item["vault_name"], item["queries"], item.get("kwargs", {}), item["output"], item["expected"])
for item in SSH_KEY_MOCK_ENTRIES
),
)
def test_ssh_key(mocker, vault, queries, kwargs, output, expected):
mocker.patch(
"ansible_collections.community.general.plugins.module_utils._onepassword_cli.OnePass.assert_logged_in",
return_value=True,
)
mocker.patch(
"ansible_collections.community.general.plugins.module_utils._onepassword_cli.OnePassCLIBase._run",
return_value=(0, json.dumps(output), ""),
)
op_lookup = lookup_loader.get("community.general.onepassword_ssh_key")
result = op_lookup.run(queries, vault=vault, **kwargs)
assert result == expected
@@ -0,0 +1,687 @@
# Copyright (c) 2026, Jean Khawand (@jeankhawand)
# 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 json
import os
import traceback
import unittest
from subprocess import TimeoutExpired
from unittest.mock import MagicMock, patch
import pytest
from ansible.errors import AnsibleLookupError, AnsibleOptionsError
from ansible_collections.community.general.plugins.lookup.proton_pass import (
LookupModule,
ProtonPassClient,
ProtonPassCLIError,
_parse_fields,
_raise_item_error,
)
# ---------------------------------------------------------------------------
# Fixtures — representative pass-cli --output json payloads (v2.x schema)
# Each fixture mirrors the {"item": {...}} envelope returned by `pass-cli item view`.
# ---------------------------------------------------------------------------
def _make_item(type_key, type_data, extra_fields=None, extra_sections=None, note="", state="Active"):
return {
"item": {
"content": {
"title": "test_item",
"note": note,
"content": {type_key: type_data},
"extra_fields": extra_fields or [],
"extra_sections": extra_sections or [],
},
"state": state,
}
}
MOCK_LOGIN_ITEM = _make_item(
"Login",
{"email": "", "username": "", "password": "correct-horse-battery", "urls": [], "totp_uri": "", "passkeys": []},
extra_fields=[
{"name": "api_token", "content": {"Hidden": "token_value_abc"}},
{"name": "backup_secret", "content": {"Hidden": "secure_value_1"}},
],
)
MOCK_SECTIONED_ITEM = _make_item(
"Custom",
{"sections": []},
extra_sections=[
{
"section_name": "Credentials",
"extra_fields": [
{"name": "backup_secret", "content": {"Hidden": "secure_value_2"}},
{"name": "storage_key", "content": {"Hidden": "secure_value_3"}},
],
}
],
)
MOCK_NOTE_ITEM = _make_item("Custom", {"sections": []}, note="some free-text note")
MOCK_LOGIN_URLS_ITEM = _make_item(
"Login",
{
"email": "user@example.com",
"username": "user@example.com",
"password": "secret",
"totp_uri": "otpauth://totp/example?secret=JBSWY3DPEHPK3PXP",
"urls": ["https://example.com", "https://app.example.com"],
"passkeys": [],
},
)
MOCK_CREDIT_CARD_ITEM = _make_item(
"CreditCard",
{
"cardholder_name": "John Doe",
"card_type": "Visa",
"number": "4111111111111111",
"verification_number": "123",
"expiration_date": "2027-12",
"pin": "1234",
},
)
MOCK_WIFI_ITEM = _make_item(
"Wifi",
{"ssid": "HomeNetwork", "password": "wifipass123", "security": "WPA2", "sections": []},
)
MOCK_IDENTITY_ITEM = _make_item(
"Identity",
{
"first_name": "John",
"last_name": "Doe",
"email": "john@example.com",
"phone_number": "+1234567890",
"organization": "ACME",
"city": "Springfield",
"country_or_region": "US",
"extra_personal_details": [
{"name": "custom_personal", "content": {"Hidden": "personal_secret"}},
],
"extra_address_details": [
{"name": "custom_address", "content": {"Text": "123 Main St"}},
],
"extra_contact_details": [],
"extra_work_details": [],
"extra_sections": [],
},
)
MOCK_SSH_KEY_ITEM = _make_item(
"SshKey",
{
"private_key": "-----BEGIN OPENSSH PRIVATE KEY-----\nfake\n-----END OPENSSH PRIVATE KEY-----",
"public_key": "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIFake deploy@host",
"fingerprint": "SHA256:abc123fake",
"key_type": "ed25519",
},
)
MOCK_ALIAS_ITEM = _make_item(
"Alias",
None,
extra_fields=[{"name": "aliased_email", "content": {"Text": "shopping.abc123@pm.me"}}],
)
MOCK_TRASHED_ITEM = _make_item(
"Login",
{"username": "x", "password": "y", "urls": [], "totp_uri": "", "passkeys": []},
extra_fields=[{"name": "secret", "content": {"Hidden": "value"}}],
state="Trashed",
)
# ---------------------------------------------------------------------------
# _parse_fields
# ---------------------------------------------------------------------------
class TestParseFields(unittest.TestCase):
def test_login_item_with_extra_fields(self):
fields = _parse_fields(MOCK_LOGIN_ITEM, "example_item")
self.assertEqual(fields["api_token"], "token_value_abc")
self.assertEqual(fields["backup_secret"], "secure_value_1")
self.assertEqual(fields["password"], "correct-horse-battery")
def test_sectioned_item(self):
fields = _parse_fields(MOCK_SECTIONED_ITEM, "grouped_item")
self.assertEqual(fields["backup_secret"], "secure_value_2")
self.assertEqual(fields["storage_key"], "secure_value_3")
def test_note_item(self):
fields = _parse_fields(MOCK_NOTE_ITEM, "notes_item")
self.assertEqual(fields["note"], "some free-text note")
def test_empty_item_raises(self):
empty = _make_item("Custom", {"sections": []})
with self.assertRaises(AnsibleLookupError) as ctx:
_parse_fields(empty, "empty_item")
self.assertIn("empty_item", str(ctx.exception))
def test_login_urls_returned_as_list(self):
fields = _parse_fields(MOCK_LOGIN_URLS_ITEM, "web_login")
self.assertEqual(fields["username"], "user@example.com")
self.assertEqual(fields["password"], "secret")
self.assertEqual(fields["totp_uri"], "otpauth://totp/example?secret=JBSWY3DPEHPK3PXP")
self.assertEqual(fields["urls"], ["https://example.com", "https://app.example.com"])
def test_credit_card_item(self):
fields = _parse_fields(MOCK_CREDIT_CARD_ITEM, "my_visa")
self.assertEqual(fields["cardholder_name"], "John Doe")
self.assertEqual(fields["card_type"], "Visa")
self.assertEqual(fields["number"], "4111111111111111")
self.assertEqual(fields["verification_number"], "123")
self.assertEqual(fields["expiration_date"], "2027-12")
self.assertEqual(fields["pin"], "1234")
def test_wifi_item(self):
fields = _parse_fields(MOCK_WIFI_ITEM, "home_wifi")
self.assertEqual(fields["ssid"], "HomeNetwork")
self.assertEqual(fields["password"], "wifipass123")
self.assertEqual(fields["security"], "WPA2")
self.assertNotIn("username", fields)
def test_identity_item(self):
fields = _parse_fields(MOCK_IDENTITY_ITEM, "my_identity")
self.assertEqual(fields["first_name"], "John")
self.assertEqual(fields["last_name"], "Doe")
self.assertEqual(fields["email"], "john@example.com")
self.assertEqual(fields["organization"], "ACME")
self.assertEqual(fields["city"], "Springfield")
self.assertEqual(fields["country_or_region"], "US")
def test_identity_sub_array_extra_fields(self):
"""Extra fields nested in Identity sub-arrays are merged into the result."""
fields = _parse_fields(MOCK_IDENTITY_ITEM, "my_identity")
self.assertEqual(fields["custom_personal"], "personal_secret")
self.assertEqual(fields["custom_address"], "123 Main St")
def test_ssh_key_item(self):
fields = _parse_fields(MOCK_SSH_KEY_ITEM, "deploy_key")
self.assertIn("-----BEGIN OPENSSH PRIVATE KEY-----", fields["private_key"])
self.assertIn("ssh-ed25519", fields["public_key"])
self.assertEqual(fields["fingerprint"], "SHA256:abc123fake")
self.assertEqual(fields["key_type"], "ed25519")
def test_alias_item(self):
fields = _parse_fields(MOCK_ALIAS_ITEM, "shopping_alias")
self.assertEqual(fields["aliased_email"], "shopping.abc123@pm.me")
def test_alias_item_aliased_address_fallback(self):
"""aliased_address is accepted when aliased_email is absent."""
item = _make_item("Alias", {"aliased_address": "alt.abc@pm.me"})
fields = _parse_fields(item, "alias2")
self.assertEqual(fields["aliased_email"], "alt.abc@pm.me")
def test_timestamp_extra_field_converted_to_string(self):
"""Timestamp integer values in extra_fields must be stored as strings."""
item = _make_item(
"Login",
{"username": "u", "password": "p", "urls": [], "totp_uri": "", "passkeys": []},
extra_fields=[{"name": "expiry", "content": {"Timestamp": 1735689600}}],
)
fields = _parse_fields(item, "item")
self.assertEqual(fields["expiry"], "1735689600")
def test_trashed_item_raises(self):
"""Items in the Proton Pass trash must raise AnsibleLookupError."""
with self.assertRaises(AnsibleLookupError) as ctx:
_parse_fields(MOCK_TRASHED_ITEM, "old_item")
self.assertIn("trash", str(ctx.exception).lower())
self.assertIn("old_item", str(ctx.exception))
# Shape emitted by pass-cli: sections live inside the item type object.
SECTIONS = [
{
"section_name": "Credentials",
"section_fields": [
{"name": "api_token", "content": {"Hidden": "token_value"}},
{"name": "endpoint", "content": {"Text": "https://api.example.com"}},
],
},
{
"section_name": "Backup",
"section_fields": [{"name": "backup_secret", "content": {"Hidden": "backup_value"}}],
},
]
@pytest.mark.parametrize(
"type_key, type_data",
[
("Custom", {"sections": SECTIONS}),
("SshKey", {"private_key": "fake-private", "public_key": "fake-public", "sections": SECTIONS}),
("Wifi", {"ssid": "HomeNetwork", "password": "wifipass123", "security": "WPA2", "sections": SECTIONS}),
("Identity", {"full_name": "John Doe", "extra_sections": SECTIONS}),
],
)
def test_section_fields_are_merged(type_key, type_data):
fields = _parse_fields(_make_item(type_key, type_data), "sectioned_item")
assert fields["api_token"] == "token_value"
assert fields["endpoint"] == "https://api.example.com"
assert fields["backup_secret"] == "backup_value"
def test_section_fields_kept_alongside_standard_fields():
item = _make_item("SshKey", {"private_key": "fake-private", "public_key": "fake-public", "sections": SECTIONS})
fields = _parse_fields(item, "deploy_key")
assert fields["private_key"] == "fake-private"
assert fields["public_key"] == "fake-public"
assert fields["api_token"] == "token_value"
def test_custom_item_with_empty_sections_raises():
item = _make_item("Custom", {"sections": [{"section_name": "Empty", "section_fields": []}]})
with pytest.raises(AnsibleLookupError, match="no fields extracted"):
_parse_fields(item, "empty_custom")
# ---------------------------------------------------------------------------
# _extract_extra_fields
# ---------------------------------------------------------------------------
class TestExtractExtraFields(unittest.TestCase):
def test_hidden_field(self):
from ansible_collections.community.general.plugins.lookup.proton_pass import _extract_extra_fields
result = _extract_extra_fields([{"name": "my_key", "content": {"Hidden": "secret_val"}}])
self.assertEqual(result, {"my_key": "secret_val"})
def test_text_field(self):
from ansible_collections.community.general.plugins.lookup.proton_pass import _extract_extra_fields
result = _extract_extra_fields([{"name": "my_key", "content": {"Text": "text_val"}}])
self.assertEqual(result, {"my_key": "text_val"})
def test_totp_field(self):
from ansible_collections.community.general.plugins.lookup.proton_pass import _extract_extra_fields
uri = "otpauth://totp/Test?secret=ABC"
result = _extract_extra_fields([{"name": "otp", "content": {"Totp": uri}}])
self.assertEqual(result, {"otp": uri})
def test_timestamp_field_converted_to_string(self):
from ansible_collections.community.general.plugins.lookup.proton_pass import _extract_extra_fields
result = _extract_extra_fields([{"name": "expiry", "content": {"Timestamp": 1735689600}}])
self.assertEqual(result, {"expiry": "1735689600"})
def test_skips_field_with_no_name(self):
from ansible_collections.community.general.plugins.lookup.proton_pass import _extract_extra_fields
result = _extract_extra_fields([{"content": {"Hidden": "val"}}])
self.assertEqual(result, {})
# ---------------------------------------------------------------------------
# _raise_item_error
# ---------------------------------------------------------------------------
class TestRaiseItemError(unittest.TestCase):
def test_not_found_stderr(self):
with self.assertRaises(AnsibleLookupError) as ctx:
_raise_item_error("vm", "vault", None, "Error: item not found")
self.assertIn("not found", str(ctx.exception).lower())
self.assertIn("vm", str(ctx.exception))
def test_unauthorized_stderr(self):
with self.assertRaises(AnsibleLookupError) as ctx:
_raise_item_error("vm", "vault", None, "Error: unauthorized access")
self.assertIn("authentication", str(ctx.exception).lower())
self.assertIn("Error: unauthorized access", str(ctx.exception))
def test_generic_error(self):
with self.assertRaises(AnsibleLookupError) as ctx:
_raise_item_error("vm", "vault", "api_key", "Unexpected Failure")
self.assertIn("Unexpected Failure", str(ctx.exception))
self.assertIn("api_key", str(ctx.exception))
# ---------------------------------------------------------------------------
# ProtonPassClient
# ---------------------------------------------------------------------------
def _make_popen_mock(returncode: int, stdout: bytes, stderr: bytes):
mock_proc = MagicMock()
mock_proc.returncode = returncode
mock_proc.communicate.return_value = (stdout, stderr)
return mock_proc
class TestProtonPassClientRun(unittest.TestCase):
@patch("ansible_collections.community.general.plugins.lookup.proton_pass.Popen")
def test_successful_run(self, mock_popen):
mock_popen.return_value = _make_popen_mock(0, b"output\n", b"")
client = ProtonPassClient(cli_path="pass-cli", timeout=30, agent_reason="")
rc, out, err = client._run(["test"])
self.assertEqual(rc, 0)
self.assertEqual(out, "output\n")
@patch("ansible_collections.community.general.plugins.lookup.proton_pass.Popen")
def test_missing_binary_raises(self, mock_popen):
mock_popen.side_effect = FileNotFoundError()
client = ProtonPassClient(cli_path="/no/such/binary", timeout=30, agent_reason="")
with self.assertRaises(ProtonPassCLIError) as ctx:
client._run(["test"])
self.assertIn("not found", str(ctx.exception))
@patch("ansible_collections.community.general.plugins.lookup.proton_pass.Popen")
def test_agent_reason_injected_into_env(self, mock_popen):
"""PROTON_PASS_AGENT_REASON must be present in the subprocess env when set."""
mock_popen.return_value = _make_popen_mock(0, b"ok\n", b"")
client = ProtonPassClient(cli_path="pass-cli", timeout=30, agent_reason="nightly deployment")
client._run(["test"])
_call_args, kwargs = mock_popen.call_args
self.assertEqual(kwargs["env"].get("PROTON_PASS_AGENT_REASON"), "nightly deployment")
@patch("ansible_collections.community.general.plugins.lookup.proton_pass.Popen")
def test_no_agent_reason_does_not_override_env(self, mock_popen):
"""When agent_reason is empty, PROTON_PASS_AGENT_REASON should not be forced."""
mock_popen.return_value = _make_popen_mock(0, b"ok\n", b"")
client = ProtonPassClient(cli_path="pass-cli", timeout=30, agent_reason="")
client._run(["test"])
_call_args, kwargs = mock_popen.call_args
# The key may be inherited from the real environment — we only assert it
# was not forcibly added by the plugin logic (value will be None if absent).
env = kwargs["env"]
self.assertNotEqual(env.get("PROTON_PASS_AGENT_REASON"), "") # not set to empty
@patch("ansible_collections.community.general.plugins.lookup.proton_pass.Popen")
def test_timeout_raises(self, mock_popen):
mock_proc = MagicMock()
mock_proc.communicate.side_effect = TimeoutExpired(cmd="pass-cli", timeout=30)
mock_popen.return_value = mock_proc
client = ProtonPassClient(cli_path="pass-cli", timeout=30, agent_reason="")
with self.assertRaises(ProtonPassCLIError) as ctx:
client._run(["test"])
self.assertIn("timed out", str(ctx.exception))
class TestProtonPassClientAuth(unittest.TestCase):
@patch("ansible_collections.community.general.plugins.lookup.proton_pass.Popen")
def test_test_session_returns_true_on_rc0(self, mock_popen):
mock_popen.return_value = _make_popen_mock(0, b"", b"")
client = ProtonPassClient(cli_path="pass-cli", timeout=30, agent_reason="")
self.assertTrue(client.test_session())
self.assertEqual(mock_popen.call_args.args[0], ["pass-cli", "info"])
@patch("ansible_collections.community.general.plugins.lookup.proton_pass.Popen")
def test_test_session_returns_false_on_nonzero(self, mock_popen):
mock_popen.return_value = _make_popen_mock(1, b"", b"not logged in\n")
client = ProtonPassClient(cli_path="pass-cli", timeout=30, agent_reason="")
self.assertFalse(client.test_session())
@patch("ansible_collections.community.general.plugins.lookup.proton_pass.Popen")
def test_ensure_authenticated_already_ok(self, mock_popen):
client = ProtonPassClient(cli_path="pass-cli", timeout=30, agent_reason="")
client._session_ok = True
# ensure_authenticated must not invoke pass-cli at all
client.ensure_authenticated(pat="")
mock_popen.assert_not_called()
@patch("ansible_collections.community.general.plugins.lookup.proton_pass.Popen")
def test_ensure_authenticated_no_session_no_pat_raises(self, mock_popen):
mock_popen.return_value = _make_popen_mock(1, b"", b"unauthenticated\n")
client = ProtonPassClient(cli_path="pass-cli", timeout=30, agent_reason="")
with self.assertRaises(AnsibleLookupError) as ctx:
client.ensure_authenticated(pat="")
self.assertIn("PAT", str(ctx.exception))
@patch("ansible_collections.community.general.plugins.lookup.proton_pass.Popen")
def test_ensure_authenticated_logs_in_with_pat(self, mock_popen):
# First call (test): unauthenticated; second call (login): success
mock_popen.side_effect = [
_make_popen_mock(1, b"", b"unauthenticated\n"),
_make_popen_mock(0, b"", b""),
]
client = ProtonPassClient(cli_path="pass-cli", timeout=30, agent_reason="")
client.ensure_authenticated(pat="pst_token::key")
self.assertEqual(mock_popen.call_count, 2)
login_call = mock_popen.call_args_list[1]
self.assertEqual(login_call.args[0], ["pass-cli", "login"])
self.assertEqual(login_call.kwargs["env"]["PROTON_PASS_PERSONAL_ACCESS_TOKEN"], "pst_token::key")
@patch("ansible_collections.community.general.plugins.lookup.proton_pass.Popen")
def test_login_pat_env_precedence(self, mock_popen):
"""The PAT option wins over an inherited token; an empty PAT leaves the environment alone."""
env_var = "PROTON_PASS_PERSONAL_ACCESS_TOKEN"
cases = [
# (pat option, inherited env value or None if unset, expected env value or None if absent)
("pst_option::key", None, "pst_option::key"),
("pst_option::key", "pst_inherited::key", "pst_option::key"),
("", "pst_inherited::key", "pst_inherited::key"),
("", None, None),
]
for pat, inherited, expected in cases:
with self.subTest(pat=pat, inherited=inherited):
mock_popen.reset_mock()
mock_popen.return_value = _make_popen_mock(0, b"", b"")
with patch.dict("os.environ"):
os.environ.pop(env_var, None)
if inherited is not None:
os.environ[env_var] = inherited
ProtonPassClient(cli_path="pass-cli", timeout=30, agent_reason="").login_with_pat(pat)
env = mock_popen.call_args.kwargs["env"]
self.assertEqual(env.get(env_var), expected)
class TestProtonPassClientFetch(unittest.TestCase):
@patch("ansible_collections.community.general.plugins.lookup.proton_pass.Popen")
def test_fetch_field_success(self, mock_popen):
"""fetch_field delegates to fetch_all_fields and returns the requested field."""
payload = json.dumps(MOCK_LOGIN_ITEM).encode()
mock_popen.return_value = _make_popen_mock(0, payload, b"")
client = ProtonPassClient(cli_path="pass-cli", timeout=30, agent_reason="")
result = client.fetch_field(vault="vault", title="example_item", field="api_token")
self.assertEqual(result, "token_value_abc")
@patch("ansible_collections.community.general.plugins.lookup.proton_pass.Popen")
def test_fetch_field_not_found_raises(self, mock_popen):
mock_popen.return_value = _make_popen_mock(1, b"", b"Error: item not found\n")
client = ProtonPassClient(cli_path="pass-cli", timeout=30, agent_reason="")
with self.assertRaises(AnsibleLookupError):
client.fetch_field(vault="vault", title="missing", field="password")
@patch("ansible_collections.community.general.plugins.lookup.proton_pass.Popen")
def test_fetch_field_missing_field_raises(self, mock_popen):
"""fetch_field raises with available fields listed when field is absent from item."""
payload = json.dumps(MOCK_LOGIN_ITEM).encode()
mock_popen.return_value = _make_popen_mock(0, payload, b"")
client = ProtonPassClient(cli_path="pass-cli", timeout=30, agent_reason="")
with self.assertRaises(AnsibleLookupError) as ctx:
client.fetch_field(vault="vault", title="example_item", field="nonexistent_key")
err = str(ctx.exception)
self.assertIn("nonexistent_key", err)
self.assertIn("Available fields", err)
@patch("ansible_collections.community.general.plugins.lookup.proton_pass.Popen")
def test_fetch_all_fields_success(self, mock_popen):
payload = json.dumps(MOCK_LOGIN_ITEM).encode()
mock_popen.return_value = _make_popen_mock(0, payload, b"")
client = ProtonPassClient(cli_path="pass-cli", timeout=30, agent_reason="")
result = client.fetch_all_fields(vault="vault", title="example_item")
self.assertEqual(result["api_token"], "token_value_abc")
self.assertEqual(result["backup_secret"], "secure_value_1")
@patch("ansible_collections.community.general.plugins.lookup.proton_pass.display")
@patch("ansible_collections.community.general.plugins.lookup.proton_pass.Popen")
def test_fetch_all_fields_debug_warning(self, mock_popen, mock_display):
"""When debug=True, display.warning is called with raw JSON;
the result is still parsed and returned correctly."""
payload = json.dumps(MOCK_LOGIN_ITEM).encode()
mock_popen.return_value = _make_popen_mock(0, payload, b"")
client = ProtonPassClient(cli_path="pass-cli", timeout=30, agent_reason="", debug=True)
result = client.fetch_all_fields(vault="vault", title="example_item")
mock_display.warning.assert_called_once()
self.assertIn("example_item", mock_display.warning.call_args[0][0])
self.assertEqual(result["api_token"], "token_value_abc")
@patch("ansible_collections.community.general.plugins.lookup.proton_pass.display")
@patch("ansible_collections.community.general.plugins.lookup.proton_pass.Popen")
def test_fetch_all_fields_no_debug_warning(self, mock_popen, mock_display):
"""When debug=False, display.warning is not called."""
payload = json.dumps(MOCK_LOGIN_ITEM).encode()
mock_popen.return_value = _make_popen_mock(0, payload, b"")
client = ProtonPassClient(cli_path="pass-cli", timeout=30, agent_reason="", debug=False)
result = client.fetch_all_fields(vault="vault", title="example_item")
mock_display.warning.assert_not_called()
self.assertEqual(result["api_token"], "token_value_abc")
@patch("ansible_collections.community.general.plugins.lookup.proton_pass.Popen")
def test_fetch_all_fields_invalid_json_raises(self, mock_popen):
mock_popen.return_value = _make_popen_mock(0, b"not json {{", b"")
client = ProtonPassClient(cli_path="pass-cli", timeout=30, agent_reason="")
with self.assertRaises(AnsibleLookupError) as ctx:
client.fetch_all_fields(vault="vault", title="bad_item")
self.assertIn("invalid JSON", str(ctx.exception))
# ---------------------------------------------------------------------------
# LookupModule integration
# ---------------------------------------------------------------------------
class TestLookupModule(unittest.TestCase):
"""
Integration tests for LookupModule.run().
Ansible's config system requires a fully initialised plugin (via lookup_loader
or ansible-test) to resolve options declared in DOCUMENTATION. In a plain
unittest environment lookup_loader returns None, so these tests patch
set_options (no-op) and get_option (returns values from a local dict) to
exercise the routing logic without depending on the Ansible config manager.
Use ``ansible-test unit`` for a full integration test in CI.
"""
def setUp(self):
self.lookup = LookupModule()
def _run(self, terms, vault="", field="", pat="", agent_reason="", cli_path="pass-cli", timeout=30, debug=False):
"""Run with Ansible option plumbing patched out."""
options = {
"vault": vault,
"field": field,
"pat": pat,
"agent_reason": agent_reason,
"cli_path": cli_path,
"timeout": timeout,
"debug": debug,
}
with patch.object(self.lookup, "set_options"):
with patch.object(self.lookup, "get_option", side_effect=lambda k: options.get(k, "")):
return self.lookup.run(terms)
@patch("ansible_collections.community.general.plugins.lookup.proton_pass.ProtonPassClient")
def test_all_fields_mode(self, mock_client_cls):
mock_client = MagicMock()
mock_client.fetch_all_fields.return_value = {"api_key": "secret123"}
mock_client_cls.return_value = mock_client
result = self._run(["vm"], vault="myvault")
self.assertEqual(result, [{"api_key": "secret123"}])
mock_client.fetch_all_fields.assert_called_once_with(vault="myvault", title="vm")
@patch("ansible_collections.community.general.plugins.lookup.proton_pass.ProtonPassClient")
def test_single_field_via_second_term(self, mock_client_cls):
mock_client = MagicMock()
mock_client.fetch_field.return_value = "secret123"
mock_client_cls.return_value = mock_client
result = self._run(["vm", "api_key"], vault="myvault")
self.assertEqual(result, ["secret123"])
mock_client.fetch_field.assert_called_once_with(vault="myvault", title="vm", field="api_key")
@patch("ansible_collections.community.general.plugins.lookup.proton_pass.ProtonPassClient")
def test_single_field_via_kwarg(self, mock_client_cls):
mock_client = MagicMock()
mock_client.fetch_field.return_value = "secret123"
mock_client_cls.return_value = mock_client
result = self._run(["vm"], vault="myvault", field="api_key")
self.assertEqual(result, ["secret123"])
@patch("ansible_collections.community.general.plugins.lookup.proton_pass.ProtonPassClient")
def test_field_kwarg_overrides_second_term(self, mock_client_cls):
"""O(field) takes precedence over the second positional term."""
mock_client = MagicMock()
mock_client.fetch_field.return_value = "secret123"
mock_client_cls.return_value = mock_client
self._run(["vm", "ignored_term"], vault="myvault", field="real_field")
mock_client.fetch_field.assert_called_once_with(vault="myvault", title="vm", field="real_field")
@patch("ansible_collections.community.general.plugins.lookup.proton_pass.ProtonPassClient")
def test_multiple_items_with_field(self, mock_client_cls):
# Three terms required: two terms trigger the (item, field) shorthand,
# so three or more terms are needed to look up multiple items.
mock_client = MagicMock()
mock_client.fetch_field.side_effect = ["pass_a", "pass_b", "pass_c"]
mock_client_cls.return_value = mock_client
result = self._run(["host_a", "host_b", "host_c"], vault="", field="gpg_keyphrase")
self.assertEqual(result, ["pass_a", "pass_b", "pass_c"])
def test_multiple_items_no_field_raises(self):
# Three terms without field= should raise AnsibleOptionsError.
with self.assertRaises(AnsibleOptionsError):
self._run(["host_a", "host_b", "host_c"], vault="")
def test_no_terms_raises(self):
with self.assertRaises(AnsibleLookupError):
self._run([], vault="myvault")
@patch("ansible_collections.community.general.plugins.lookup.proton_pass.ProtonPassClient")
def test_debug_option_passed_to_client(self, mock_client_cls):
"""Verify that the debug option is passed to ProtonPassClient."""
mock_client = MagicMock()
mock_client.fetch_all_fields.return_value = {"api_key": "secret123"}
mock_client_cls.return_value = mock_client
self._run(["vm"], vault="myvault", debug=True)
# Check that ProtonPassClient was instantiated with debug=True
mock_client_cls.assert_called_once()
call_kwargs = mock_client_cls.call_args[1]
self.assertTrue(call_kwargs["debug"])
@patch("ansible_collections.community.general.plugins.lookup.proton_pass.display")
@patch("ansible_collections.community.general.plugins.lookup.proton_pass.Popen")
def test_pat_not_exposed_when_login_times_out(self, mock_popen, mock_display):
"""The PAT must not appear in the error, its traceback, or verbose output."""
pat = "pst_SECRETTOKEN::SECRETKEY"
def popen(command, **kwargs):
if command[1:] == ["info"]:
return _make_popen_mock(1, b"", b"not logged in\n")
mock_proc = MagicMock()
mock_proc.communicate.side_effect = TimeoutExpired(cmd=command, timeout=30)
return mock_proc
mock_popen.side_effect = popen
with self.assertRaises(ProtonPassCLIError) as ctx:
self._run(["vm"], vault="myvault", pat=pat)
exc = ctx.exception
rendered = "".join(traceback.format_exception(type(exc), exc, exc.__traceback__))
self.assertIn("timed out", rendered)
self.assertNotIn("SECRETTOKEN", rendered)
for call in mock_display.method_calls:
self.assertNotIn("SECRETTOKEN", str(call))
for call in mock_popen.call_args_list:
self.assertNotIn(pat, call.args[0])
@@ -0,0 +1,37 @@
# Copyright (c) 2021, RevBits <info@revbits.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 unittest import TestCase
from unittest.mock import (
MagicMock,
patch,
)
from ansible.plugins.loader import lookup_loader
from ansible_collections.community.general.plugins.lookup import revbitspss
class MockPamSecrets(MagicMock):
RESPONSE = "dummy value"
def get_pam_secret(self, path):
return self.RESPONSE
class TestLookupModule(TestCase):
def setUp(self):
revbitspss.ANOTHER_LIBRARY_IMPORT_ERROR = None
self.lookup = lookup_loader.get("community.general.revbitspss")
@patch(
"ansible_collections.community.general.plugins.lookup.revbitspss.LookupModule.Client",
MockPamSecrets(),
)
def test_get_pam_secret(self):
terms = ["dummy secret"]
variables = []
kwargs = {"base_url": "https://dummy.url", "api_key": "dummy"}
self.assertListEqual([{"dummy secret": "dummy value"}], self.lookup.run(terms, variables, **kwargs))
@@ -0,0 +1,269 @@
# Copyright (c) 2020, Adam Migus <adam@migus.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
from unittest import TestCase
from unittest.mock import (
DEFAULT,
MagicMock,
patch,
)
from ansible.plugins.loader import lookup_loader
from ansible_collections.community.general.plugins.lookup import tss
TSS_IMPORT_PATH = "ansible_collections.community.general.plugins.lookup.tss"
def make_absolute(name):
return f"{TSS_IMPORT_PATH}.{name}"
class SecretServerError(Exception):
def __init__(self):
self.message = ""
class SecretServerClientError(SecretServerError):
pass
class MockSecretServer(MagicMock):
RESPONSE = '{"foo": "bar"}'
def get_secret_json(self, path):
return self.RESPONSE
class MockFaultySecretServer(MagicMock):
def get_secret_json(self, path):
raise SecretServerError
@patch(make_absolute("SecretServer"), MockSecretServer())
class TestTSSClient(TestCase):
def setUp(self):
self.server_params = {
"base_url": "",
"username": "",
"domain": "",
"password": "",
"api_path_uri": "",
"token_path_uri": "",
}
def test_from_params(self):
with patch(make_absolute("HAS_TSS_AUTHORIZER"), False):
self.assert_client_version("v0")
with patch.dict(self.server_params, {"domain": "foo"}):
with self.assertRaises(tss.AnsibleError):
self._get_client()
with patch.multiple(
TSS_IMPORT_PATH,
HAS_TSS_AUTHORIZER=True,
PasswordGrantAuthorizer=DEFAULT,
DomainPasswordGrantAuthorizer=DEFAULT,
):
self.assert_client_version("v1")
with patch.dict(self.server_params, {"domain": "foo"}):
self.assert_client_version("v1")
def assert_client_version(self, version):
version_to_class = {"v0": tss.TSSClientV0, "v1": tss.TSSClientV1}
client = self._get_client()
self.assertIsInstance(client, version_to_class[version])
def _get_client(self):
return tss.TSSClient.from_params(**self.server_params)
class TestLookupModule(TestCase):
VALID_TERMS = [1]
INVALID_TERMS = ["foo"]
def setUp(self):
self.lookup = lookup_loader.get("community.general.tss")
tss._client_cache.clear()
self.addCleanup(tss._client_cache.clear)
@patch.multiple(TSS_IMPORT_PATH, HAS_TSS_SDK=False, SecretServer=MockSecretServer)
def test_missing_sdk(self):
with self.assertRaises(tss.AnsibleError):
self._run_lookup(self.VALID_TERMS)
@patch.multiple(TSS_IMPORT_PATH, HAS_TSS_SDK=True, SecretServerError=SecretServerError)
def test_get_secret_json(self):
with patch(make_absolute("SecretServer"), MockSecretServer):
self.assertListEqual([MockSecretServer.RESPONSE], self._run_lookup(self.VALID_TERMS))
with self.assertRaises(tss.AnsibleOptionsError):
self._run_lookup(self.INVALID_TERMS)
with patch(make_absolute("SecretServer"), MockFaultySecretServer):
tss._client_cache.clear()
with self.assertRaises(tss.AnsibleError):
self._run_lookup(self.VALID_TERMS)
@patch.multiple(TSS_IMPORT_PATH, HAS_TSS_SDK=True, SecretServerError=SecretServerError)
def test_client_cache_reuse(self):
wrapper = MagicMock()
wrapper.get_secret.return_value = "secret"
with patch(make_absolute("TSSClient.from_params"), return_value=wrapper) as from_params:
self._run_lookup(self.VALID_TERMS)
self._run_lookup(self.VALID_TERMS)
self.assertEqual(from_params.call_count, 1)
@patch.multiple(TSS_IMPORT_PATH, HAS_TSS_SDK=True, SecretServerError=SecretServerError)
def test_cache_survives_plugin_reinstantiation(self):
wrapper = MagicMock()
wrapper.get_secret.return_value = "secret"
kwargs = {"base_url": "dummy", "username": "dummy", "password": "dummy"}
with patch(make_absolute("TSSClient.from_params"), return_value=wrapper) as from_params:
self.lookup.run(self.VALID_TERMS, [], **kwargs)
# A brand-new plugin instance (as ansible-core creates per invocation)
# must reuse the module-level cache instead of building a new client.
fresh = lookup_loader.get("community.general.tss")
fresh.run(self.VALID_TERMS, [], **kwargs)
self.assertEqual(from_params.call_count, 1)
@patch.multiple(TSS_IMPORT_PATH, HAS_TSS_SDK=True, SecretServerError=SecretServerError)
def test_token_auth_is_not_cached(self):
wrapper = MagicMock()
wrapper.get_secret.return_value = "secret"
with patch(make_absolute("TSSClient.from_params"), return_value=wrapper) as from_params:
self._run_lookup(self.VALID_TERMS, base_url="dummy", token="token")
self._run_lookup(self.VALID_TERMS, base_url="dummy", token="token")
self.assertEqual(from_params.call_count, 2)
@patch.multiple(TSS_IMPORT_PATH, HAS_TSS_SDK=True, SecretServerError=SecretServerError)
def test_cache_separates_clients_by_credential_identity(self):
wrapper = MagicMock()
wrapper.get_secret.return_value = "secret"
with patch(make_absolute("TSSClient.from_params"), return_value=wrapper) as from_params:
self._run_lookup(self.VALID_TERMS, base_url="dummy", username="alice", password="p")
self._run_lookup(self.VALID_TERMS, base_url="dummy", username="bob", password="p")
self.assertEqual(from_params.call_count, 2)
self.assertEqual(len(tss._client_cache), 2)
@patch.multiple(TSS_IMPORT_PATH, HAS_TSS_SDK=True, SecretServerError=SecretServerError)
def test_token_path_source_auto_empties_token_path_uri(self):
wrapper = MagicMock()
wrapper.get_secret.return_value = "secret"
with patch(make_absolute("TSSClient.from_params"), return_value=wrapper) as from_params:
self._run_lookup(self.VALID_TERMS, base_url="dummy", username="u", password="p", token_path_source="auto")
self.assertEqual(from_params.call_args.kwargs["token_path_uri"], "")
@patch.multiple(TSS_IMPORT_PATH, HAS_TSS_SDK=True, SecretServerError=SecretServerError)
def test_token_path_source_auto_overrides_explicit_token_path_uri(self):
wrapper = MagicMock()
wrapper.get_secret.return_value = "secret"
with patch(make_absolute("TSSClient.from_params"), return_value=wrapper) as from_params:
self._run_lookup(
self.VALID_TERMS,
base_url="dummy",
username="u",
password="p",
token_path_source="auto",
token_path_uri="/oauth2/token",
)
self.assertEqual(from_params.call_args.kwargs["token_path_uri"], "")
@patch.multiple(TSS_IMPORT_PATH, HAS_TSS_SDK=True, SecretServerError=SecretServerError)
def test_default_token_path_source_uses_configured_token_path_uri(self):
wrapper = MagicMock()
wrapper.get_secret.return_value = "secret"
with patch(make_absolute("TSSClient.from_params"), return_value=wrapper) as from_params:
self._run_lookup(
self.VALID_TERMS,
base_url="dummy",
username="u",
password="p",
token_path_uri="/custom/token",
)
self.assertEqual(from_params.call_args.kwargs["token_path_uri"], "/custom/token")
@patch.multiple(TSS_IMPORT_PATH, HAS_TSS_SDK=True, SecretServerError=SecretServerError)
def test_token_path_source_partitions_cache(self):
wrapper = MagicMock()
wrapper.get_secret.return_value = "secret"
with patch(make_absolute("TSSClient.from_params"), return_value=wrapper) as from_params:
self._run_lookup(self.VALID_TERMS, base_url="dummy", username="u", password="p", token_path_source="auto")
self._run_lookup(self.VALID_TERMS, base_url="dummy", username="u", password="p")
self.assertEqual(from_params.call_count, 2)
self.assertEqual(len(tss._client_cache), 2)
@patch.multiple(
TSS_IMPORT_PATH,
HAS_TSS_SDK=True,
HAS_SS_CLIENT_ERROR=True,
SecretServerError=SecretServerError,
SecretServerClientError=SecretServerClientError,
)
def test_retry_on_client_error_then_success(self):
faulty = MagicMock()
faulty.get_secret.side_effect = SecretServerClientError()
good = MagicMock()
good.get_secret.return_value = "ok"
with patch(make_absolute("TSSClient.from_params"), side_effect=[faulty, good]) as from_params:
self.assertListEqual(["ok"], self._run_lookup(self.VALID_TERMS))
self.assertEqual(from_params.call_count, 2)
@patch.multiple(
TSS_IMPORT_PATH,
HAS_TSS_SDK=True,
HAS_SS_CLIENT_ERROR=True,
SecretServerError=SecretServerError,
SecretServerClientError=SecretServerClientError,
)
def test_retry_exhausted_raises(self):
faulty1 = MagicMock()
faulty1.get_secret.side_effect = SecretServerClientError()
faulty2 = MagicMock()
faulty2.get_secret.side_effect = SecretServerClientError()
with patch(make_absolute("TSSClient.from_params"), side_effect=[faulty1, faulty2]) as from_params:
with self.assertRaises(tss.AnsibleError):
self._run_lookup(self.VALID_TERMS)
self.assertEqual(from_params.call_count, 2)
@patch.multiple(
TSS_IMPORT_PATH,
HAS_TSS_SDK=True,
HAS_SS_CLIENT_ERROR=True,
SecretServerError=SecretServerError,
SecretServerClientError=SecretServerClientError,
)
def test_non_client_error_does_not_retry(self):
faulty = MagicMock()
faulty.get_secret.side_effect = SecretServerError()
with patch(make_absolute("TSSClient.from_params"), side_effect=[faulty, MagicMock()]) as from_params:
with self.assertRaises(tss.AnsibleError):
self._run_lookup(self.VALID_TERMS)
self.assertEqual(from_params.call_count, 1)
@patch.multiple(
TSS_IMPORT_PATH,
HAS_TSS_SDK=True,
HAS_SS_CLIENT_ERROR=False,
SecretServerError=SecretServerError,
SecretServerClientError=None,
)
def test_missing_client_error_symbol_does_not_retry(self):
faulty = MagicMock()
faulty.get_secret.side_effect = SecretServerClientError()
with patch(make_absolute("TSSClient.from_params"), side_effect=[faulty, MagicMock()]) as from_params:
with self.assertRaises(tss.AnsibleError):
self._run_lookup(self.VALID_TERMS)
self.assertEqual(from_params.call_count, 1)
def _run_lookup(self, terms, variables=None, **kwargs):
variables = variables or []
kwargs = kwargs or {"base_url": "dummy", "username": "dummy", "password": "dummy"}
return self.lookup.run(terms, variables, **kwargs)
@@ -0,0 +1,84 @@
# 2018.07.26 --- use DictComparison instead of GcpRequest
#
# Copyright (c) 2016, Tom Melendez <tom@supertom.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 unittest
from ansible_collections.community.general.plugins.module_utils._hwc_utils import are_different_dicts
class HwcDictComparisonTestCase(unittest.TestCase):
def test_simple_no_difference(self):
value1 = {"foo": "bar", "test": "original"}
self.assertFalse(are_different_dicts(value1, value1))
def test_simple_different(self):
value1 = {"foo": "bar", "test": "original"}
value2 = {"foo": "bar", "test": "different"}
value3 = {"test": "original"}
self.assertTrue(are_different_dicts(value1, value2))
self.assertTrue(are_different_dicts(value1, value3))
self.assertTrue(are_different_dicts(value2, value3))
def test_nested_dictionaries_no_difference(self):
value1 = {"foo": {"quiet": {"tree": "test"}, "bar": "baz"}, "test": "original"}
self.assertFalse(are_different_dicts(value1, value1))
def test_nested_dictionaries_with_difference(self):
value1 = {"foo": {"quiet": {"tree": "test"}, "bar": "baz"}, "test": "original"}
value2 = {"foo": {"quiet": {"tree": "baz"}, "bar": "hello"}, "test": "original"}
value3 = {"foo": {"quiet": {"tree": "test"}, "bar": "baz"}}
self.assertTrue(are_different_dicts(value1, value2))
self.assertTrue(are_different_dicts(value1, value3))
self.assertTrue(are_different_dicts(value2, value3))
def test_arrays_strings_no_difference(self):
value1 = {"foo": ["baz", "bar"]}
self.assertFalse(are_different_dicts(value1, value1))
def test_arrays_strings_with_difference(self):
value1 = {
"foo": [
"baz",
"bar",
]
}
value2 = {"foo": ["baz", "hello"]}
value3 = {
"foo": [
"bar",
]
}
self.assertTrue(are_different_dicts(value1, value2))
self.assertTrue(are_different_dicts(value1, value3))
self.assertTrue(are_different_dicts(value2, value3))
def test_arrays_dicts_with_no_difference(self):
value1 = {"foo": [{"test": "value", "foo": "bar"}, {"different": "dict"}]}
self.assertFalse(are_different_dicts(value1, value1))
def test_arrays_dicts_with_difference(self):
value1 = {"foo": [{"test": "value", "foo": "bar"}, {"different": "dict"}]}
value2 = {
"foo": [
{"test": "value2", "foo": "bar2"},
]
}
value3 = {"foo": [{"test": "value", "foo": "bar"}]}
self.assertTrue(are_different_dicts(value1, value2))
self.assertTrue(are_different_dicts(value1, value3))
self.assertTrue(are_different_dicts(value2, value3))
@@ -0,0 +1,38 @@
# 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
import unittest
from ansible_collections.community.general.plugins.module_utils._hwc_utils import HwcModuleException, navigate_value
class HwcUtilsTestCase(unittest.TestCase):
def setUp(self):
super().setUp()
def test_navigate_value(self):
value = {
"foo": {
"quiet": {"tree": "test", "trees": [0, 1]},
}
}
self.assertEqual(navigate_value(value, ["foo", "quiet", "tree"]), "test")
self.assertEqual(navigate_value(value, ["foo", "quiet", "trees"], {"foo.quiet.trees": 1}), 1)
self.assertRaisesRegex(
HwcModuleException, r".* key\(q\) is not exist in dict", navigate_value, value, ["foo", "q", "tree"]
)
self.assertRaisesRegex(
HwcModuleException,
r".* the index is out of list",
navigate_value,
value,
["foo", "quiet", "trees"],
{"foo.quiet.trees": 2},
)
@@ -0,0 +1,32 @@
#
# Copyright (c) 2019, 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
from __future__ import annotations
class AnsibleModuleException(Exception):
def __init__(self, *args, **kwargs):
self.args = args
self.kwargs = kwargs
class ExitJsonException(AnsibleModuleException):
pass
class FailJsonException(AnsibleModuleException):
pass
class FakeAnsibleModule:
def __init__(self, params=None, check_mode=False):
self.params = params
self.check_mode = check_mode
def exit_json(self, *args, **kwargs):
raise ExitJsonException(*args, **kwargs)
def fail_json(self, *args, **kwargs):
raise FailJsonException(*args, **kwargs)
@@ -0,0 +1,66 @@
#
# Copyright (c) 2019, 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
from __future__ import annotations
FAKE_API_VERSION = "1.1"
class Failure(Exception):
def __init__(self, details):
self.details = details
def __str__(self):
return str(self.details)
class Session:
def __init__(self, uri, transport=None, encoding=None, verbose=0, allow_none=1, ignore_ssl=False):
self.transport = transport
self._session = None
self.last_login_method = None
self.last_login_params = None
self.API_version = FAKE_API_VERSION
def _get_api_version(self):
return FAKE_API_VERSION
def _login(self, method, params):
self._session = "OpaqueRef:fake-xenapi-session-ref"
self.last_login_method = method
self.last_login_params = params
self.API_version = self._get_api_version()
def _logout(self):
self._session = None
self.last_login_method = None
self.last_login_params = None
self.API_version = FAKE_API_VERSION
def xenapi_request(self, methodname, params):
if methodname.startswith("login"):
self._login(methodname, params)
return None
elif methodname == "logout" or methodname == "session.logout":
self._logout()
return None
else:
# Should be patched with mocker.patch().
return None
def __getattr__(self, name):
if name == "handle":
return self._session
elif name == "xenapi":
# Should be patched with mocker.patch().
return None
elif name.startswith("login") or name.startswith("slave_local"):
return lambda *params: self._login(name, params)
elif name == "logout":
return self._logout
def xapi_local():
return Session("http://_var_lib_xcp_xapi/")
@@ -0,0 +1,24 @@
#
# Copyright (c) 2019, 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
from __future__ import annotations
def fake_xenapi_ref(xenapi_class):
return f"OpaqueRef:fake-xenapi-{xenapi_class}-ref"
testcase_bad_xenapi_refs = {
"params": [
None,
"",
"OpaqueRef:NULL",
],
"ids": [
"none",
"empty",
"ref-null",
],
}
@@ -0,0 +1,110 @@
#
# Copyright (c) 2019, 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
from __future__ import annotations
import importlib
import json
import os
from unittest.mock import MagicMock
import pytest
from .FakeAnsibleModule import FakeAnsibleModule
XENSERVER_MODULE_UTILS_PATH = "ansible_collections.community.general.plugins.module_utils._xenserver"
@pytest.fixture
def fake_ansible_module(request):
"""Returns fake AnsibleModule with fake module params."""
if hasattr(request, "param"):
return FakeAnsibleModule(request.param)
else:
params = {
"hostname": "somehost",
"username": "someuser",
"password": "somepwd",
"validate_certs": True,
}
return FakeAnsibleModule(params)
@pytest.fixture(autouse=True)
def XenAPI(mocker):
"""Imports and returns fake XenAPI module."""
# Import of fake XenAPI module is wrapped by fixture so that it does not
# affect other unit tests which could potentially also use XenAPI module.
fake_xenapi = importlib.import_module(
"ansible_collections.community.general.tests.unit.plugins.module_utils._xenserver.FakeXenAPI"
)
mocker.patch(f"{XENSERVER_MODULE_UTILS_PATH}.HAS_XENAPI", True)
mocker.patch(f"{XENSERVER_MODULE_UTILS_PATH}.XenAPI", fake_xenapi, create=True)
return fake_xenapi
@pytest.fixture(autouse=True)
def xenserver(XenAPI):
"""Imports and returns xenserver module util."""
from ansible_collections.community.general.plugins.module_utils import _xenserver as xenserver
return xenserver
@pytest.fixture
def mock_xenapi_failure(XenAPI, mocker):
"""
Returns mock object that raises XenAPI.Failure on any XenAPI
method call.
"""
fake_error_msg = "Fake XAPI method call error!"
# We need to use our MagicMock based class that passes side_effect to its
# children because calls to xenapi methods can generate an arbitrary
# hierarchy of mock objects. Any such object when called should use the
# same side_effect as its parent mock object.
class MagicMockSideEffect(MagicMock):
def _get_child_mock(self, **kw):
child_mock = super()._get_child_mock(**kw)
child_mock.side_effect = self.side_effect
return child_mock
mocked_xenapi = mocker.patch.object(XenAPI.Session, "xenapi", new=MagicMockSideEffect(), create=True)
mocked_xenapi.side_effect = XenAPI.Failure(fake_error_msg)
return mocked_xenapi, fake_error_msg
@pytest.fixture
def fixture_data_from_file(request):
"""Loads fixture data from files."""
if not hasattr(request, "param"):
return {}
fixture_path = os.path.join(os.path.dirname(__file__), "fixtures")
fixture_data = {}
if isinstance(request.param, str):
request.param = [request.param]
for fixture_name in request.param:
path = os.path.join(fixture_path, fixture_name)
with open(path) as f:
data = f.read()
try:
data = json.loads(data)
except Exception:
pass
fixture_data[fixture_name] = data
return fixture_data
@@ -0,0 +1,75 @@
{
"cdrom": {
"type": "none"
},
"customization_agent": "native",
"disks": [
{
"name": "ansible-test-vm-1-C",
"name_desc": "C:\\",
"os_device": "xvda",
"size": 42949672960,
"sr": "Ansible Test Storage 1",
"sr_uuid": "767b30e4-f8db-a83d-8ba7-f5e6e732e06f",
"uuid": "b807f67b-3f37-4a6e-ad6c-033f812ab093",
"vbd_userdevice": "0",
"vdi_type": "vhd"
}
],
"domid": "143",
"folder": "/Ansible/Test",
"hardware": {
"memory_mb": 2048,
"num_cpu_cores_per_socket": 2,
"num_cpus": 2
},
"home_server": "",
"is_template": false,
"name": "ansible-test-vm-1",
"name_desc": "Created by Ansible",
"networks": [
{
"gateway": "10.0.0.1",
"gateway6": "",
"ip": "10.0.0.2",
"ip6": [
"fe80:0000:0000:0000:11e1:12c9:ef3b:75a0"
],
"mac": "7a:a6:48:1e:31:46",
"mtu": "1500",
"name": "Host internal management network",
"netmask": "255.255.255.0",
"prefix": "24",
"prefix6": "",
"vif_device": "0"
}
],
"other_config": {
"base_template_name": "Windows Server 2016 (64-bit)",
"folder": "/Ansible/Test",
"import_task": "OpaqueRef:e43eb71c-45d6-5351-09ff-96e4fb7d0fa5",
"install-methods": "cdrom",
"instant": "true",
"mac_seed": "366fe8e0-878b-4320-8731-90d1ed3c0b93"
},
"platform": {
"acpi": "1",
"apic": "true",
"cores-per-socket": "2",
"device_id": "0002",
"hpet": "true",
"nx": "true",
"pae": "true",
"timeoffset": "-28800",
"vga": "std",
"videoram": "8",
"viridian": "true",
"viridian_reference_tsc": "true",
"viridian_time_ref_count": "true"
},
"state": "poweredon",
"uuid": "81c373d7-a407-322f-911b-31386eb5215d",
"xenstore_data": {
"vm-data": ""
}
}
@@ -0,0 +1,3 @@
GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
SPDX-License-Identifier: GPL-3.0-or-later
SPDX-FileCopyrightText: Ansible Project

Some files were not shown because too many files have changed in this diff Show More