Initial commit
This commit is contained in:
@@ -0,0 +1,14 @@
|
||||
from ansible.plugins.callback import CallbackBase
|
||||
|
||||
|
||||
class CallbackModule(CallbackBase):
|
||||
CALLBACK_VERSION = 2.0
|
||||
CALLBACK_TYPE = 'aggregate'
|
||||
CALLBACK_NAME = 'other_callback'
|
||||
|
||||
def v2_playbook_on_play_start(self, play):
|
||||
pass
|
||||
|
||||
def v2_runner_on_ok(self, result):
|
||||
pass
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
import os
|
||||
import shutil
|
||||
|
||||
import pytest
|
||||
import pexpect
|
||||
from ansible_runner.runner_config import RunnerConfig
|
||||
|
||||
|
||||
@pytest.fixture(scope='function')
|
||||
def rc(tmpdir):
|
||||
rc = RunnerConfig(str(tmpdir))
|
||||
rc.suppress_ansible_output = True
|
||||
rc.expect_passwords = {
|
||||
pexpect.TIMEOUT: None,
|
||||
pexpect.EOF: None
|
||||
}
|
||||
rc.cwd = str(tmpdir)
|
||||
rc.env = {}
|
||||
rc.job_timeout = 10
|
||||
rc.idle_timeout = 0
|
||||
rc.pexpect_timeout = 2.
|
||||
rc.pexpect_use_poll = True
|
||||
return rc
|
||||
|
||||
|
||||
# TODO: determine if we want to add docker / podman
|
||||
# to zuul instances in order to run these tests
|
||||
@pytest.fixture(scope="session", autouse=True)
|
||||
def container_runtime_available():
|
||||
import subprocess
|
||||
import warnings
|
||||
|
||||
runtimes_available = True
|
||||
for runtime in ('docker', 'podman'):
|
||||
try:
|
||||
subprocess.run([runtime, '-v'])
|
||||
except FileNotFoundError:
|
||||
warnings.warn(UserWarning(f"{runtime} not available"))
|
||||
runtimes_available = False
|
||||
return runtimes_available
|
||||
|
||||
|
||||
# TODO: determine if we want to add docker / podman
|
||||
# to zuul instances in order to run these tests
|
||||
@pytest.fixture(scope="session")
|
||||
def container_runtime_installed():
|
||||
import subprocess
|
||||
|
||||
for runtime in ('podman', 'docker'):
|
||||
try:
|
||||
subprocess.run([runtime, '-v'])
|
||||
return runtime
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
pytest.skip('No container runtime is available.')
|
||||
|
||||
|
||||
@pytest.fixture(scope='session')
|
||||
def clear_integration_artifacts(request):
|
||||
'''Fixture is session scoped to allow parallel runs without error
|
||||
'''
|
||||
if 'PYTEST_XDIST_WORKER' in os.environ:
|
||||
# we never want to clean artifacts if running parallel tests
|
||||
# because we cannot know when all processes are finished and it is
|
||||
# safe to clean up
|
||||
return
|
||||
|
||||
def rm_integration_artifacts():
|
||||
path = "test/integration/artifacts"
|
||||
if os.path.exists(path):
|
||||
shutil.rmtree(path)
|
||||
|
||||
request.addfinalizer(rm_integration_artifacts)
|
||||
@@ -0,0 +1,71 @@
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import yaml
|
||||
|
||||
from tempfile import NamedTemporaryFile
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def tmp_file_maker():
|
||||
"""Fixture to return temporary file maker."""
|
||||
def tmp_file(text):
|
||||
with NamedTemporaryFile(delete=False) as tempf:
|
||||
tempf.write(bytes(text, 'UTF-8'))
|
||||
return tempf.name
|
||||
return tmp_file
|
||||
|
||||
|
||||
class CompletedProcessProxy(object):
|
||||
|
||||
def __init__(self, result):
|
||||
self.result = result
|
||||
|
||||
def __getattr__(self, attr):
|
||||
return getattr(self.result, attr)
|
||||
|
||||
@property
|
||||
def json(self):
|
||||
try:
|
||||
response_json = json.loads(self.stdout)
|
||||
except json.JSONDecodeError:
|
||||
pytest.fail(
|
||||
f"Unable to convert the response to a valid json - stdout: {self.stdout}, stderr: {self.stderr}"
|
||||
)
|
||||
return response_json
|
||||
|
||||
@property
|
||||
def yaml(self):
|
||||
return yaml.safe_load(self.stdout)
|
||||
|
||||
|
||||
@pytest.fixture(scope='function')
|
||||
def cli(request):
|
||||
def run(args, *a, **kw):
|
||||
if not kw.pop('bare', None):
|
||||
args = ['ansible-runner',] + args
|
||||
kw['encoding'] = 'utf-8'
|
||||
if 'check' not in kw:
|
||||
# By default we want to fail if a command fails to run. Tests that
|
||||
# want to skip this can pass check=False when calling this fixture
|
||||
kw['check'] = True
|
||||
if 'stdout' not in kw:
|
||||
kw['stdout'] = subprocess.PIPE
|
||||
if 'stderr' not in kw:
|
||||
kw['stderr'] = subprocess.PIPE
|
||||
|
||||
kw.setdefault('env', os.environ.copy()).update({
|
||||
'LANG': 'en_US.UTF-8'
|
||||
})
|
||||
|
||||
try:
|
||||
ret = CompletedProcessProxy(subprocess.run(' '.join(args), shell=True, *a, **kw))
|
||||
except subprocess.CalledProcessError as err:
|
||||
pytest.fail(
|
||||
f"Running {err.cmd} resulted in a non-zero return code: {err.returncode} - stdout: {err.stdout}, stderr: {err.stderr}"
|
||||
)
|
||||
|
||||
return ret
|
||||
return run
|
||||
@@ -0,0 +1 @@
|
||||
localhost
|
||||
@@ -0,0 +1,38 @@
|
||||
---
|
||||
- hosts: localhost
|
||||
gather_facts: true
|
||||
vars:
|
||||
cgroup_search_terms: docker\|lxc\|podman\|oci
|
||||
is_container: false
|
||||
is_podman: false
|
||||
is_docker: false
|
||||
tasks:
|
||||
- debug: msg="Test if we are in a container!"
|
||||
|
||||
- name: 'Look for container env var defined in /proc/1/environ'
|
||||
shell: "grep 'container=' /proc/1/environ"
|
||||
register: container_proc_environ
|
||||
ignore_errors: true
|
||||
|
||||
- name: 'Look for container info defined in /proc/1/cgroup'
|
||||
shell: "grep '{{ cgroup_search_terms}}' /proc/1/cgroup"
|
||||
register: container_proc_cgroup
|
||||
ignore_errors: true
|
||||
|
||||
- name: 'Found evidence that we are in docker container'
|
||||
set_fact:
|
||||
is_docker: true
|
||||
when: (('container' in ansible_env and ansible_env.container == 'docker') or ansible_virtualization_type == 'docker')
|
||||
|
||||
- name: 'Found evidence that we are in podman container'
|
||||
set_fact:
|
||||
is_podman: true
|
||||
when: ('container' in ansible_env and ansible_env.container == 'podman')
|
||||
|
||||
- name: 'Found evidence that we are in a container'
|
||||
set_fact:
|
||||
is_container: true
|
||||
when: is_docker or is_podman or container_proc_environ.rc == 0 or container_proc_cgroup.rc == 0
|
||||
|
||||
- fail:
|
||||
when: not (is_container)
|
||||
@@ -0,0 +1,73 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
import os
|
||||
|
||||
import pytest
|
||||
|
||||
HERE = os.path.abspath(os.path.dirname(__file__))
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def skip_if_no_podman(container_runtime_installed):
|
||||
if container_runtime_installed != 'podman':
|
||||
pytest.skip('podman container runtime(s) not available')
|
||||
|
||||
|
||||
@pytest.mark.serial
|
||||
def test_module_run(cli, skip_if_no_podman):
|
||||
r = cli(['run', '-m', 'ping','--hosts', 'localhost', os.path.join(HERE, 'priv_data')])
|
||||
assert '"ping": "pong"' in r.stdout
|
||||
|
||||
|
||||
@pytest.mark.serial
|
||||
def test_playbook_run(cli, skip_if_no_podman):
|
||||
r = cli(['run', os.path.join(HERE,'priv_data'), '-p', 'test-container.yml'])
|
||||
assert 'PLAY RECAP *******' in r.stdout
|
||||
assert 'failed=0' in r.stdout
|
||||
|
||||
|
||||
@pytest.mark.serial
|
||||
def test_provide_env_var(cli, skip_if_no_podman, test_data_dir):
|
||||
r = cli(['run', os.path.join(test_data_dir, 'job_env'), '-p', 'printenv.yml'])
|
||||
assert 'gifmyvqok2' in r.stdout, r.stdout
|
||||
|
||||
|
||||
@pytest.mark.serial
|
||||
def test_adhoc_localhost_setup(cli, skip_if_no_podman, container_runtime_installed):
|
||||
r = cli(
|
||||
[
|
||||
'adhoc',
|
||||
'--private-data-dir', os.path.join(HERE,'priv_data'),
|
||||
'--container-runtime', container_runtime_installed,
|
||||
'localhost', '-m', 'setup'
|
||||
]
|
||||
)
|
||||
# TODO: look for some fact that indicates we are in container?
|
||||
assert '"ansible_facts": {' in r.stdout
|
||||
|
||||
|
||||
@pytest.mark.serial
|
||||
def test_playbook_with_private_data_dir(cli, skip_if_no_podman, container_runtime_installed):
|
||||
# tests using a private_data_dir in conjunction with an absolute path
|
||||
r = cli(
|
||||
[
|
||||
'playbook',
|
||||
'--private-data-dir', os.path.join(HERE,'priv_data'),
|
||||
'--container-runtime', container_runtime_installed,
|
||||
os.path.join(HERE, 'priv_data/project/test-container.yml')
|
||||
]
|
||||
)
|
||||
assert 'PLAY RECAP *******' in r.stdout
|
||||
assert 'failed=0' in r.stdout
|
||||
|
||||
|
||||
@pytest.mark.serial
|
||||
def test_playbook_with_relative_path(cli, skip_if_no_podman, container_runtime_installed):
|
||||
r = cli(
|
||||
[
|
||||
'playbook',
|
||||
'--container-runtime', container_runtime_installed,
|
||||
'test/integration/containerized/priv_data/project/test-container.yml'
|
||||
]
|
||||
)
|
||||
assert 'PLAY RECAP *******' in r.stdout
|
||||
assert 'failed=0' in r.stdout
|
||||
@@ -0,0 +1,72 @@
|
||||
import os
|
||||
import shutil
|
||||
import time
|
||||
|
||||
import pytest
|
||||
|
||||
from ansible_runner.interface import run
|
||||
|
||||
|
||||
def is_running(cli, container_runtime_installed, container_name):
|
||||
cmd = [container_runtime_installed, 'ps', '-aq', '--filter', 'name=ansible_runner_foo_bar']
|
||||
r = cli(cmd, bare=True)
|
||||
output = '{}{}'.format(r.stdout, r.stderr)
|
||||
print(' '.join(cmd))
|
||||
print(output)
|
||||
return output.strip()
|
||||
|
||||
|
||||
class CancelStandIn:
|
||||
def __init__(self, runtime, cli, delay=0.2):
|
||||
self.runtime = runtime
|
||||
self.cli = cli
|
||||
self.delay = 0.2
|
||||
self.checked_running = False
|
||||
self.start_time = None
|
||||
|
||||
def cancel(self):
|
||||
# Avoid checking for some initial delay to allow container startup
|
||||
if not self.start_time:
|
||||
self.start_time = time.time()
|
||||
if time.time() - self.start_time < self.delay:
|
||||
return False
|
||||
# guard against false passes by checking for running container
|
||||
if not self.checked_running:
|
||||
for i in range(5):
|
||||
if is_running(self.cli, self.runtime, 'ansible_runner_foo_bar'):
|
||||
break
|
||||
time.sleep(0.2)
|
||||
else:
|
||||
print(self.cli([self.runtime, 'ps', '-a'], bare=True).stdout)
|
||||
raise Exception('Never spawned expected container')
|
||||
self.checked_running = True
|
||||
# Established that container was running, now we cancel job
|
||||
return True
|
||||
|
||||
|
||||
@pytest.mark.serial
|
||||
def test_cancel_will_remove_container(test_data_dir, container_runtime_installed, cli):
|
||||
private_data_dir = os.path.join(test_data_dir, 'sleep')
|
||||
|
||||
env_dir = os.path.join(private_data_dir, 'env')
|
||||
if os.path.exists(env_dir):
|
||||
shutil.rmtree(env_dir)
|
||||
|
||||
cancel_standin = CancelStandIn(container_runtime_installed, cli)
|
||||
|
||||
res = run(
|
||||
private_data_dir=private_data_dir,
|
||||
playbook='sleep.yml',
|
||||
settings={
|
||||
'process_isolation_executable': container_runtime_installed,
|
||||
'process_isolation': True
|
||||
},
|
||||
cancel_callback=cancel_standin.cancel,
|
||||
ident='foo?bar' # question mark invalid char, but should still work
|
||||
)
|
||||
assert res.rc == 254, res.stdout.read()
|
||||
assert res.status == 'canceled'
|
||||
|
||||
assert not is_running(
|
||||
cli, container_runtime_installed, 'ansible_runner_foo_bar'
|
||||
), 'Found a running container, they should have all been stopped'
|
||||
@@ -0,0 +1,7 @@
|
||||
FROM registry.access.redhat.com/ubi8/ubi
|
||||
|
||||
RUN yum -y install python3-pip gcc python3-devel openssh-clients
|
||||
RUN pip3 install https://github.com/ansible/ansible/archive/devel.tar.gz
|
||||
RUN pip3 install https://github.com/ansible/ansible-runner/archive/devel.tar.gz
|
||||
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
---
|
||||
- name: Run some basic system automation stuff
|
||||
hosts: rhel8
|
||||
tasks:
|
||||
- name: install some basic packages
|
||||
yum:
|
||||
name:
|
||||
- tmux
|
||||
- git
|
||||
- vim-enhanced
|
||||
- python3
|
||||
|
||||
- name: enable journald persistent storage
|
||||
file:
|
||||
path: /var/log/journal
|
||||
state: directory
|
||||
|
||||
- name: Get tuned profile
|
||||
slurp:
|
||||
src: /etc/tuned/active_profile
|
||||
register: tuned_active_profile
|
||||
|
||||
- debug:
|
||||
msg: "{{ tuned_active_profile['content'] | b64decode | trim }}"
|
||||
|
||||
- name: tuned-adm set throughput-performance
|
||||
shell: /usr/sbin/tuned-adm profile throughput-performance
|
||||
when: "tuned_active_profile['content'] | b64decode | trim != 'throughput-performance'"
|
||||
|
||||
- name: don't allow password based ssh
|
||||
lineinfile:
|
||||
path: /etc/ssh/sshd_config
|
||||
regexp: '^PasswordAuthentication'
|
||||
line: "PasswordAuthentication no"
|
||||
notify: restart sshd
|
||||
|
||||
handlers:
|
||||
- name: restart sshd
|
||||
service:
|
||||
name: sshd
|
||||
state: restarted
|
||||
@@ -0,0 +1,2 @@
|
||||
[rhel8]
|
||||
azure-rhel8 ansible_host=168.62.187.3 ansible_user=admiller ansible_become=yes
|
||||
@@ -0,0 +1,2 @@
|
||||
[all]
|
||||
localhost ansible_connection=local
|
||||
@@ -0,0 +1,2 @@
|
||||
[all]
|
||||
localhost ansible_connection=local ansible_python_interpreter-"/usr/bin/env python"
|
||||
@@ -0,0 +1,6 @@
|
||||
---
|
||||
- hosts: all
|
||||
tasks:
|
||||
- debug: msg="Before!"
|
||||
- shell: sleep 90
|
||||
- debug: msg="After!"
|
||||
@@ -0,0 +1 @@
|
||||
{install_date: 'Mon Aug 20 13:21:07 2018', version: master}
|
||||
@@ -0,0 +1,13 @@
|
||||
---
|
||||
galaxy_info:
|
||||
author: Ben Thomasson
|
||||
description: Hello World role
|
||||
company: Red Hat
|
||||
|
||||
license: Apache
|
||||
|
||||
min_ansible_version: 1.2
|
||||
|
||||
galaxy_tags:
|
||||
- hello
|
||||
dependencies: []
|
||||
@@ -0,0 +1,2 @@
|
||||
---
|
||||
- debug:
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
- hosts: all
|
||||
gather_facts: false
|
||||
roles:
|
||||
- name: benthomasson.hello_role
|
||||
@@ -0,0 +1,249 @@
|
||||
import os
|
||||
import sys
|
||||
import uuid
|
||||
import json
|
||||
import random
|
||||
import string
|
||||
import tempfile
|
||||
import shutil
|
||||
|
||||
from pytest import raises
|
||||
from unittest.mock import patch
|
||||
|
||||
from ansible_runner.__main__ import main
|
||||
|
||||
|
||||
def random_string():
|
||||
return ''.join(random.choice(string.ascii_uppercase + string.digits)
|
||||
for _ in range(random.randint(3, 20)))
|
||||
|
||||
|
||||
def random_json(keys=None):
|
||||
data = dict()
|
||||
if keys:
|
||||
for key in keys:
|
||||
data[key] = random_string()
|
||||
else:
|
||||
for _ in range(0, 5):
|
||||
data[random_string()] = random_string()
|
||||
return json.dumps(data)
|
||||
|
||||
|
||||
def cmdline(command, *args):
|
||||
cmdline = ['ansible-runner', command]
|
||||
cmdline.extend(args)
|
||||
sys.argv = cmdline
|
||||
|
||||
|
||||
def test_main_bad_private_data_dir():
|
||||
tmpfile = os.path.join('/tmp', str(uuid.uuid4().hex))
|
||||
open(tmpfile, 'w').write(random_string())
|
||||
|
||||
cmdline('run', tmpfile, '-p', 'fake')
|
||||
|
||||
try:
|
||||
with raises(OSError):
|
||||
main()
|
||||
finally:
|
||||
os.remove(tmpfile)
|
||||
|
||||
|
||||
def run_role(options, private_data_dir=None, expected_rc=0):
|
||||
try:
|
||||
private_data_dir = private_data_dir or tempfile.mkdtemp()
|
||||
args = ['run', private_data_dir]
|
||||
args.extend(options)
|
||||
|
||||
with patch('ansible_runner.interface.run') as mock_run:
|
||||
with raises(SystemExit) as exc:
|
||||
main()
|
||||
assert exc.type == SystemExit
|
||||
assert exc.value.code == expected_rc
|
||||
|
||||
finally:
|
||||
shutil.rmtree(private_data_dir)
|
||||
return mock_run
|
||||
|
||||
|
||||
def test_cmdline_role_defaults():
|
||||
"""Run a role directly with all command line defaults
|
||||
"""
|
||||
private_data_dir = tempfile.mkdtemp()
|
||||
options = ['-r' , 'test']
|
||||
|
||||
playbook = [{'hosts': 'all', 'gather_facts': True, 'roles': [{'role': 'test'}]}]
|
||||
|
||||
run_options = {
|
||||
'private_data_dir': private_data_dir,
|
||||
'playbook': playbook
|
||||
}
|
||||
|
||||
result = run_role(options, private_data_dir)
|
||||
result.called_with_args([run_options])
|
||||
|
||||
|
||||
def test_cmdline_role_skip_facts():
|
||||
"""Run a role directly and set --role-skip-facts option
|
||||
"""
|
||||
private_data_dir = tempfile.mkdtemp()
|
||||
options = ['-r' , 'test', '--role-skip-facts']
|
||||
|
||||
playbook = [{'hosts': 'all', 'gather_facts': False, 'roles': [{'role': 'test'}]}]
|
||||
|
||||
run_options = {
|
||||
'private_data_dir': private_data_dir,
|
||||
'playbook': playbook
|
||||
}
|
||||
|
||||
result = run_role(options, private_data_dir)
|
||||
result.called_with_args([run_options])
|
||||
|
||||
|
||||
def test_cmdline_role_inventory():
|
||||
"""Run a role directly and set --inventory option
|
||||
"""
|
||||
private_data_dir = tempfile.mkdtemp()
|
||||
options = ['-r' , 'test', '--inventory hosts']
|
||||
|
||||
playbook = [{'hosts': 'all', 'gather_facts': False, 'roles': [{'role': 'test'}]}]
|
||||
|
||||
run_options = {
|
||||
'private_data_dir': private_data_dir,
|
||||
'playbook': playbook,
|
||||
'inventory': 'hosts'
|
||||
}
|
||||
|
||||
result = run_role(options, private_data_dir)
|
||||
result.called_with_args([run_options])
|
||||
|
||||
|
||||
def test_cmdline_role_vars():
|
||||
"""Run a role directly and set --role-vars option
|
||||
"""
|
||||
private_data_dir = tempfile.mkdtemp()
|
||||
options = ['-r' , 'test', '--role-vars "foo=bar"']
|
||||
|
||||
playbook = [{
|
||||
'hosts': 'all',
|
||||
'gather_facts': False,
|
||||
'roles': [{
|
||||
'role': 'test',
|
||||
'vars': {'foo': 'bar'}
|
||||
}]
|
||||
}]
|
||||
|
||||
run_options = {
|
||||
'private_data_dir': private_data_dir,
|
||||
'playbook': playbook
|
||||
}
|
||||
|
||||
result = run_role(options, private_data_dir)
|
||||
result.called_with_args([run_options])
|
||||
|
||||
|
||||
def test_cmdline_roles_path():
|
||||
"""Run a role directly and set --roles-path option
|
||||
"""
|
||||
private_data_dir = tempfile.mkdtemp()
|
||||
options = ['-r' , 'test', '--roles-path /tmp/roles']
|
||||
|
||||
playbook = [{'hosts': 'all', 'gather_facts': False, 'roles': [{'role': 'test'}]}]
|
||||
|
||||
run_options = {
|
||||
'private_data_dir': private_data_dir,
|
||||
'playbook': playbook,
|
||||
'envvars': {'ANSIBLE_ROLES_PATH': '/tmp/roles'}
|
||||
}
|
||||
|
||||
result = run_role(options, private_data_dir)
|
||||
result.called_with_args([run_options])
|
||||
|
||||
|
||||
def test_cmdline_role_with_playbook_option():
|
||||
"""Test error is raised with invalid command line option '-p'
|
||||
"""
|
||||
cmdline('run', 'private_data_dir', '-r', 'fake', '-p', 'fake')
|
||||
with raises(SystemExit) as exc:
|
||||
main()
|
||||
assert exc == 1
|
||||
|
||||
|
||||
def test_cmdline_playbook(is_pre_ansible28):
|
||||
try:
|
||||
private_data_dir = tempfile.mkdtemp()
|
||||
play = [{'hosts': 'all', 'tasks': [{'debug': {'msg': random_string()}}]}]
|
||||
|
||||
path = os.path.join(private_data_dir, 'project')
|
||||
os.makedirs(path)
|
||||
|
||||
playbook = os.path.join(path, 'main.yaml')
|
||||
with open(playbook, 'w') as f:
|
||||
f.write(json.dumps(play))
|
||||
|
||||
path = os.path.join(private_data_dir, 'inventory')
|
||||
os.makedirs(path)
|
||||
|
||||
inventory = os.path.join(path, 'hosts')
|
||||
with open(inventory, 'w') as f:
|
||||
if is_pre_ansible28:
|
||||
f.write('[all]\nlocalhost ansible_connection=local ansible_python_interpreter="/usr/bin/env python"')
|
||||
else:
|
||||
f.write('[all]\nlocalhost ansible_connection=local')
|
||||
|
||||
cmdline('run', private_data_dir, '-p', playbook, '--inventory', inventory)
|
||||
|
||||
assert main() == 0
|
||||
|
||||
with open(playbook) as f:
|
||||
assert json.loads(f.read()) == play
|
||||
|
||||
finally:
|
||||
shutil.rmtree(private_data_dir)
|
||||
|
||||
|
||||
def test_cmdline_playbook_hosts():
|
||||
"""Test error is raised with trying to pass '--hosts' with '-p'
|
||||
"""
|
||||
cmdline('run', 'private_data_dir', '-p', 'fake', '--hosts', 'all')
|
||||
with raises(SystemExit) as exc:
|
||||
main()
|
||||
assert exc == 1
|
||||
|
||||
|
||||
def test_cmdline_includes_one_option():
|
||||
"""Test error is raised if not '-p', '-m' or '-r'
|
||||
"""
|
||||
cmdline('run', 'private_data_dir')
|
||||
with raises(SystemExit) as exc:
|
||||
main()
|
||||
assert exc == 1
|
||||
|
||||
|
||||
def test_cmdline_cmdline_override(is_pre_ansible28):
|
||||
try:
|
||||
private_data_dir = tempfile.mkdtemp()
|
||||
play = [{'hosts': 'all', 'tasks': [{'debug': {'msg': random_string()}}]}]
|
||||
|
||||
path = os.path.join(private_data_dir, 'project')
|
||||
os.makedirs(path)
|
||||
|
||||
playbook = os.path.join(path, 'main.yaml')
|
||||
with open(playbook, 'w') as f:
|
||||
f.write(json.dumps(play))
|
||||
path = os.path.join(private_data_dir, 'inventory')
|
||||
os.makedirs(path)
|
||||
|
||||
inventory = os.path.join(path, 'hosts')
|
||||
with open(inventory, 'w') as f:
|
||||
if is_pre_ansible28:
|
||||
f.write('[all]\nlocalhost ansible_connection=local ansible_python_interpreter="/usr/bin/env python"')
|
||||
else:
|
||||
f.write('[all]\nlocalhost ansible_connection=local')
|
||||
|
||||
# privateip: removed --hosts command line option from test beause it is
|
||||
# not a supported combination of cli options
|
||||
#cmdline('run', private_data_dir, '-p', playbook, '--hosts', 'all', '--cmdline', '-e foo=bar')
|
||||
cmdline('run', private_data_dir, '-p', playbook, '--cmdline', '-e foo=bar')
|
||||
assert main() == 0
|
||||
finally:
|
||||
shutil.rmtree(private_data_dir)
|
||||
@@ -0,0 +1,422 @@
|
||||
from __future__ import absolute_import
|
||||
|
||||
import json
|
||||
import os
|
||||
import yaml
|
||||
import six
|
||||
|
||||
from ansible import __version__ as ANSIBLE_VERSION
|
||||
|
||||
from ansible_runner.interface import init_runner
|
||||
|
||||
import pytest
|
||||
|
||||
HERE = os.path.abspath(os.path.dirname(__file__))
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def executor(tmpdir, request, is_pre_ansible28):
|
||||
private_data_dir = six.text_type(tmpdir.mkdir('foo'))
|
||||
|
||||
playbooks = request.node.callspec.params.get('playbook')
|
||||
playbook = list(playbooks.values())[0]
|
||||
envvars = request.node.callspec.params.get('envvars')
|
||||
if envvars is None:
|
||||
envvars = {}
|
||||
# warning messages create verbose events and interfere with assertions
|
||||
envvars["ANSIBLE_DEPRECATION_WARNINGS"] = "False"
|
||||
# python interpreter used is not of much interest, we really want to silence warnings
|
||||
envvars['ANSIBLE_PYTHON_INTERPRETER'] = 'auto_silent'
|
||||
|
||||
if is_pre_ansible28:
|
||||
inventory = 'localhost ansible_connection=local ansible_python_interpreter="/usr/bin/env python"'
|
||||
else:
|
||||
inventory = 'localhost ansible_connection=local'
|
||||
|
||||
|
||||
r = init_runner(
|
||||
private_data_dir=private_data_dir,
|
||||
inventory=inventory,
|
||||
envvars=envvars,
|
||||
playbook=yaml.safe_load(playbook)
|
||||
)
|
||||
|
||||
return r
|
||||
|
||||
|
||||
@pytest.mark.parametrize('event', ['playbook_on_start',
|
||||
'playbook_on_play_start',
|
||||
'playbook_on_task_start', 'runner_on_ok',
|
||||
'playbook_on_stats'])
|
||||
@pytest.mark.parametrize('playbook', [
|
||||
{'helloworld.yml': '''
|
||||
- name: Hello World Sample
|
||||
connection: local
|
||||
hosts: all
|
||||
gather_facts: no
|
||||
tasks:
|
||||
- name: Hello Message
|
||||
debug:
|
||||
msg: "Hello World!"
|
||||
'''}, # noqa
|
||||
{'results_included.yml': '''
|
||||
- name: Run module which generates results list
|
||||
connection: local
|
||||
hosts: all
|
||||
gather_facts: no
|
||||
vars:
|
||||
results: ['foo', 'bar']
|
||||
tasks:
|
||||
- name: Generate results list
|
||||
debug:
|
||||
var: results
|
||||
'''} # noqa
|
||||
], ids=['helloworld.yml', 'results_included.yml'])
|
||||
@pytest.mark.parametrize('envvars', [
|
||||
{'ANSIBLE_CALLBACK_PLUGINS': os.path.join(HERE, 'callback')},
|
||||
{'ANSIBLE_CALLBACK_PLUGINS': ''}],
|
||||
ids=['local-callback-plugin', 'no-callback-plugin']
|
||||
)
|
||||
def test_callback_plugin_receives_events(executor, event, playbook, envvars):
|
||||
executor.run()
|
||||
assert len(list(executor.events))
|
||||
assert event in [task['event'] for task in executor.events]
|
||||
|
||||
|
||||
|
||||
@pytest.mark.parametrize('playbook', [
|
||||
{'no_log_on_ok.yml': '''
|
||||
- name: args should not be logged when task-level no_log is set
|
||||
connection: local
|
||||
hosts: all
|
||||
gather_facts: no
|
||||
tasks:
|
||||
- shell: echo "SENSITIVE"
|
||||
no_log: true
|
||||
'''}, # noqa
|
||||
{'no_log_on_fail.yml': '''
|
||||
- name: failed args should not be logged when task-level no_log is set
|
||||
connection: local
|
||||
hosts: all
|
||||
gather_facts: no
|
||||
tasks:
|
||||
- shell: echo "SENSITIVE"
|
||||
no_log: true
|
||||
failed_when: true
|
||||
ignore_errors: true
|
||||
'''}, # noqa
|
||||
{'no_log_on_skip.yml': '''
|
||||
- name: skipped task args should be suppressed with no_log
|
||||
connection: local
|
||||
hosts: all
|
||||
gather_facts: no
|
||||
tasks:
|
||||
- shell: echo "SENSITIVE"
|
||||
no_log: true
|
||||
when: false
|
||||
'''}, # noqa
|
||||
{'no_log_on_play.yml': '''
|
||||
- name: args should not be logged when play-level no_log set
|
||||
connection: local
|
||||
hosts: all
|
||||
gather_facts: no
|
||||
no_log: true
|
||||
tasks:
|
||||
- shell: echo "SENSITIVE"
|
||||
'''}, # noqa
|
||||
{'async_no_log.yml': '''
|
||||
- name: async task args should suppressed with no_log
|
||||
connection: local
|
||||
hosts: all
|
||||
gather_facts: no
|
||||
no_log: true
|
||||
tasks:
|
||||
- async: 10
|
||||
poll: 1
|
||||
shell: echo "SENSITIVE"
|
||||
no_log: true
|
||||
'''}, # noqa
|
||||
{'with_items.yml': '''
|
||||
- name: with_items tasks should be suppressed with no_log
|
||||
connection: local
|
||||
hosts: all
|
||||
gather_facts: no
|
||||
tasks:
|
||||
- shell: echo {{ item }}
|
||||
no_log: true
|
||||
with_items: [ "SENSITIVE", "SENSITIVE-SKIPPED", "SENSITIVE-FAILED" ]
|
||||
when: item != "SENSITIVE-SKIPPED"
|
||||
failed_when: item == "SENSITIVE-FAILED"
|
||||
ignore_errors: yes
|
||||
'''}, # noqa, NOTE: with_items will be deprecated in 2.9
|
||||
{'loop.yml': '''
|
||||
- name: loop tasks should be suppressed with no_log
|
||||
connection: local
|
||||
hosts: all
|
||||
gather_facts: no
|
||||
tasks:
|
||||
- shell: echo {{ item }}
|
||||
no_log: true
|
||||
loop: [ "SENSITIVE", "SENSITIVE-SKIPPED", "SENSITIVE-FAILED" ]
|
||||
when: item != "SENSITIVE-SKIPPED"
|
||||
failed_when: item == "SENSITIVE-FAILED"
|
||||
ignore_errors: yes
|
||||
'''}, # noqa
|
||||
])
|
||||
def test_callback_plugin_no_log_filters(executor, playbook):
|
||||
executor.run()
|
||||
assert len(list(executor.events))
|
||||
assert 'SENSITIVE' not in json.dumps(list(executor.events))
|
||||
|
||||
|
||||
@pytest.mark.parametrize('playbook', [
|
||||
{'no_log_on_ok.yml': '''
|
||||
- name: args should not be logged when no_log is set at the task or module level
|
||||
connection: local
|
||||
hosts: all
|
||||
gather_facts: no
|
||||
tasks:
|
||||
- shell: echo "PUBLIC"
|
||||
- shell: echo "PRIVATE"
|
||||
no_log: true
|
||||
- uri: url=https://example.org url_username="PUBLIC" url_password="PRIVATE"
|
||||
'''}, # noqa
|
||||
])
|
||||
def test_callback_plugin_task_args_leak(executor, playbook, skipif_pre_ansible28):
|
||||
executor.run()
|
||||
events = list(executor.events)
|
||||
assert events[0]['event'] == 'playbook_on_start'
|
||||
assert events[1]['event'] == 'playbook_on_play_start'
|
||||
|
||||
# task 1
|
||||
assert events[2]['event'] == 'playbook_on_task_start'
|
||||
assert events[3]['event'] == 'runner_on_start'
|
||||
assert events[4]['event'] == 'runner_on_ok'
|
||||
|
||||
# task 2 no_log=True
|
||||
assert events[5]['event'] == 'playbook_on_task_start'
|
||||
assert events[6]['event'] == 'runner_on_start'
|
||||
assert events[7]['event'] == 'runner_on_ok'
|
||||
assert 'PUBLIC' in json.dumps(events), events
|
||||
for event in events:
|
||||
assert 'PRIVATE' not in json.dumps(event), event
|
||||
# make sure playbook was successful, so all tasks were hit
|
||||
assert not events[-1]['event_data']['failures'], 'Unexpected playbook execution failure'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('playbook', [
|
||||
{'loop_with_no_log.yml': '''
|
||||
- name: playbook variable should not be overwritten when using no log
|
||||
connection: local
|
||||
hosts: all
|
||||
gather_facts: no
|
||||
tasks:
|
||||
- command: "{{ item }}"
|
||||
register: command_register
|
||||
no_log: True
|
||||
with_items:
|
||||
- "echo helloworld!"
|
||||
- debug: msg="{{ command_register.results|map(attribute='stdout')|list }}"
|
||||
'''}, # noqa
|
||||
])
|
||||
def test_callback_plugin_censoring_does_not_overwrite(executor, playbook, skipif_pre_ansible28):
|
||||
executor.run()
|
||||
events = list(executor.events)
|
||||
assert events[0]['event'] == 'playbook_on_start'
|
||||
assert events[1]['event'] == 'playbook_on_play_start'
|
||||
|
||||
# task 1
|
||||
assert events[2]['event'] == 'playbook_on_task_start'
|
||||
# Ordering of task and item events may differ randomly
|
||||
assert set(['runner_on_start', 'runner_item_on_ok', 'runner_on_ok']) == set([data['event'] for data in events[3:6]])
|
||||
|
||||
# task 2 no_log=True
|
||||
assert events[6]['event'] == 'playbook_on_task_start'
|
||||
assert events[7]['event'] == 'runner_on_start'
|
||||
assert events[8]['event'] == 'runner_on_ok'
|
||||
assert 'helloworld!' in events[8]['event_data']['res']['msg']
|
||||
|
||||
|
||||
@pytest.mark.parametrize('playbook', [
|
||||
{'strip_env_vars.yml': '''
|
||||
- name: sensitive environment variables should be stripped from events
|
||||
connection: local
|
||||
hosts: all
|
||||
tasks:
|
||||
- shell: echo "Hello, World!"
|
||||
'''}, # noqa
|
||||
])
|
||||
def test_callback_plugin_strips_task_environ_variables(executor, playbook):
|
||||
executor.run()
|
||||
assert len(list(executor.events))
|
||||
for event in list(executor.events):
|
||||
assert os.environ['PATH'] not in json.dumps(event)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('playbook', [
|
||||
{'custom_set_stat.yml': '''
|
||||
- name: custom set_stat calls should persist to the local disk so awx can save them
|
||||
connection: local
|
||||
hosts: all
|
||||
tasks:
|
||||
- set_stats:
|
||||
data:
|
||||
foo: "bar"
|
||||
'''}, # noqa
|
||||
])
|
||||
def test_callback_plugin_saves_custom_stats(executor, playbook, skipif_pre_ansible28):
|
||||
executor.run()
|
||||
for event in executor.events:
|
||||
event_data = event.get('event_data', {})
|
||||
if 'artifact_data' in event_data:
|
||||
assert event_data['artifact_data'] == {'foo': 'bar'}
|
||||
break
|
||||
else:
|
||||
raise Exception('Did not find expected artifact data in event data')
|
||||
|
||||
|
||||
@pytest.mark.parametrize('playbook', [
|
||||
{'handle_playbook_on_notify.yml': '''
|
||||
- name: handle playbook_on_notify events properly
|
||||
connection: local
|
||||
hosts: all
|
||||
handlers:
|
||||
- name: my_handler
|
||||
debug: msg="My Handler"
|
||||
tasks:
|
||||
- debug: msg="My Task"
|
||||
changed_when: true
|
||||
notify:
|
||||
- my_handler
|
||||
'''}, # noqa
|
||||
])
|
||||
@pytest.mark.skipif(ANSIBLE_VERSION < '2.5', reason="v2_playbook_on_notify doesn't work before ansible 2.5")
|
||||
def test_callback_plugin_records_notify_events(executor, playbook, skipif_pre_ansible28):
|
||||
executor.run()
|
||||
assert len(list(executor.events))
|
||||
notify_events = [x for x in executor.events if x['event'] == 'playbook_on_notify']
|
||||
assert len(notify_events) == 1
|
||||
assert notify_events[0]['event_data']['handler'] == 'my_handler'
|
||||
assert notify_events[0]['event_data']['host'] == 'localhost'
|
||||
assert notify_events[0]['event_data']['task'] == 'debug'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('playbook', [
|
||||
{'no_log_module_with_var.yml': '''
|
||||
- name: ensure that module-level secrets are redacted
|
||||
connection: local
|
||||
hosts: all
|
||||
vars:
|
||||
- pw: SENSITIVE
|
||||
tasks:
|
||||
- uri:
|
||||
url: https://example.org
|
||||
url_username: john-jacob-jingleheimer-schmidt
|
||||
url_password: "{{ pw }}"
|
||||
'''}, # noqa
|
||||
])
|
||||
def test_module_level_no_log(executor, playbook, skipif_pre_ansible28):
|
||||
# It's possible for `no_log=True` to be defined at the _module_ level,
|
||||
# e.g., for the URI module password parameter
|
||||
# This test ensures that we properly redact those
|
||||
executor.run()
|
||||
assert len(list(executor.events))
|
||||
assert 'john-jacob-jingleheimer-schmidt' in json.dumps(list(executor.events))
|
||||
assert 'SENSITIVE' not in json.dumps(list(executor.events))
|
||||
|
||||
|
||||
def test_output_when_given_invalid_playbook(tmpdir):
|
||||
# As shown in the following issue:
|
||||
#
|
||||
# https://github.com/ansible/ansible-runner/issues/29
|
||||
#
|
||||
# There was a lack of output by runner when a playbook that doesn't exist
|
||||
# is provided. This was fixed in this PR:
|
||||
#
|
||||
# https://github.com/ansible/ansible-runner/pull/34
|
||||
#
|
||||
# But no test validated it. This does that.
|
||||
private_data_dir = str(tmpdir)
|
||||
executor = init_runner(
|
||||
private_data_dir=private_data_dir,
|
||||
inventory="localhost ansible_connection=local",
|
||||
envvars={"ANSIBLE_DEPRECATION_WARNINGS": "False"},
|
||||
playbook=os.path.join(private_data_dir, 'fake_playbook.yml')
|
||||
)
|
||||
|
||||
executor.run()
|
||||
stdout = executor.stdout.read()
|
||||
assert "ERROR! the playbook:" in stdout
|
||||
assert "could not be found" in stdout
|
||||
|
||||
|
||||
def test_output_when_given_non_playbook_script(tmpdir):
|
||||
# As shown in the following pull request:
|
||||
#
|
||||
# https://github.com/ansible/ansible-runner/pull/256
|
||||
#
|
||||
# This ports some functionality that previously lived in awx and allows raw
|
||||
# lines of stdout to be treated as event lines.
|
||||
#
|
||||
# As mentioned in the pull request as well, there were no specs added, and
|
||||
# this is a retro-active test based on the sample repo provided in the PR:
|
||||
#
|
||||
# https://github.com/AlanCoding/ansible-runner-examples/tree/master/non_playbook/sleep_with_writes
|
||||
private_data_dir = str(tmpdir)
|
||||
with open(os.path.join(private_data_dir, "args"), 'w') as args_file:
|
||||
args_file.write("bash sleep_and_write.sh\n")
|
||||
with open(os.path.join(private_data_dir, "sleep_and_write.sh"), 'w') as script_file:
|
||||
script_file.write("echo 'hi world'\nsleep 0.5\necho 'goodbye world'\n")
|
||||
|
||||
# Update the settings to make this test a bit faster :)
|
||||
os.mkdir(os.path.join(private_data_dir, "env"))
|
||||
with open(os.path.join(private_data_dir, "env", "settings"), 'w') as settings_file:
|
||||
settings_file.write("pexpect_timeout: 0.2")
|
||||
|
||||
executor = init_runner(
|
||||
private_data_dir=private_data_dir,
|
||||
inventory="localhost ansible_connection=local",
|
||||
envvars={"ANSIBLE_DEPRECATION_WARNINGS": "False"}
|
||||
)
|
||||
|
||||
executor.run()
|
||||
stdout = executor.stdout.readlines()
|
||||
assert stdout[0].strip() == "hi world"
|
||||
assert stdout[1].strip() == "goodbye world"
|
||||
|
||||
events = list(executor.events)
|
||||
|
||||
assert len(events) == 2
|
||||
assert events[0]['event'] == 'verbose'
|
||||
assert events[0]['stdout'] == 'hi world'
|
||||
assert events[1]['event'] == 'verbose'
|
||||
assert events[1]['stdout'] == 'goodbye world'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('playbook', [
|
||||
{'listvars.yml': '''
|
||||
- name: List Variables
|
||||
connection: local
|
||||
hosts: localhost
|
||||
gather_facts: false
|
||||
tasks:
|
||||
- name: Print a lot of lines
|
||||
debug:
|
||||
msg: "{{ ('F' * 150) | list }}"
|
||||
'''}, # noqa
|
||||
])
|
||||
def test_large_stdout_parsing_when_using_json_output(executor, playbook, skipif_pre_ansible28):
|
||||
# When the json flag is used, it is possible to output more data than
|
||||
# pexpect's maxread default of 2000 characters. As a result, if not
|
||||
# handled properly, the stdout can end up being corrupted with partial
|
||||
# non-event matches with raw "non-json" lines being intermixed with json
|
||||
# ones.
|
||||
#
|
||||
# This tests to confirm we don't polute the stdout output with non-json
|
||||
# lines when a single event has a lot of output.
|
||||
if six.PY2:
|
||||
pytest.skip('Ansible in python2 uses different syntax.')
|
||||
executor.config.env['ANSIBLE_NOCOLOR'] = str(True)
|
||||
executor.run()
|
||||
text = executor.stdout.read()
|
||||
assert text.count('"F"') == 150
|
||||
@@ -0,0 +1,192 @@
|
||||
import pytest
|
||||
import tempfile
|
||||
from distutils.spawn import find_executable
|
||||
import json
|
||||
import os
|
||||
|
||||
from ansible_runner import defaults, run, run_async
|
||||
|
||||
|
||||
@pytest.mark.parametrize('containerized', [True, False])
|
||||
def test_basic_events(containerized, container_runtime_available, is_pre_ansible28, is_run_async=False, g_facts=False):
|
||||
if containerized and not container_runtime_available:
|
||||
pytest.skip('container runtime(s) not available')
|
||||
tdir = tempfile.mkdtemp()
|
||||
|
||||
if is_pre_ansible28:
|
||||
inventory = 'localhost ansible_connection=local ansible_python_interpreter="/usr/bin/env python"'
|
||||
else:
|
||||
inventory = 'localhost ansible_connection=local'
|
||||
|
||||
playbook = [{'hosts': 'all', 'gather_facts': g_facts, 'tasks': [{'debug': {'msg': "test"}}]}]
|
||||
run_args = {'private_data_dir': tdir,
|
||||
'inventory': inventory,
|
||||
'envvars': {"ANSIBLE_DEPRECATION_WARNINGS": "False", 'ANSIBLE_PYTHON_INTERPRETER': 'auto_silent'},
|
||||
'playbook': playbook}
|
||||
if containerized:
|
||||
run_args.update({'process_isolation': True,
|
||||
'process_isolation_executable': 'podman',
|
||||
'container_image': defaults.default_container_image,
|
||||
'container_volume_mounts': [f'{tdir}:{tdir}']})
|
||||
|
||||
if not is_run_async:
|
||||
r = run(**run_args)
|
||||
else:
|
||||
thread, r = run_async(**run_args)
|
||||
thread.join() # ensure async run finishes
|
||||
|
||||
event_types = [x['event'] for x in r.events if x['event'] != 'verbose']
|
||||
okay_events = [x for x in filter(lambda x: 'event' in x and x['event'] == 'runner_on_ok',
|
||||
r.events)]
|
||||
|
||||
assert event_types[0] == 'playbook_on_start'
|
||||
assert "playbook_on_play_start" in event_types
|
||||
assert "runner_on_ok" in event_types
|
||||
assert "playbook_on_stats" in event_types
|
||||
assert r.rc == 0
|
||||
if not is_run_async:
|
||||
assert len(okay_events) == 1
|
||||
else:
|
||||
assert len(okay_events) == 2
|
||||
|
||||
okay_event = okay_events[0]
|
||||
assert "uuid" in okay_event and len(okay_event['uuid']) == 36
|
||||
assert "parent_uuid" in okay_event and len(okay_event['parent_uuid']) == 36
|
||||
assert "stdout" in okay_event and len(okay_event['stdout']) > 0
|
||||
assert "start_line" in okay_event and int(okay_event['start_line']) > 0
|
||||
assert "end_line" in okay_event and int(okay_event['end_line']) > 0
|
||||
assert "event_data" in okay_event and len(okay_event['event_data']) > 0
|
||||
|
||||
|
||||
@pytest.mark.parametrize('containerized', [True, False])
|
||||
def test_async_events(containerized, container_runtime_available, is_pre_ansible28):
|
||||
test_basic_events(containerized, container_runtime_available, is_pre_ansible28, is_run_async=True,g_facts=True)
|
||||
|
||||
|
||||
def test_basic_serializeable(is_pre_ansible28):
|
||||
tdir = tempfile.mkdtemp()
|
||||
if is_pre_ansible28:
|
||||
inv = 'localhost ansible_connection=local ansible_python_interpreter="/usr/bin/env python"'
|
||||
else:
|
||||
inv = 'localhost ansible_connection=local'
|
||||
r = run(private_data_dir=tdir,
|
||||
inventory=inv,
|
||||
playbook=[{'hosts': 'all', 'gather_facts': False, 'tasks': [{'debug': {'msg': "test"}}]}])
|
||||
events = [x for x in r.events]
|
||||
json.dumps(events)
|
||||
|
||||
|
||||
def test_event_omission(is_pre_ansible28):
|
||||
tdir = tempfile.mkdtemp()
|
||||
if is_pre_ansible28:
|
||||
inv = 'localhost ansible_connection=local ansible_python_interpreter="/usr/bin/env python"'
|
||||
else:
|
||||
inv = 'localhost ansible_connection=local'
|
||||
r = run(private_data_dir=tdir,
|
||||
inventory=inv,
|
||||
omit_event_data=True,
|
||||
playbook=[{'hosts': 'all', 'gather_facts': False, 'tasks': [{'debug': {'msg': "test"}}]}])
|
||||
assert not any([x['event_data'] for x in r.events])
|
||||
|
||||
|
||||
def test_event_omission_except_failed(is_pre_ansible28):
|
||||
tdir = tempfile.mkdtemp()
|
||||
if is_pre_ansible28:
|
||||
inv = 'localhost ansible_connection=local ansible_python_interpreter="/usr/bin/env python"'
|
||||
else:
|
||||
inv = 'localhost ansible_connection=local'
|
||||
r = run(private_data_dir=tdir,
|
||||
inventory=inv,
|
||||
only_failed_event_data=True,
|
||||
playbook=[{'hosts': 'all', 'gather_facts': False, 'tasks': [{'fail': {'msg': "test"}}]}])
|
||||
all_event_datas = [x['event_data'] for x in r.events if x['event_data']]
|
||||
assert len(all_event_datas) == 1
|
||||
|
||||
|
||||
def test_runner_on_start(rc, skipif_pre_ansible28):
|
||||
tdir = tempfile.mkdtemp()
|
||||
r = run(private_data_dir=tdir,
|
||||
inventory="localhost ansible_connection=local",
|
||||
playbook=[{'hosts': 'all', 'gather_facts': False, 'tasks': [{'debug': {'msg': "test"}}]}])
|
||||
start_events = [x for x in filter(lambda x: 'event' in x and x['event'] == 'runner_on_start',
|
||||
r.events)]
|
||||
assert len(start_events) == 1
|
||||
|
||||
|
||||
def test_playbook_on_stats_summary_fields(test_data_dir, is_pre_ansible28):
|
||||
if is_pre_ansible28:
|
||||
pytest.skip('Test is for post 2.8 status types.')
|
||||
private_data_dir = os.path.join(test_data_dir, 'host_status')
|
||||
|
||||
res = run(
|
||||
private_data_dir=private_data_dir,
|
||||
playbook='gen_host_status.yml'
|
||||
)
|
||||
assert res.rc != 0, res.stdout.read()
|
||||
|
||||
EXPECTED_SUMMARY_FIELDS = ('changed', 'dark', 'failures', 'ignored', 'ok', 'rescued', 'skipped')
|
||||
|
||||
runner_stats = res.stats
|
||||
for stat in EXPECTED_SUMMARY_FIELDS:
|
||||
assert stat in runner_stats
|
||||
assert runner_stats[stat] # expected at least 1 host in each stat type
|
||||
|
||||
|
||||
def test_include_role_events(clear_integration_artifacts):
|
||||
r = run(
|
||||
private_data_dir=os.path.abspath('test/integration'),
|
||||
playbook='use_role.yml'
|
||||
)
|
||||
role_events = [event for event in r.events if event.get('event_data', {}).get('role', '') == "benthomasson.hello_role"]
|
||||
assert 'runner_on_ok' in [event['event'] for event in role_events]
|
||||
for event in role_events:
|
||||
event_data = event['event_data']
|
||||
assert not event_data.get('warning', False) # role use should not contain warnings
|
||||
if event['event'] == 'runner_on_ok':
|
||||
assert event_data['res']['msg'] == 'Hello world!'
|
||||
|
||||
|
||||
@pytest.mark.skipif(find_executable('cgexec') is None,
|
||||
reason="cgexec not available")
|
||||
def test_profile_data(skipif_pre_ansible28):
|
||||
tdir = tempfile.mkdtemp()
|
||||
try:
|
||||
r = run(private_data_dir=tdir,
|
||||
inventory="localhost ansible_connection=local",
|
||||
resource_profiling=True,
|
||||
resource_profiling_base_cgroup='ansible-runner',
|
||||
playbook=[{'hosts': 'all', 'gather_facts': False, 'tasks': [{'debug': {'msg': "test"}}]}])
|
||||
assert r.config.env['ANSIBLE_CALLBACK_WHITELIST'] == 'cgroup_perf_recap'
|
||||
assert r.config.env['CGROUP_CONTROL_GROUP'].startswith('ansible-runner/')
|
||||
expected_datadir = os.path.join(tdir, 'profiling_data')
|
||||
assert r.config.env['CGROUP_OUTPUT_DIR'] == expected_datadir
|
||||
assert r.config.env['CGROUP_OUTPUT_FORMAT'] == 'json'
|
||||
assert r.config.env['CGROUP_CPU_POLL_INTERVAL'] == '0.25'
|
||||
assert r.config.env['CGROUP_MEMORY_POLL_INTERVAL'] == '0.25'
|
||||
assert r.config.env['CGROUP_PID_POLL_INTERVAL'] == '0.25'
|
||||
assert r.config.env['CGROUP_FILE_PER_TASK'] == 'True'
|
||||
assert r.config.env['CGROUP_WRITE_FILES'] == 'True'
|
||||
assert r.config.env['CGROUP_DISPLAY_RECAP'] == 'False'
|
||||
|
||||
data_files = [f for f in os.listdir(expected_datadir)
|
||||
if os.path.isfile(os.path.join(expected_datadir, f))]
|
||||
# Ensure each type of metric is represented in the results
|
||||
for metric in ('cpu', 'memory', 'pids'):
|
||||
assert len([f for f in data_files if '{}.json'.format(metric) in f]) == 1
|
||||
|
||||
# Ensure each file consists of a list of json dicts
|
||||
for file in data_files:
|
||||
with open(os.path.join(expected_datadir, file)) as f:
|
||||
for line in f:
|
||||
line = line[1:-1] # strip RS and LF (see https://tools.ietf.org/html/rfc7464#section-2.2)
|
||||
try:
|
||||
json.loads(line)
|
||||
except json.JSONDecodeError as e:
|
||||
pytest.fail("Failed to parse {}: '{}'"
|
||||
.format(os.path.join(expected_datadir, file), e))
|
||||
|
||||
except RuntimeError:
|
||||
pytest.skip(
|
||||
'this test requires a cgroup to run e.g., '
|
||||
'sudo cgcreate -a `whoami` -t `whoami` -g cpuacct,memory,pids:ansible-runner'
|
||||
) # noqa
|
||||
@@ -0,0 +1,136 @@
|
||||
import os
|
||||
import pytest
|
||||
import shutil
|
||||
|
||||
from ansible_runner.interface import run, run_async
|
||||
|
||||
|
||||
def test_run():
|
||||
r = run(module='debug', host_pattern='localhost')
|
||||
assert r.status == 'successful'
|
||||
|
||||
|
||||
def test_run_async():
|
||||
thread, r = run_async(module='debug', host_pattern='localhost')
|
||||
thread.join()
|
||||
assert r.status == 'successful'
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def printenv_example(test_data_dir):
|
||||
private_data_dir = os.path.join(test_data_dir, 'printenv')
|
||||
# TODO: remove if main code can handle this for us
|
||||
# https://github.com/ansible/ansible-runner/issues/493
|
||||
# for now, necessary to prevent errors on re-run
|
||||
env_dir = os.path.join(private_data_dir, 'env')
|
||||
if os.path.exists(env_dir):
|
||||
shutil.rmtree(env_dir)
|
||||
return private_data_dir
|
||||
|
||||
|
||||
def get_env_data(res):
|
||||
for event in res.events:
|
||||
found = bool(
|
||||
event['event'] == 'runner_on_ok' and event.get(
|
||||
'event_data', {}
|
||||
).get('task_action', None) == 'look_at_environment'
|
||||
)
|
||||
if found:
|
||||
return event['event_data']['res']
|
||||
else:
|
||||
print('output:')
|
||||
print(res.stdout.read())
|
||||
raise RuntimeError('Count not find look_at_environment task from playbook')
|
||||
|
||||
|
||||
def test_env_accuracy(request, printenv_example):
|
||||
os.environ['SET_BEFORE_TEST'] = 'MADE_UP_VALUE'
|
||||
|
||||
def remove_test_env_var():
|
||||
if 'SET_BEFORE_TEST' in os.environ:
|
||||
del os.environ['SET_BEFORE_TEST']
|
||||
|
||||
request.addfinalizer(remove_test_env_var)
|
||||
|
||||
res = run(
|
||||
private_data_dir=printenv_example,
|
||||
playbook='get_environment.yml',
|
||||
inventory=None,
|
||||
envvars={'FROM_TEST': 'FOOBAR'},
|
||||
)
|
||||
assert res.rc == 0, res.stdout.read()
|
||||
|
||||
actual_env = get_env_data(res)['environment']
|
||||
|
||||
assert actual_env == res.config.env
|
||||
|
||||
|
||||
@pytest.mark.serial
|
||||
def test_env_accuracy_inside_container(request, printenv_example, container_runtime_installed):
|
||||
os.environ['SET_BEFORE_TEST'] = 'MADE_UP_VALUE'
|
||||
|
||||
def remove_test_env_var():
|
||||
if 'SET_BEFORE_TEST' in os.environ:
|
||||
del os.environ['SET_BEFORE_TEST']
|
||||
|
||||
request.addfinalizer(remove_test_env_var)
|
||||
|
||||
res = run(
|
||||
private_data_dir=printenv_example,
|
||||
project_dir='/tmp',
|
||||
playbook='get_environment.yml',
|
||||
inventory=None,
|
||||
envvars={'FROM_TEST': 'FOOBAR'},
|
||||
settings={
|
||||
'process_isolation_executable': container_runtime_installed,
|
||||
'process_isolation': True
|
||||
}
|
||||
)
|
||||
assert res.rc == 0, res.stdout.read()
|
||||
|
||||
env_data = get_env_data(res)
|
||||
actual_env = env_data['environment']
|
||||
|
||||
expected_env = res.config.env.copy()
|
||||
|
||||
# NOTE: the reported environment for containerized jobs will not account for
|
||||
# all environment variables, particularly those set by the entrypoint script
|
||||
for key, value in expected_env.items():
|
||||
assert key in actual_env
|
||||
assert actual_env[key] == value, 'Reported value wrong for {0} env var'.format(key)
|
||||
|
||||
assert env_data['cwd'] == res.config.cwd
|
||||
|
||||
|
||||
def test_multiple_inventories(test_data_dir):
|
||||
private_data_dir = os.path.join(test_data_dir, 'debug')
|
||||
|
||||
res = run(
|
||||
private_data_dir=private_data_dir,
|
||||
playbook='debug.yml',
|
||||
)
|
||||
stdout = res.stdout.read()
|
||||
assert res.rc == 0, stdout
|
||||
|
||||
# providing no inventory should cause <private_data_dir>/inventory
|
||||
# to be used, reading both inventories in the directory
|
||||
assert 'host_1' in stdout
|
||||
assert 'host_2' in stdout
|
||||
|
||||
|
||||
def test_inventory_absolute_path(test_data_dir):
|
||||
private_data_dir = os.path.join(test_data_dir, 'debug')
|
||||
|
||||
res = run(
|
||||
private_data_dir=private_data_dir,
|
||||
playbook='debug.yml',
|
||||
inventory=[
|
||||
os.path.join(private_data_dir, 'inventory', 'inv_1'),
|
||||
],
|
||||
)
|
||||
stdout = res.stdout.read()
|
||||
assert res.rc == 0, stdout
|
||||
|
||||
# hosts can be down-selected to one inventory out of those available
|
||||
assert 'host_1' in stdout
|
||||
assert 'host_2' not in stdout
|
||||
@@ -0,0 +1,327 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import print_function
|
||||
from ansible_runner.__main__ import main
|
||||
|
||||
import os
|
||||
import codecs
|
||||
import multiprocessing
|
||||
import shutil
|
||||
import yaml
|
||||
import tempfile
|
||||
import time
|
||||
from contextlib import contextmanager
|
||||
import pytest
|
||||
|
||||
|
||||
from ansible_runner.exceptions import AnsibleRunnerException
|
||||
|
||||
HERE = os.path.abspath(os.path.dirname(__file__))
|
||||
|
||||
|
||||
def ensure_directory(directory):
|
||||
if not os.path.exists(directory):
|
||||
os.makedirs(directory)
|
||||
|
||||
|
||||
def ensure_removed(path):
|
||||
if os.path.exists(path):
|
||||
if os.path.isfile(path):
|
||||
os.unlink(path)
|
||||
elif os.path.isdir(path):
|
||||
shutil.rmtree(path)
|
||||
|
||||
|
||||
@contextmanager
|
||||
def temp_directory(files=None):
|
||||
temp_dir = tempfile.mkdtemp()
|
||||
print(temp_dir)
|
||||
try:
|
||||
yield temp_dir
|
||||
shutil.rmtree(temp_dir)
|
||||
except BaseException:
|
||||
if files is not None:
|
||||
for file in files:
|
||||
if os.path.exists(file):
|
||||
with open(file) as f:
|
||||
print(f.read())
|
||||
raise
|
||||
|
||||
|
||||
def test_temp_directory():
|
||||
|
||||
context = dict()
|
||||
|
||||
|
||||
def will_fail():
|
||||
with temp_directory() as temp_dir:
|
||||
context['saved_temp_dir'] = temp_dir
|
||||
assert False
|
||||
|
||||
def will_pass():
|
||||
with temp_directory() as temp_dir:
|
||||
context['saved_temp_dir'] = temp_dir
|
||||
assert True
|
||||
|
||||
with pytest.raises(AssertionError):
|
||||
will_fail()
|
||||
assert os.path.exists(context['saved_temp_dir'])
|
||||
shutil.rmtree(context['saved_temp_dir'])
|
||||
|
||||
will_pass()
|
||||
assert not os.path.exists(context['saved_temp_dir'])
|
||||
|
||||
|
||||
def test_help():
|
||||
with pytest.raises(SystemExit) as exc:
|
||||
main([])
|
||||
assert exc.value.code == 2, 'Should raise SystemExit with return code 2'
|
||||
|
||||
|
||||
def test_module_run():
|
||||
try:
|
||||
rc = main(['run', '-m', 'ping',
|
||||
'--hosts', 'localhost',
|
||||
'ping'])
|
||||
assert os.path.exists('./ping')
|
||||
assert os.path.exists('./ping/artifacts')
|
||||
assert rc == 0
|
||||
finally:
|
||||
if os.path.exists('./ping'):
|
||||
shutil.rmtree('./ping')
|
||||
|
||||
|
||||
def test_module_run_debug():
|
||||
try:
|
||||
rc = main(['run', '-m', 'ping',
|
||||
'--hosts', 'localhost',
|
||||
'--debug',
|
||||
'ping'])
|
||||
assert os.path.exists('./ping')
|
||||
assert os.path.exists('./ping/artifacts')
|
||||
assert rc == 0
|
||||
finally:
|
||||
if os.path.exists('./ping'):
|
||||
shutil.rmtree('./ping')
|
||||
|
||||
|
||||
def test_module_run_clean():
|
||||
with temp_directory() as temp_dir:
|
||||
rc = main(['run', '-m', 'ping',
|
||||
'--hosts', 'localhost',
|
||||
temp_dir])
|
||||
assert rc == 0
|
||||
|
||||
|
||||
def test_role_run(skipif_pre_ansible28, clear_integration_artifacts):
|
||||
rc = main(['run', '-r', 'benthomasson.hello_role',
|
||||
'--hosts', 'localhost',
|
||||
'--roles-path', 'test/integration/roles',
|
||||
"test/integration"])
|
||||
assert rc == 0
|
||||
|
||||
|
||||
def test_role_run_abs():
|
||||
with temp_directory() as temp_dir:
|
||||
rc = main(['run', '-r', 'benthomasson.hello_role',
|
||||
'--hosts', 'localhost',
|
||||
'--roles-path', os.path.join(HERE, 'project/roles'),
|
||||
temp_dir])
|
||||
assert rc == 0
|
||||
|
||||
|
||||
def test_role_logfile(skipif_pre_ansible28, clear_integration_artifacts):
|
||||
rc = main(['run', '-r', 'benthomasson.hello_role',
|
||||
'--hosts', 'localhost',
|
||||
'--roles-path', 'test/integration/project/roles',
|
||||
'--logfile', 'new_logfile',
|
||||
'test/integration'])
|
||||
assert os.path.exists('new_logfile')
|
||||
assert rc == 0
|
||||
|
||||
|
||||
def test_role_logfile_abs():
|
||||
try:
|
||||
with temp_directory() as temp_dir:
|
||||
rc = main(['run', '-r', 'benthomasson.hello_role',
|
||||
'--hosts', 'localhost',
|
||||
'--roles-path', os.path.join(HERE, 'project/roles'),
|
||||
'--logfile', 'new_logfile',
|
||||
temp_dir])
|
||||
assert os.path.exists('new_logfile')
|
||||
assert rc == 0
|
||||
finally:
|
||||
ensure_removed("new_logfile")
|
||||
|
||||
|
||||
def test_role_bad_project_dir():
|
||||
|
||||
with open("bad_project_dir", 'w') as f:
|
||||
f.write('not a directory')
|
||||
|
||||
try:
|
||||
with pytest.raises(OSError):
|
||||
main(['run', '-r', 'benthomasson.hello_role',
|
||||
'--hosts', 'localhost',
|
||||
'--roles-path', os.path.join(HERE, 'project/roles'),
|
||||
'--logfile', 'new_logfile',
|
||||
'bad_project_dir'])
|
||||
finally:
|
||||
os.unlink('bad_project_dir')
|
||||
ensure_removed("new_logfile")
|
||||
|
||||
|
||||
def test_role_run_clean(skipif_pre_ansible28, clear_integration_artifacts):
|
||||
|
||||
rc = main(['run', '-r', 'benthomasson.hello_role',
|
||||
'--hosts', 'localhost',
|
||||
'--roles-path', 'test/integration/roles',
|
||||
"test/integration"])
|
||||
assert rc == 0
|
||||
|
||||
|
||||
def test_role_run_cmd_line_abs():
|
||||
with temp_directory() as temp_dir:
|
||||
rc = main(['run', '-r', 'benthomasson.hello_role',
|
||||
'--hosts', 'localhost',
|
||||
'--roles-path', os.path.join(HERE, 'project/roles'),
|
||||
temp_dir])
|
||||
assert rc == 0
|
||||
|
||||
|
||||
def test_role_run_artifacts_dir(skipif_pre_ansible28, clear_integration_artifacts):
|
||||
rc = main(['run', '-r', 'benthomasson.hello_role',
|
||||
'--hosts', 'localhost',
|
||||
'--roles-path', 'test/integration/roles',
|
||||
'--artifact-dir', 'otherartifacts',
|
||||
"test/integration"])
|
||||
assert rc == 0
|
||||
|
||||
|
||||
def test_role_run_artifacts_dir_abs(skipif_pre_ansible28):
|
||||
try:
|
||||
with temp_directory() as temp_dir:
|
||||
rc = main(['run', '-r', 'benthomasson.hello_role',
|
||||
'--hosts', 'localhost',
|
||||
'--roles-path', os.path.join(HERE, 'project/roles'),
|
||||
'--artifact-dir', 'otherartifacts',
|
||||
temp_dir])
|
||||
assert os.path.exists(os.path.join('.', 'otherartifacts'))
|
||||
assert rc == 0
|
||||
finally:
|
||||
shutil.rmtree(os.path.join('.', 'otherartifacts'))
|
||||
|
||||
|
||||
@pytest.mark.parametrize('envvars', [
|
||||
{'msg': 'hi'},
|
||||
{
|
||||
'msg': u'utf-8-䉪ቒ칸ⱷ?噂폄蔆㪗輥',
|
||||
u'蔆㪗輥': u'䉪ቒ칸'
|
||||
}],
|
||||
ids=['regular-text', 'utf-8-text']
|
||||
)
|
||||
def test_role_run_env_vars(envvars):
|
||||
|
||||
with temp_directory() as temp_dir:
|
||||
ensure_directory(os.path.join(temp_dir, 'env'))
|
||||
with codecs.open(os.path.join(temp_dir, 'env/envvars'), 'w', encoding='utf-8') as f:
|
||||
f.write(yaml.dump(envvars))
|
||||
|
||||
rc = main(['run', '-r', 'benthomasson.hello_role',
|
||||
'--hosts', 'localhost',
|
||||
'--roles-path', os.path.join(HERE, 'project/roles'),
|
||||
temp_dir])
|
||||
assert rc == 0
|
||||
|
||||
|
||||
def test_role_run_args():
|
||||
|
||||
with temp_directory() as temp_dir:
|
||||
rc = main(['run', '-r', 'benthomasson.hello_role',
|
||||
'--hosts', 'localhost',
|
||||
'--roles-path', os.path.join(HERE, 'project/roles'),
|
||||
'--role-vars', 'msg=hi',
|
||||
temp_dir])
|
||||
assert rc == 0
|
||||
|
||||
|
||||
def test_role_run_inventory(is_pre_ansible28):
|
||||
|
||||
inv = 'inventory/localhost_preansible28' if is_pre_ansible28 else 'inventory/localhost'
|
||||
with temp_directory() as temp_dir:
|
||||
ensure_directory(os.path.join(temp_dir, 'inventory'))
|
||||
shutil.copy(os.path.join(HERE, inv), os.path.join(temp_dir, 'inventory/localhost'))
|
||||
|
||||
rc = main(['run', '-r', 'benthomasson.hello_role',
|
||||
'--hosts', 'localhost',
|
||||
'--roles-path', os.path.join(HERE, 'project/roles'),
|
||||
'--inventory', os.path.join(temp_dir, 'inventory/localhost'),
|
||||
temp_dir])
|
||||
assert rc == 0
|
||||
|
||||
|
||||
def test_role_run_inventory_missing(is_pre_ansible28):
|
||||
|
||||
inv = 'inventory/localhost_preansible28' if is_pre_ansible28 else 'inventory/localhost'
|
||||
with temp_directory() as temp_dir:
|
||||
ensure_directory(os.path.join(temp_dir, 'inventory'))
|
||||
shutil.copy(os.path.join(HERE, inv), os.path.join(temp_dir, 'inventory/localhost'))
|
||||
|
||||
with pytest.raises(AnsibleRunnerException):
|
||||
main(['run', '-r', 'benthomasson.hello_role',
|
||||
'--hosts', 'localhost',
|
||||
'--roles-path', os.path.join(HERE, 'project/roles'),
|
||||
'--inventory', 'does_not_exist',
|
||||
temp_dir])
|
||||
|
||||
|
||||
def test_role_start():
|
||||
|
||||
|
||||
with temp_directory() as temp_dir:
|
||||
p = multiprocessing.Process(target=main,
|
||||
args=[['start', '-r', 'benthomasson.hello_role',
|
||||
'--hosts', 'localhost',
|
||||
'--roles-path', os.path.join(HERE, 'project/roles'),
|
||||
temp_dir]])
|
||||
p.start()
|
||||
p.join()
|
||||
|
||||
|
||||
def test_playbook_start(skipif_pre_ansible28):
|
||||
|
||||
inv = 'inventory/localhost'
|
||||
with temp_directory() as temp_dir:
|
||||
project_dir = os.path.join(temp_dir, 'project')
|
||||
ensure_directory(project_dir)
|
||||
shutil.copy(os.path.join(HERE, 'project/hello.yml'), project_dir)
|
||||
ensure_directory(os.path.join(temp_dir, 'inventory'))
|
||||
shutil.copy(os.path.join(HERE, inv), os.path.join(temp_dir,'inventory/localhost'))
|
||||
|
||||
# privateip: removed --hosts command line option from test beause it is
|
||||
# not a supported combination of cli options
|
||||
p = multiprocessing.Process(target=main,
|
||||
args=[['start', '-p', 'hello.yml',
|
||||
'--inventory', os.path.join(HERE, 'inventory/localhost'),
|
||||
#'--hosts', 'localhost',
|
||||
temp_dir]])
|
||||
p.start()
|
||||
|
||||
|
||||
time.sleep(5)
|
||||
|
||||
assert os.path.exists(os.path.join(temp_dir, 'pid'))
|
||||
|
||||
rc = main(['is-alive', temp_dir])
|
||||
assert rc == 0
|
||||
rc = main(['stop', temp_dir])
|
||||
assert rc == 0
|
||||
|
||||
time.sleep(1)
|
||||
|
||||
rc = main(['is-alive', temp_dir])
|
||||
assert rc == 1
|
||||
|
||||
ensure_removed(os.path.join(temp_dir, 'pid'))
|
||||
|
||||
rc = main(['stop', temp_dir])
|
||||
assert rc == 1
|
||||
@@ -0,0 +1,279 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import pytest
|
||||
import six
|
||||
import sys
|
||||
try:
|
||||
from unittest.mock import MagicMock
|
||||
except ImportError:
|
||||
from unittest.mock import MagicMock
|
||||
from ansible_runner import Runner
|
||||
|
||||
from ansible_runner.exceptions import AnsibleRunnerException
|
||||
|
||||
|
||||
@pytest.mark.serial
|
||||
def test_password_prompt(rc):
|
||||
rc.command = [sys.executable, '-c' 'import time; print(input("Password: "))']
|
||||
rc.expect_passwords[re.compile(r'Password:\s*?$', re.M)] = '1234'
|
||||
status, exitcode = Runner(config=rc).run()
|
||||
assert status == 'successful'
|
||||
assert exitcode == 0
|
||||
with open(os.path.join(rc.artifact_dir, 'stdout')) as f:
|
||||
assert '1234' in f.read()
|
||||
|
||||
|
||||
def test_run_command(rc):
|
||||
rc.command = ['sleep', '1']
|
||||
status, exitcode = Runner(config=rc).run()
|
||||
assert status == 'successful'
|
||||
assert exitcode == 0
|
||||
with open(os.path.join(rc.artifact_dir, 'command')) as f:
|
||||
data = json.load(f)
|
||||
assert data.get('command') == ['sleep','1']
|
||||
assert 'cwd' in data
|
||||
assert isinstance(data.get('env'), dict)
|
||||
|
||||
|
||||
def test_run_command_with_unicode(rc):
|
||||
expected = '"utf-8-䉪ቒ칸ⱷ?噂폄蔆㪗輥"'
|
||||
if six.PY2:
|
||||
expected = expected.decode('utf-8')
|
||||
rc.command = ['echo', '"utf-8-䉪ቒ칸ⱷ?噂폄蔆㪗輥"']
|
||||
rc.envvars = {"䉪ቒ칸": "蔆㪗輥"}
|
||||
rc.prepare_env()
|
||||
status, exitcode = Runner(config=rc).run()
|
||||
assert status == 'successful'
|
||||
assert exitcode == 0
|
||||
with open(os.path.join(rc.artifact_dir, 'command')) as f:
|
||||
data = json.load(f)
|
||||
assert data.get('command') == ['echo', expected]
|
||||
assert 'cwd' in data
|
||||
assert isinstance(data.get('env'), dict)
|
||||
assert u"䉪ቒ칸" in data.get('env')
|
||||
|
||||
|
||||
def test_run_command_finished_callback(rc):
|
||||
finished_callback = MagicMock()
|
||||
rc.command = ['sleep','1']
|
||||
runner = Runner(config=rc, finished_callback=finished_callback)
|
||||
status, exitcode = runner.run()
|
||||
assert status == 'successful'
|
||||
assert exitcode == 0
|
||||
finished_callback.assert_called_with(runner)
|
||||
|
||||
|
||||
def test_run_command_explosive_finished_callback(rc):
|
||||
def boom(*args):
|
||||
raise Exception('boom')
|
||||
rc.command = ['sleep','1']
|
||||
runner = Runner(config=rc, finished_callback=boom)
|
||||
with pytest.raises(Exception):
|
||||
runner.run()
|
||||
|
||||
|
||||
def test_run_command_explosive_cancel_callback(rc):
|
||||
def boom(*args):
|
||||
raise Exception('boom')
|
||||
rc.command = ['sleep','1']
|
||||
runner = Runner(config=rc, cancel_callback=boom)
|
||||
with pytest.raises(Exception):
|
||||
runner.run()
|
||||
|
||||
|
||||
def test_run_command_cancel_callback(rc):
|
||||
def cancel(*args):
|
||||
return True
|
||||
rc.command = ['sleep','1']
|
||||
runner = Runner(config=rc, cancel_callback=cancel)
|
||||
status, exitcode = runner.run()
|
||||
assert status == 'canceled'
|
||||
assert exitcode == 254
|
||||
|
||||
|
||||
def test_run_command_job_timeout(rc):
|
||||
rc.command = ['sleep', '1']
|
||||
rc.job_timeout = 0.0000001
|
||||
runner = Runner(config=rc)
|
||||
status, exitcode = runner.run()
|
||||
assert status == 'timeout'
|
||||
assert exitcode == 254
|
||||
|
||||
|
||||
def test_run_command_idle_timeout(rc):
|
||||
rc.command = ['sleep', '1']
|
||||
rc.idle_timeout = 0.0000001
|
||||
runner = Runner(config=rc)
|
||||
status, exitcode = runner.run()
|
||||
assert status == 'timeout'
|
||||
assert exitcode == 254
|
||||
|
||||
|
||||
def test_run_command_failed(rc):
|
||||
rc.command = ['false']
|
||||
runner = Runner(config=rc)
|
||||
status, exitcode = runner.run()
|
||||
assert status == 'failed'
|
||||
assert exitcode == 1
|
||||
|
||||
|
||||
def test_executable_not_found(rc):
|
||||
rc.command = ['supercalifragilistic']
|
||||
runner = Runner(config=rc)
|
||||
status, exitcode = runner.run()
|
||||
assert status == 'failed'
|
||||
assert exitcode == 127
|
||||
events = list(runner.events)
|
||||
assert len(events) == 1
|
||||
assert 'The command was not found or was not executable: supercalifragilistic' in events[0]['stdout'] # noqa
|
||||
|
||||
|
||||
def test_run_command_long_running(rc):
|
||||
rc.command = ['yes']
|
||||
runner = Runner(config=rc)
|
||||
status, exitcode = runner.run()
|
||||
assert status == 'timeout'
|
||||
assert exitcode == 254
|
||||
|
||||
|
||||
def test_run_command_long_running_children(rc):
|
||||
rc.command = ['bash', '-c', "(yes)"]
|
||||
runner = Runner(config=rc)
|
||||
status, exitcode = runner.run()
|
||||
assert status == 'timeout'
|
||||
assert exitcode == 254
|
||||
|
||||
|
||||
def test_run_command_events_missing(rc):
|
||||
rc.command = ['sleep','1']
|
||||
runner = Runner(config=rc)
|
||||
status, exitcode = runner.run()
|
||||
assert status == 'successful'
|
||||
assert exitcode == 0
|
||||
assert list(runner.events) == []
|
||||
|
||||
|
||||
def test_run_command_stdout_missing(rc):
|
||||
rc.command = ['sleep','1']
|
||||
runner = Runner(config=rc)
|
||||
status, exitcode = runner.run()
|
||||
assert status == 'successful'
|
||||
assert exitcode == 0
|
||||
os.unlink(os.path.join(runner.config.artifact_dir, 'stdout'))
|
||||
with pytest.raises(AnsibleRunnerException):
|
||||
list(runner.stdout)
|
||||
|
||||
|
||||
def test_run_command_no_stats(rc):
|
||||
rc.command = ['sleep','1']
|
||||
runner = Runner(config=rc)
|
||||
status, exitcode = runner.run()
|
||||
assert status == 'successful'
|
||||
assert exitcode == 0
|
||||
assert runner.stats is None
|
||||
|
||||
|
||||
def test_run_command_ansible(rc):
|
||||
rc.module = "debug"
|
||||
rc.host_pattern = "localhost"
|
||||
rc.prepare()
|
||||
runner = Runner(config=rc)
|
||||
status, exitcode = runner.run()
|
||||
assert status == 'successful'
|
||||
assert exitcode == 0
|
||||
assert list(runner.events) != []
|
||||
assert runner.stats != {}
|
||||
assert list(runner.host_events('localhost')) != []
|
||||
stdout = runner.stdout
|
||||
assert stdout.read() != ""
|
||||
|
||||
|
||||
def test_run_command_ansible_event_handler(rc):
|
||||
event_handler = MagicMock()
|
||||
status_handler = MagicMock()
|
||||
rc.module = "debug"
|
||||
rc.host_pattern = "localhost"
|
||||
rc.prepare()
|
||||
runner = Runner(config=rc, event_handler=event_handler, status_handler=status_handler)
|
||||
status, exitcode = runner.run()
|
||||
assert status == 'successful'
|
||||
assert exitcode == 0
|
||||
event_handler.assert_called()
|
||||
status_handler.assert_called()
|
||||
|
||||
|
||||
def test_run_command_ansible_event_handler_failure(rc):
|
||||
def event_handler(*args):
|
||||
raise IOError()
|
||||
rc.module = "debug"
|
||||
rc.host_pattern = "localhost"
|
||||
rc.prepare()
|
||||
runner = Runner(config=rc, event_handler=event_handler)
|
||||
status, exitcode = runner.run()
|
||||
assert status == 'successful'
|
||||
assert exitcode == 0
|
||||
|
||||
|
||||
def test_run_command_ansible_rotate_artifacts(rc):
|
||||
rc.module = "debug"
|
||||
rc.host_pattern = "localhost"
|
||||
rc.prepare()
|
||||
rc.rotate_artifacts = 1
|
||||
runner = Runner(config=rc)
|
||||
status, exitcode = runner.run()
|
||||
assert status == 'successful'
|
||||
assert exitcode == 0
|
||||
runner = Runner(config=rc)
|
||||
status, exitcode = runner.run()
|
||||
assert status == 'successful'
|
||||
assert exitcode == 0
|
||||
|
||||
|
||||
def test_get_fact_cache(rc):
|
||||
assert os.path.basename(rc.fact_cache) == 'fact_cache'
|
||||
rc.module = "setup"
|
||||
rc.host_pattern = "localhost"
|
||||
rc.prepare()
|
||||
runner = Runner(config=rc)
|
||||
status, exitcode = runner.run()
|
||||
assert status == 'successful'
|
||||
assert exitcode == 0
|
||||
print(rc.cwd)
|
||||
assert os.path.exists(os.path.join(rc.artifact_dir, 'fact_cache'))
|
||||
assert os.path.exists(os.path.join(rc.artifact_dir, 'fact_cache', 'localhost'))
|
||||
data = runner.get_fact_cache('localhost')
|
||||
assert data
|
||||
|
||||
|
||||
def test_set_fact_cache(rc):
|
||||
assert os.path.basename(rc.fact_cache) == 'fact_cache'
|
||||
rc.module = "debug"
|
||||
rc.module_args = "var=message"
|
||||
rc.host_pattern = "localhost"
|
||||
rc.prepare()
|
||||
runner = Runner(config=rc)
|
||||
runner.set_fact_cache('localhost', dict(message='hello there'))
|
||||
status, exitcode = runner.run()
|
||||
assert status == 'successful'
|
||||
assert exitcode == 0
|
||||
print(rc.cwd)
|
||||
assert os.path.exists(os.path.join(rc.artifact_dir, 'fact_cache'))
|
||||
assert os.path.exists(os.path.join(rc.artifact_dir, 'fact_cache', 'localhost'))
|
||||
data = runner.get_fact_cache('localhost')
|
||||
assert data['message'] == 'hello there'
|
||||
|
||||
|
||||
def test_set_extra_vars(rc):
|
||||
rc.module = "debug"
|
||||
rc.module_args = "var=test_extra_vars"
|
||||
rc.host_pattern = "localhost"
|
||||
rc.extra_vars = dict(test_extra_vars='hello there')
|
||||
rc.prepare()
|
||||
runner = Runner(config=rc)
|
||||
status, exitcode = runner.run()
|
||||
with open(os.path.join(rc.artifact_dir, 'stdout')) as f:
|
||||
assert 'hello there' in f.read()
|
||||
|
||||
@@ -0,0 +1,216 @@
|
||||
import io
|
||||
import os
|
||||
import socket
|
||||
import concurrent.futures
|
||||
import time
|
||||
|
||||
import pytest
|
||||
import json
|
||||
|
||||
from ansible_runner import run
|
||||
from ansible_runner.streaming import Transmitter, Worker, Processor
|
||||
|
||||
import ansible_runner.interface # AWX import pattern
|
||||
|
||||
|
||||
class TestStreamingUsage:
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def reset_self_props(self):
|
||||
self.status_data = None
|
||||
|
||||
def status_handler(self, status_data, runner_config=None):
|
||||
self.status_data = status_data
|
||||
|
||||
def get_job_kwargs(self, job_type):
|
||||
"""For this test scenaro, the ansible-runner interface kwargs"""
|
||||
if job_type == 'run':
|
||||
job_kwargs = dict(playbook='debug.yml')
|
||||
else:
|
||||
job_kwargs = dict(module='setup', host_pattern='localhost')
|
||||
# also test use of user env vars
|
||||
job_kwargs['envvars'] = dict(MY_ENV_VAR='bogus')
|
||||
return job_kwargs
|
||||
|
||||
def check_artifacts(self, process_dir, job_type):
|
||||
|
||||
assert set(os.listdir(process_dir)) == {'artifacts',}
|
||||
|
||||
events_dir = os.path.join(process_dir, 'artifacts', 'job_events')
|
||||
events = []
|
||||
for file in os.listdir(events_dir):
|
||||
with open(os.path.join(events_dir, file), 'r') as f:
|
||||
if file in ('status', 'rc'):
|
||||
continue
|
||||
content = f.read()
|
||||
events.append(json.loads(content))
|
||||
stdout = '\n'.join(event['stdout'] for event in events)
|
||||
|
||||
if job_type == 'run':
|
||||
assert 'Hello world!' in stdout
|
||||
else:
|
||||
assert '"ansible_facts"' in stdout
|
||||
|
||||
@pytest.mark.parametrize("job_type", ['run', 'adhoc'])
|
||||
def test_remote_job_interface(self, tmpdir, test_data_dir, job_type):
|
||||
transmit_dir = os.path.join(test_data_dir, 'debug')
|
||||
worker_dir = str(tmpdir.mkdir('for_worker'))
|
||||
process_dir = str(tmpdir.mkdir('for_process'))
|
||||
job_kwargs = self.get_job_kwargs(job_type)
|
||||
|
||||
outgoing_buffer = io.BytesIO()
|
||||
|
||||
transmitter = Transmitter(_output=outgoing_buffer, private_data_dir=transmit_dir, **job_kwargs)
|
||||
|
||||
for key, value in job_kwargs.items():
|
||||
assert transmitter.kwargs.get(key, '') == value
|
||||
|
||||
status, rc = transmitter.run()
|
||||
assert rc in (None, 0)
|
||||
assert status == 'unstarted'
|
||||
|
||||
outgoing_buffer.seek(0) # rewind so we can start reading
|
||||
|
||||
sent = outgoing_buffer.getvalue()
|
||||
assert sent # should not be blank at least
|
||||
assert b'zipfile' in sent
|
||||
|
||||
incoming_buffer = io.BytesIO()
|
||||
|
||||
worker = Worker(_input=outgoing_buffer, _output=incoming_buffer, private_data_dir=worker_dir)
|
||||
worker.run()
|
||||
|
||||
assert set(os.listdir(worker_dir)) == {'artifacts', 'inventory', 'project', 'env'}, outgoing_buffer.getvalue()
|
||||
|
||||
incoming_buffer.seek(0) # again, be kind, rewind
|
||||
|
||||
processor = Processor(_input=incoming_buffer, private_data_dir=process_dir)
|
||||
processor.run()
|
||||
|
||||
self.check_artifacts(process_dir, job_type)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("job_type", ['run', 'adhoc'])
|
||||
def test_remote_job_by_sockets(self, tmpdir, test_data_dir, container_runtime_installed, job_type):
|
||||
"""This test case is intended to be close to how the AWX use case works
|
||||
the process interacts with receptorctl with sockets
|
||||
sockets are used here, but worker is manually called instead of invoked by receptor
|
||||
"""
|
||||
transmit_dir = os.path.join(test_data_dir, 'debug')
|
||||
worker_dir = str(tmpdir.mkdir('for_worker'))
|
||||
process_dir = str(tmpdir.mkdir('for_process'))
|
||||
job_kwargs = self.get_job_kwargs(job_type)
|
||||
|
||||
def transmit_method(transmit_sockfile_write):
|
||||
return ansible_runner.interface.run(
|
||||
streamer='transmit',
|
||||
_output=transmit_sockfile_write,
|
||||
private_data_dir=transmit_dir, **job_kwargs)
|
||||
|
||||
def worker_method(transmit_sockfile_read, results_sockfile_write):
|
||||
return ansible_runner.interface.run(
|
||||
streamer='worker',
|
||||
_input=transmit_sockfile_read, _output=results_sockfile_write,
|
||||
private_data_dir=worker_dir, **job_kwargs)
|
||||
|
||||
def process_method(results_sockfile_read):
|
||||
return ansible_runner.interface.run(
|
||||
streamer='process', quiet=True,
|
||||
_input=results_sockfile_read,
|
||||
private_data_dir=process_dir, status_handler=self.status_handler, **job_kwargs)
|
||||
|
||||
transmit_socket_write, transmit_socket_read = socket.socketpair()
|
||||
results_socket_write, results_socket_read = socket.socketpair()
|
||||
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=3) as executor:
|
||||
transmit_future = executor.submit(transmit_method, transmit_socket_write.makefile('wb'))
|
||||
# In real AWX implementation, worker is done via receptorctl
|
||||
executor.submit(worker_method, transmit_socket_read.makefile('rb'), results_socket_write.makefile('wb'))
|
||||
|
||||
while True:
|
||||
if transmit_future.done():
|
||||
break
|
||||
time.sleep(0.05) # additionally, AWX calls cancel_callback()
|
||||
|
||||
res = transmit_future.result()
|
||||
assert res.rc in (None, 0)
|
||||
assert res.status == 'unstarted'
|
||||
|
||||
process_future = executor.submit(process_method, results_socket_read.makefile('rb'))
|
||||
|
||||
while True:
|
||||
if process_future.done():
|
||||
break
|
||||
time.sleep(0.05) # additionally, AWX calls cancel_callback()
|
||||
|
||||
for s in (transmit_socket_write, transmit_socket_read, results_socket_write, results_socket_read):
|
||||
s.close()
|
||||
|
||||
assert self.status_data is not None
|
||||
if 'result_traceback' in self.status_data:
|
||||
raise Exception(self.status_data['result_traceback'])
|
||||
assert self.status_data.get('status') == 'successful'
|
||||
|
||||
assert set(os.listdir(worker_dir)) == {'artifacts', 'inventory', 'project', 'env'}
|
||||
|
||||
self.check_artifacts(process_dir, job_type)
|
||||
|
||||
|
||||
def test_missing_private_dir_transmit(tmpdir):
|
||||
outgoing_buffer = io.BytesIO()
|
||||
|
||||
# Transmit
|
||||
with pytest.raises(ValueError) as excinfo:
|
||||
run(
|
||||
streamer='transmit',
|
||||
_output=outgoing_buffer,
|
||||
private_data_dir='/foo/bar/baz',
|
||||
playbook='debug.yml',
|
||||
)
|
||||
|
||||
assert "private_data_dir path is either invalid or does not exist" in str(excinfo.value)
|
||||
|
||||
|
||||
def test_garbage_private_dir_worker(tmpdir):
|
||||
worker_dir = str(tmpdir.mkdir('for_worker'))
|
||||
incoming_buffer = io.BytesIO(
|
||||
b'{"kwargs": {"playbook": "debug.yml"}}\n{"zipfile": 5}\n\x01\x02\x03\x04\x05{"eof": true}\n')
|
||||
outgoing_buffer = io.BytesIO()
|
||||
|
||||
# Worker
|
||||
run(
|
||||
streamer='worker',
|
||||
_input=incoming_buffer,
|
||||
_output=outgoing_buffer,
|
||||
private_data_dir=worker_dir,
|
||||
)
|
||||
sent = outgoing_buffer.getvalue()
|
||||
assert b'"status": "error"' in sent
|
||||
|
||||
|
||||
def test_unparsable_private_dir_worker(tmpdir):
|
||||
worker_dir = str(tmpdir.mkdir('for_worker'))
|
||||
incoming_buffer = io.BytesIO(b'')
|
||||
outgoing_buffer = io.BytesIO()
|
||||
|
||||
# Worker
|
||||
run(
|
||||
streamer='worker',
|
||||
_input=incoming_buffer,
|
||||
_output=outgoing_buffer,
|
||||
private_data_dir=worker_dir,
|
||||
)
|
||||
sent = outgoing_buffer.getvalue()
|
||||
assert b'"status": "error"' in sent
|
||||
|
||||
|
||||
def test_unparsable_private_dir_processor(tmpdir):
|
||||
process_dir = str(tmpdir.mkdir('for_process'))
|
||||
incoming_buffer = io.BytesIO(b'')
|
||||
|
||||
processor = run(
|
||||
streamer='process',
|
||||
_input=incoming_buffer,
|
||||
private_data_dir=process_dir,
|
||||
)
|
||||
assert processor.status == 'error'
|
||||
Reference in New Issue
Block a user