在 testinfra 中使用 Ansible 变量 [英] Using Ansible variables in testinfra

查看:30
本文介绍了在 testinfra 中使用 Ansible 变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用带有 Ansible 后端的 TestInfra 进行测试.除了在运行测试时使用 Ansible 本身外,一切都很好

Using TestInfra with Ansible backend for testing purposes. Everything goes fine except using Ansible itself while running tests

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 变量.可以通过运行这个playbook获得

where zabbix_agent_version is an Ansible variable from group_vars. It can be obtained by running this playbook

- 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

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 时可以看到它吗?

Any idea why Ansible can't see this variable when running testinfra's Ansible module while it can see it while running Ansible alone?

推荐答案

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

If zabbix_agent_version is a variable set using group_vars, then it seems as if you should be accessing it using host.ansible.get_variables() rather than running debug task. In any case, both should work. If I have, in my current directory:

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'

然后所有测试都通过了:

Then all tests pass:

$ 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 目录相对于您的测试的位置)与我在此处显示的内容相符吗?

Can you confirm that the layout of our files (in particular, the location of your group_vars directory relative to the your tests) matches what I've shown here?

这篇关于在 testinfra 中使用 Ansible 变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆