Testinfraを使って、サービスの状態を確認してみる【Ansible×Testinfra】

Linux,Python

testinfra-handsonアイキャッチ画像
ブログ運営者
さいとう

閲覧いただきありがとうございます!"さいとう"と申します。わたしは異業種・未経験からIT業界に転職し、現在インフラエンジニアとしてクラウド環境の設計や構築・運用の支援を行っています。

Salt、Ansible、Puppet、Chefなどの管理ツールによって、インフラ構築の自動化が進んでいます。これらのIaC(Infrastructure as Code)ツールの強みは、同じ構成のサーバを何百台も一気に構築できることです。


しかし、本当に全てのサーバが同じ構成になっているかをどのように確認していますか?


一台一台に接続してコマンドを実行するのは現実的ではありません。そこで、今回の記事ではIaCツールで構成されたサーバの状態をテストする「Testinfra」について、ハンズオンを交えながら紹介します。


Testinfraの主な特徴

testinfra-handsonアイコン

TestinfraはPython製のテストフレームワークで、インフラの状態をテスト駆動開発(TDD)の原則に従って検証するために使用されます。pipを使ってTestinfraをインストールし、テストファイルを用意するだけで簡単に実行できます。Pythonでのテストといえばpytestが思い浮かびますが、Testinfraはそのpytestをベースにしたフレームワークで、インフラストラクチャ(特にサーバーやシステムの状態)のテストに特化しています。


Testinfraの優れた点は、SSH、Docker、Salt、Ansibleなど、さまざまなバックエンドを通じてリモートマシンやコンテナに対するテストをサポートしていることです。インフラエンジニアとして、ぜひ使いこなせるようになりたいツールです。


■ハンズオン

testinfra-handson仕組み

今回のハンズオンは、Ansibleで構成管理するサーバに対し、Testinfraを使用してnginxの実行状況と自動起動の有効化、index.htmlの存在確認をテストする内容です。


先述した通り、Testinfraはインフラストラクチャの状態確認のテストに特化していて、IaCツールとも親和性が高いです。たとえばテストするサーバへの接続に関して、Ansibleのhostsファイルやカスタムインベントリファイルを参照することができます。わざわざTestinfraのためのhostsファイルを用意する必要がなく、現在利用しているシステムに簡単に組み込むことができるかと思います。

●環境準備

使用する環境に関して、「Ansibleを利用してnginxをインストール・起動してみる」の環境をそのまま利用します。記事を参考にして、コントロールノード1台、管理ノード2台を用意しましょう。

●testinfraインストール

testinfraパッケージはpipでインストールします。pipがインストールされていない方は、まずはpipをインストールしましょう。

sudo dnf install python3-pip -y


【実行結果】

[ec2-user@ip-10-0-1-136 ~]$ sudo dnf install python3-pip -y
Last metadata expiration check: 0:04:31 ago on Sat Feb 17 06:30:53 2024.
Dependencies resolved.
===================================================================================================================================================
 Package                              Architecture               Version                                     Repository                       Size 
===================================================================================================================================================
Installing:
 python3-pip                          noarch                     21.3.1-2.amzn2023.0.5                       amazonlinux                     1.8 M 
Installing weak dependencies:
 libxcrypt-compat                     x86_64                     4.4.33-7.amzn2023                           amazonlinux                      92 k 

Transaction Summary
===================================================================================================================================================
Install  2 Packages

<省略>

    Release notes:
     https://docs.aws.amazon.com/linux/al2023/release-notes/relnotes-2023.3.20240205.html

===================================================================================================================================================

Installed:
  libxcrypt-compat-4.4.33-7.amzn2023.x86_64                                python3-pip-21.3.1-2.amzn2023.0.5.noarch

Complete!


つづいてtestinfraをインストールします。

pip install pytest-testinfra


【実行結果】

[ec2-user@ip-10-0-1-136 ~]$ pip install pytest-testinfra
Defaulting to user installation because normal site-packages is not writeable
Collecting pytest-testinfra
  Downloading pytest_testinfra-10.1.0-py3-none-any.whl (76 kB)
     |████████████████████████████████| 76 kB 4.4 MB/s

<省略>

 Collecting exceptiongroup>=1.0.0rc8
  Downloading exceptiongroup-1.2.0-py3-none-any.whl (16 kB)
Installing collected packages: tomli, pluggy, packaging, iniconfig, exceptiongroup, pytest, pytest-testinfra
Successfully installed exceptiongroup-1.2.0 iniconfig-2.0.0 packaging-23.2 pluggy-1.4.0 pytest-8.0.1 pytest-testinfra-10.1.0 tomli-2.0.1


testinfraインストールは以上です。

●テストファイル作成

testinfraで利用するテストファイルを作成していきます。テストする内容は、nginxが実行中で、かつ自動起動の設定が有効化されているかと、index.htmlが/usr/share/nginx/html/に格納されているかを確認します。わたしはテストファイルを自身のユーザー直下に作成しますが、testディレクトリを作成していただいても大丈夫です。

vim test_management_node.py


test_management_node.py

import pytest

def test_nginx_running_and_enabled(host):
    # Nginxサービスが実行中かつ自動起動設定されているかを確認
    nginx = host.service("nginx")
    assert nginx.is_running
    assert nginx.is_enabled

def test_index_html_exists(host):
    # /usr/share/nginx/html/index.html ファイルが存在するかを確認
    index_html = host.file("/usr/share/nginx/html/index.html")
    assert index_html.exists

テストファイル作成は以上です。

●テスト実行

テストする準備が整いましたので、実際にテストしてみましょう。実行コマンドは以下です。

py.test -v --hosts='ansible://all' --ansible-inventory=/home/ec2-user/inventory.txt test_management_node.py


コマンドの内容は、実行コマンドであるpy.testに、詳細表示のvオプションをつけ、全サーバに対し、どのテストを実行するかを表しています。–ansible-inventoryをつけない場合、デフォルトでnasibleのhostsファイルを参照します。カスタムインベントリファイルを利用している場合は、–ansible-inventoryでファイルパスを指定しましょう。

【実行結果】

[ec2-user@ip-10-0-1-136 ~]$ py.test -v --hosts='ansible://all' --ansible-inventory=/home/ec2-user/inventory.txt test_management_node.py
=============================================================== test session starts ===============================================================
platform linux -- Python 3.9.16, pytest-8.0.1, pluggy-1.4.0 -- /usr/bin/python3
cachedir: .pytest_cache
rootdir: /home/ec2-user
plugins: testinfra-10.1.0
collected 4 items

test_management_node.py::test_nginx_running_and_enabled[ansible://ansible-test-target1] PASSED                                              [ 25%]
test_management_node.py::test_index_html_exists[ansible://ansible-test-target1] PASSED                                                      [ 50%]
test_management_node.py::test_nginx_running_and_enabled[ansible://ansible-test-target2] PASSED                                              [ 75%]
test_management_node.py::test_index_html_exists[ansible://ansible-test-target2] PASSED                                                      [100%]

================================================================ 4 passed in 4.43s ================================================================


testinfra-handson結果



管理するサーバ2台に対し、2つのテストが実行され、すべて"pass"したことがわかりますね。実際の現場ではテスト項目がさらに増え、対象サーバも増えるかと思います。テスト実行は以上です。

まとめ

Testinfraはインフラ自動化をさらに推進し、堅牢な構築を可能にするツールです。脆弱性対応のためのサーバ入れ替えや、新規サーバ構築時に要件に沿ったインフラ構築の確認が容易になります。


今回はハンズオンでAnsibleと組み合わせてTestinfraを使用しましたが、ローカルホストの単体テストやDocker、kubectl、OpenShiftなどのコンテナのテストにも活用できます。Testinfraを使用することで、インフラの一貫性と信頼性を確保し、効率的な運用が実現できます。ぜひ試してみてください。

参考リンク: Testinfra