在zabbix頁面上配置主機監控項還是比較容易的,但是當要添加的主機數量很多時,手動一個個區添加還是很累的。除了手動外,可以寫python腳本等去添加,好在ansible的zabbix_host模塊已經幫我們實現這個功能,通過ansible playbook我們就能快速完成zabbix主機監控的添加。
環境說明
環境 | 版本 |
---|---|
CentOS | 7 |
Ansible | 2.3.2 |
Zabbix | 2.4.7 |
Python | >=2.6 |
假設,zabbix服務器的地址爲:192.168.0.100
需要注意的是,ansible是基於python開發的,要使用zabbix_host模塊,需要安裝zabbix-api軟件包。安裝方法如下:
pip install zabbix-api
Ansible任務示例
# 安裝zabbix
- name: install zabbix
yum: name=zabbix state=present
become: true
# 配置zabbix agent
- name: config /etc/zabbix/zabbix_agentd.conf
lineinfile: dest=/etc/zabbix/zabbix_agentd.conf state=present regexp='^Server=' line='Server=192.168.0.100'
become: true
# 如果/etc/zabbix_agentd.conf文件也存在,則也對其進行配置
- name: check /etc/zabbix_agentd.conf state
stat: path=/etc/zabbix_agentd.conf
register: check_etc_zabbix_agentd
- name: config /etc/zabbix_agentd.conf
when: check_etc_zabbix_agentd.stat.exists
lineinfile: dest=/etc/zabbix_agentd.conf state=present regexp='^Server=' line='Server=192.168.0.100'
become: true
# 重啓zabbix agent
- name: restart zabbix agent
service: name=zabbix-agent state=restarted enabled=yes
become: true
# 添加zabbix hosts
- name: add zabbix hosts
local_action:
module: zabbix_host
server_url: http://192.168.0.100/zabbix/
login_user: admin
login_password: password
host_name: '{{inventory_hostname}}'
visible_name: '{{project_name}}_{{inventory_hostname}}'
host_groups:
- '{{host_group}}'
link_templates:
- Template OS Linux
#status: disabled
status: enabled
state: present
interfaces:
- type: 1
main: 1
useip: 1
ip: '{{inventory_hostname}}'
dns: ""
port: 10050
tags:
- set_hosts
說明:
上面的ansible任務片段,實現了zabbix agent的安裝和配置,並將其添加到zabbix server上。
注意1:
在安裝zabbix agent的時候,發現有的服務器存在/etc/zabbix/zabbix_agentd.conf和/etc/zabbix_agentd.conf兩個配置文件,agent在啓動的時候,實際使用的配置文件可能不是你預計的那個,所以,我將這兩個都做了同樣的配置。
注意2:
在調用zabbix_host模塊的時候,安裝官網上的說明語法配置就不會有太大的問題。但要注意visible_name字段是在ansible的2.3版本以後才加入的,我之前使用的是ansible 2.2的版本,結果報錯不能識別這個字段屬性。爲了能夠設置visible_name,我特意將ansible升級到了2.3