使用ansible添加zabbix的主机监控

àì夳堔傛蜴生んèń 2022-06-07 02:24 301阅读 0赞

在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软件包。安装方法如下:

  1. pip install zabbix-api

Ansible任务示例

  1. # 安装zabbix
  2. - name: install zabbix
  3. yum: name=zabbix state=present
  4. become: true
  5. # 配置zabbix agent
  6. - name: config /etc/zabbix/zabbix_agentd.conf
  7. lineinfile: dest=/etc/zabbix/zabbix_agentd.conf state=present regexp='^Server=' line='Server=192.168.0.100'
  8. become: true
  9. # 如果/etc/zabbix_agentd.conf文件也存在,则也对其进行配置
  10. - name: check /etc/zabbix_agentd.conf state
  11. stat: path=/etc/zabbix_agentd.conf
  12. register: check_etc_zabbix_agentd
  13. - name: config /etc/zabbix_agentd.conf
  14. when: check_etc_zabbix_agentd.stat.exists
  15. lineinfile: dest=/etc/zabbix_agentd.conf state=present regexp='^Server=' line='Server=192.168.0.100'
  16. become: true
  17. # 重启zabbix agent
  18. - name: restart zabbix agent
  19. service: name=zabbix-agent state=restarted enabled=yes
  20. become: true
  21. # 添加zabbix hosts
  22. - name: add zabbix hosts
  23. local_action:
  24. module: zabbix_host
  25. server_url: http://192.168.0.100/zabbix/
  26. login_user: admin
  27. login_password: password
  28. host_name: '{ {inventory_hostname}}'
  29. visible_name: '{ {project_name}}_{ {inventory_hostname}}'
  30. host_groups:
  31. - '{ {host_group}}'
  32. link_templates:
  33. - Template OS Linux
  34. #status: disabled
  35. status: enabled
  36. state: present
  37. interfaces:
  38. - type: 1
  39. main: 1
  40. useip: 1
  41. ip: '{ {inventory_hostname}}'
  42. dns: ""
  43. port: 10050
  44. tags:
  45. - 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

发表评论

表情:
评论列表 (有 0 条评论,301人围观)

还没有评论,来说两句吧...

相关阅读