使用ansible添加zabbix的主机监控
在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
还没有评论,来说两句吧...