在testinfra中使用Ansible变量

时间:2017-10-17 14:17:17

标签: python testing ansible pytest

将TestInfra与Ansible后端一起用于测试目的。一切顺利,除了在运行测试时使用Ansible本身

test.py

import pytest
def test_zabbix_agent_package(host):
    package = host.package("zabbix-agent")
    assert package.is_installed
    package_version = host.ansible("debug", "msg={{ zabbix_agent_version }}")["msg"]
    (...)

其中zabbix_agent_version是group_vars的Ansible变量。它可以通过运行这个剧本来获得

- hosts: all
  become: true
  tasks:
  - name: debug
    debug: msg={{ zabbix_agent_version }}

命令执行测试

pytest --connection=ansible --ansible-inventory=inventory  --hosts=$hosts -v test.py

ansible.cfg

[defaults]
timeout = 10
host_key_checking = False
library=library/
retry_files_enabled = False
roles_path=roles/
pipelining=true
ConnectTimeout=60
remote_user=deploy
private_key_file=/opt/jenkins/.ssh/deploy

我得到的输出是

self = <ansible>, module_name = 'debug', module_args = 'msg={{ zabbix_agent_version }}', check = True, kwargs = {}
result = {'failed': True, 'msg': "the field 'args' has an invalid value, which appears to include a variable that is undefined. The error was: 'zabbix_agent_version' is undefined"}

    def __call__(self, module_name, module_args=None, check=True, **kwargs):
        if not self._host.backend.HAS_RUN_ANSIBLE:
            raise RuntimeError((
                "Ansible module is only available with ansible "
                "connection backend"))
        result = self._host.backend.run_ansible(
            module_name, module_args, check=check, **kwargs)
        if result.get("failed", False) is True:
>           raise AnsibleException(result)
E           AnsibleException: Unexpected error: {'failed': True,
E            'msg': u"the field 'args' has an invalid value, which appears to include a variable that is undefined. The error was: 'zabbix_agent_version' is undefined"}

/usr/lib/python2.7/site-packages/testinfra/modules/ansible.py:70: AnsibleException

任何想法为什么Ansible在运行testinfra的Ansible模块时看不到这个变量,而单独运行Ansible时可以看到它?

2 个答案:

答案 0 :(得分:3)

如果zabbix_agent_version是使用group_vars设置的变量,那么您似乎应该使用host.ansible.get_variables()而不是运行debug任务来访问它。无论如何,两者都应该有效。如果我有,请在我当前的目录中:

test_myvar.py
group_vars/
  all.yml

group_vars/all.yml我有:

myvar: value

test_myvar.py我有:

def test_myvar_using_get_variables(host):
    all_variables = host.ansible.get_variables()
    assert 'myvar' in all_variables
    assert all_variables['myvar'] == 'myvalue'


def test_myvar_using_debug_var(host):
    result = host.ansible("debug", "var=myvar")
    assert 'myvar' in result
    assert result['myvar'] == 'myvalue'


def test_myvar_using_debug_msg(host):
    result = host.ansible("debug", "msg={{ myvar }}")
    assert 'msg' in result
    assert result['msg'] == 'myvalue'

然后所有测试都通过:

$ py.test --connection=ansible --ansible-inventory=hosts -v 
test_myvar.py 
============================= test session starts ==============================
platform linux2 -- Python 2.7.13, pytest-3.2.3, py-1.4.34, pluggy-0.4.0 -- /home/lars/env/common/bin/python2
cachedir: .cache
rootdir: /home/lars/tmp/testinfra, inifile:
plugins: testinfra-1.8.1.dev2
collected 3 items                                                               

test_myvar.py::test_myvar_using_get_variables[ansible://localhost] PASSED
test_myvar.py::test_myvar_using_debug_var[ansible://localhost] PASSED
test_myvar.py::test_myvar_using_debug_msg[ansible://localhost] PASSED

=========================== 3 passed in 1.77 seconds ===========================

您能否确认我们的文件布局(特别是group_vars目录相对于您的测试的位置)与我在此处显示的内容相符?

答案 1 :(得分:0)

我追了几天的答案。这是最终对我有用的东西。基本上你使用testinfra的Ansible模块来访问Ansible的include_vars函数。

import pytest

@pytest.fixture()
def AnsibleVars(host):
ansible_vars = host.ansible(
    "include_vars", "file=./group_vars/all/vars.yml")
return ansible_vars["ansible_facts"]

然后在我的测试中,我将该函数作为参数包含在内:

def test_something(host, AnsibleVars):

此解决方案部分来自https://github.com/metacloud/molecule/issues/151

我有一个有趣的问题,我试图在我的主剧本中包含变量,并且在包含playbook.yml文件时我收到了“必须存储为字典/哈希”的错误。将变量分离到group_vars / all / vars.yml文件中可以解决该错误。