使用Testinfra和Ansible验证服务器状态

  • 使用Testinfra和Ansible验证服务器状态已关闭评论
  • 119 views
  • A+
所属分类:运维实战

Testinfra是一个功能强大的库,用于编写测试以验证基础架构的状态。与Ansible和Nagios相结合,它提供了一种简单的解决方案,可以将基础架构强制为代码。

Testinfra入门

可以使用Python包管理器(pip)和Python虚拟环境轻松安装Testinfra。

$ python3 -m venv venv
$ source venv/bin/activate
(venv) $ pip install testinfra

Testinfra也可以使用EPEL存储库在Fedora和CentOS的软件包存储库中使用。例如,在CentOS 7上,您可以使用以下命令安装它:

yum install -y epel-release
$ yum install -y python-testinfra

一个简单的测试脚本

在Testinfra中编写测试很容易。使用您选择的代码编辑器,将以下内容添加到名为test_simple.py的文件中:

import testinfra

def test_os_release(host):
    assert host.file("/etc/os-release").contains("Fedora")

def test_sshd_inactive(host):
    assert host.service("sshd").is_running is False
默认情况下,Testinfra为测试用例提供宿主对象; 此对象提供对不同帮助程序模块的访问。例如,第一个测试使用文件模块验证主机上文件的内容,第二个测试用例使用服务模块检查systemd服务的状态。

要在本地计算机上运行这些测试,请执行以下命令:

(venv)$ pytest test_simple.py
================================ test session starts =============================
platform linux -- Python 3.7.3, pytest-4.4.1, py-1.8.0, pluggy-0.9.0
rootdir: /home/cverna/Documents/Python/testinfra
plugins: testinfra-3.0.0
collected 2 items
test_simple.py ..

================================ 2 passed in 0.05 seconds ========================
有关Testinfra API的完整列表,您可以参考文档

Testinfra和Ansible

estinfra支持的后端之一是Ansible,这意味着Testinfra可以直接使用Ansible的库存文件和库存中定义的一组机器来对它们进行测试。

我们使用以下库存文件作为示例:

[web]
app-frontend01
app-frontend02

[database]
db-backend01

我们希望确保我们的Apache Web服务器服务在app-frontend01app-frontend02上运行。让我们在名为test_web.py的文件中编写测试:

def check_httpd_service(host):
    """Check that the httpd service is running on the host"""
    assert host.service("httpd").is_running

要使用Testinfra和Ansible运行此测试,请使用以下命令:

(venv) $ pip install ansible
(venv) $ py.test --hosts=web --ansible-inventory=inventory --connection=ansible test_web.py

在调用测试时,我们使用Ansible库存[web]组作为目标计算机,并指定我们要使用Ansible作为连接后端。

使用Ansible模块

Testinfra还为Ansible提供了一个很好的API,可用于测试。Ansible模块允许访问在测试中运行Ansible,并且可以轻松检查结果。

    """ 
    Verify that a package is installed using Ansible
    package module
    """
    assert not host.ansible("package", "name=httpd state=present")["changed"]

默认情况下,启用Ansible的  检查模式,这意味着Ansible将报告在远程主机上执行播放时会发生什么变化。

Testinfra和Nagios

现在我们可以轻松地运行测试来验证机器的状态,我们可以使用这些测试来触发监控系统上的警报。这是捕获意外更改的好方法。

Testinfra提供与Nagios的集成,Nagios是一种流行的监控解决方案。默认情况下,Nagios使用NRPE插件对远程主机执行检查,但使用Testinfra可以直接从Nagios主机运行测试。

要使Testinfra输出与Nagios兼容,我们必须在触发测试时使用--nagios标志。我们还使用-qq pytest标志来启用pytest的安静模式,因此不会显示所有测试详细信息。

(venv) $ py.test --hosts=web --ansible-inventory=inventory --connection=ansible --nagios -qq line test.py 
TESTINFRA OK - 1 passed, 0 failed, 0 skipped in 2.55 seconds

Testinfra是一个功能强大的库,用于编写测试以验证基础架构的状态。与Ansible和Nagios相结合,它提供了一种简单的解决方案,可以将基础架构强制为代码。它也是使用Molecule在Ansible角色开发过程中添加测试的关键组件。

  • 安卓客户端下载
  • 微信扫一扫
  • weinxin
  • 微信公众号
  • 微信公众号扫一扫
  • weinxin
avatar