zabbix について
zabbixは、Zabbix APIと公式Pythonライブラリzabbix_utilsを使った監視操作の自動化を案内するスキルです。Zabbix環境を管理する開発者や運用担当者向けに、リソース管理、監視データの照会、一括処理の例を提供します。
主な機能
- 01zabbix_utilsによるAPI呼び出し
- 02ホスト・テンプレート・アイテムの管理
- 03トリガー・ホストグループ・メンテナンス期間の管理
- 04問題・イベント・履歴データの照会
- 05Senderによるデータ送信
- 06一括管理スクリプトの例
活用シーン
- 01CSVからのホスト一括作成
- 02ホストのテンプレート検索やリンク
- 03メンテナンス期間の作成と問題の確認
- 04ホストまたはテンプレートデータのエクスポート
インストール
コマンドをコピーしてターミナルで実行します。
$
npx skills add https:/ / github.com/ julianobarbosa/ claude-code-skills --skill zabbixインストール後、Claude Code で/zabbixを入力して読み込まれたか確認します。
同梱ファイル
SKILL.md と一緒にインストールされる参考資料やスクリプト。
LICENSE.txtreferences/api-reference.mdtrigger-expressions.mdscripts/zabbix-bulk-hosts.pyzabbix-export.pyzabbix-maintenance.pyzabbix-status.py詳細
Zabbix 自動化スキル
概要
このスキルでは、API と公式 Python ライブラリ zabbix_utils を使用して Zabbix の監視操作を自動化する方法を説明します。
クイックスタート
インストール
pip install zabbix-utils --break-system-packages
認証
from zabbix_utils import ZabbixAPI
# Option 1: Username/password
api = ZabbixAPI(url="https://zabbix.example.com")
api.login(user="Admin", password="zabbix")
# Option 2: API token (Zabbix 5.4+, preferred)
api = ZabbixAPI(url="https://zabbix.example.com")
api.login(token="your_api_token")
# Verify connection
print(api.api_version())
環境変数のパターン
import os
from zabbix_utils import ZabbixAPI
api = ZabbixAPI(url=os.environ.get("ZABBIX_URL", "http://localhost/zabbix"))
api.login(token=os.environ["ZABBIX_TOKEN"])
コア API メソッド
すべての API は api.<object>.<method>() というパターンに従い、メソッドは get、create、update、delete です。
ホスト操作
# Get hosts
hosts = api.host.get(output=["hostid", "host", "name"],
selectInterfaces=["ip"])
# Create host
api.host.create(
host="server01",
groups=[{"groupid": "2"}], # Linux servers
interfaces=[{
"type": 1, # 1=agent, 2=SNMP, 3=IPMI, 4=JMX
"main": 1,
"useip": 1,
"ip": "192.168.1.100",
"dns": "",
"port": "10050"
}],
templates=[{"templateid": "10001"}]
)
# Update host
api.host.update(hostid="10084", status=0) # 0=enabled, 1=disabled
# Delete host
api.host.delete("10084")
テンプレート操作
# Get templates
templates = api.template.get(output=["templateid", "host", "name"],
selectHosts=["hostid", "name"])
# Link template to host
api.host.update(hostid="10084",
templates=[{"templateid": "10001"}])
# Import template from XML
with open("template.xml") as f:
api.configuration.import_(
source=f.read(),
format="xml",
rules={
"templates": {"createMissing": True, "updateExisting": True},
"items": {"createMissing": True, "updateExisting": True},
"triggers": {"createMissing": True, "updateExisting": True}
}
)
アイテム操作
# Get items
items = api.item.get(hostids="10084",
output=["itemid", "name", "key_"],
search={"key_": "system.cpu"})
# Create item
api.item.create(
name="CPU Load",
key_="system.cpu.load[percpu,avg1]",
hostid="10084",
type=0, # 0=Zabbix agent
value_type=0, # 0=float, 3=integer, 4=text
delay="30s",
interfaceid="1"
)
トリガー操作
# Get triggers
triggers = api.trigger.get(hostids="10084",
output=["triggerid", "description", "priority"],
selectFunctions="extend")
# Create trigger
api.trigger.create(
description="High CPU on {HOST.NAME}",
expression="last(/server01/system.cpu.load[percpu,avg1])>5",
priority=3 # 0=not classified, 1=info, 2=warning, 3=average, 4=high, 5=disaster
)
ホストグループ操作
# Get groups
groups = api.hostgroup.get(output=["groupid", "name"])
# Create group
api.hostgroup.create(name="Production/Web Servers")
# Add hosts to group
api.hostgroup.massadd(groups=[{"groupid": "5"}],
hosts=[{"hostid": "10084"}])
メンテナンス期間
import time
# Create maintenance
api.maintenance.create(
name="Server Maintenance",
active_since=int(time.time()),
active_till=int(time.time()) + 3600, # 1 hour
hostids=["10084"],
timeperiods=[{
"timeperiod_type": 0, # One-time
"period": 3600
}]
)
イベントと障害
# Get current problems
problems = api.problem.get(output=["eventid", "name", "severity"],
recent=True)
# Get events
events = api.event.get(hostids="10084",
time_from=int(time.time()) - 86400,
output="extend")
履歴データ
# Get history (value_type must match item's value_type)
# 0=float, 1=character, 2=log, 3=integer, 4=text
history = api.history.get(
itemids="28269",
history=0, # float
time_from=int(time.time()) - 3600,
output="extend",
sortfield="clock",
sortorder="DESC"
)
Zabbix Sender(トラッパーアイテム)
from zabbix_utils import Sender
sender = Sender(server="zabbix.example.com", port=10051)
# Send single value
response = sender.send_value("hostname", "trap.key", "value123")
print(response) # {"processed": 1, "failed": 0, "total": 1}
# Send multiple values
from zabbix_utils import ItemValue
values = [
ItemValue("host1", "key1", "value1"),
ItemValue("host2", "key2", 42),
]
response = sender.send(values)
Zabbix Getter(エージェントへの問い合わせ)
from zabbix_utils import Getter
agent = Getter(host="192.168.1.100", port=10050)
response = agent.get("system.uname")
print(response.value)
よく使うパターン
CSV からのホスト一括作成
import csv
from zabbix_utils import ZabbixAPI
api = ZabbixAPI(url="https://zabbix.example.com")
api.login(token="your_token")
with open("hosts.csv") as f:
for row in csv.DictReader(f):
try:
api.host.create(
host=row["hostname"],
groups=[{"groupid": row["groupid"]}],
interfaces=[{
"type": 1, "main": 1, "useip": 1,
"ip": row["ip"], "dns": "", "port": "10050"
}]
)
print(f"Created: {row['hostname']}")
except Exception as e:
print(f"Failed {row['hostname']}: {e}")
テンプレートがないホストを検索
# Get all hosts
all_hosts = api.host.get(output=["hostid", "host"],
selectParentTemplates=["templateid"])
# Filter hosts without specific template
template_id = "10001"
hosts_without = [h for h in all_hosts
if not any(t["templateid"] == template_id
for t in h.get("parentTemplates", []))]
パターンでトリガーを無効化
triggers = api.trigger.get(
search={"description": "test"},
output=["triggerid"]
)
for t in triggers:
api.trigger.update(triggerid=t["triggerid"], status=1) # 1=disabled
アイテムタイプのリファレンス
| タイプ | 値 | 説明 |
|---|---|---|
| Zabbix エージェント | 0 | アクティブチェック |
| Zabbix トラッパー | 2 | パッシブ。Sender 経由でデータを送信 |
| シンプルチェック | 3 | ICMP、TCP など |
| Zabbix 内部 | 5 | サーバー内部のメトリクス |
| Zabbix エージェント(アクティブ) | 7 | エージェントから開始 |
| HTTP エージェント | 19 | HTTP/REST API の監視 |
| 依存アイテム | 18 | マスターアイテムから派生 |
| スクリプト | 21 | カスタムスクリプト |
値のタイプのリファレンス
| タイプ | 値 | 説明 |
|---|---|---|
| 浮動小数点 | 0 | 数値(浮動小数点) |
| 文字 | 1 | 文字列 |
| ログ | 2 | ログファイル |
| 符号なし整数 | 3 | 数値(整数) |
| テキスト | 4 | テキスト |
トリガー深刻度のリファレンス
| 深刻度 | 値 | 色 |
|---|---|---|
| 未分類 | 0 | グレー |
| 情報 | 1 | 水色 |
| 警告 | 2 | 黄色 |
| 平均 | 3 | オレンジ |
| 高 | 4 | 薄い赤 |
| 災害 | 5 | 赤 |
エラー処理
from zabbix_utils import ZabbixAPI
from zabbix_utils.exceptions import APIRequestError
try:
api.host.create(host="duplicate_host", groups=[{"groupid": "2"}])
except APIRequestError as e:
print(f"API Error: {e.message}")
print(f"Code: {e.code}")
デバッグ
import logging
logging.basicConfig(level=logging.DEBUG)
# Now all API calls will be logged
スクリプトのリファレンス
すぐに使える自動化スクリプトについては、scripts/ ディレクトリを参照してください。
zabbix-bulk-hosts.py- CSV からのホスト一括管理zabbix-maintenance.py- メンテナンス期間の作成と管理zabbix-export.py- ホスト/テンプレートを JSON/XML にエクスポート
ベストプラクティス
- 可能な場合は、ユーザー名/パスワードより API トークンを使用する
- 出力フィールドを制限する -
output="extend"ではなく、必ずoutput=["field1", "field2"]を指定する - 検索/フィルターを使用する - すべてのオブジェクトを取得して Python でフィルタリングしない
- ページネーションを処理する - 大きな結果セットでは
limitとoffsetが必要になる場合があります - 一括操作を使用する - 一括変更には
massadd、massupdateを使用する - エラー処理 - API 呼び出しは必ず try/except で囲む
- 冪等性 - オブジェクトを作成する前に、すでに存在するか確認する
コメント
Markdown 対応