当我们的Zabbix自动注册+Ansible自动部署在一起时,会碰出什么样的火花,答案就是可以实现执行ansible的一条命令,监控任意一台或多台主机。
一、配置好自动注册规则

1、编写playbook
1. [root@Ansible zabbix]# cat zabbix.yaml
2. - hosts: web03
3. vars:
4. - SERVER_IP: 172.16.1.71
5. tasks:
6. - name: Install Zabbix-Agent
7. yum:
8. name: https://mirrors.aliyun.com/zabbix/zabbix/5.0/rhel/7/x86_64/zabbix-agent-5.0.34-1.el7.x86_64.rpm
9. state: present
10. - name: Install centos-release-scl and Agent
11. yum:
12. name: centos-release-scl
13. state: present
14. - name: Install Agent
15. yum:
16. name: zabbix-agent
17. state: present
18. - name: Config Zabbix-Agent
19. template:
20. src: zabbix_agentd.conf.j2
21. dest: /etc/zabbix/zabbix_agentd.conf
22. notify: Restart Zabbix Agent
23. - name: Scp Zabbix Agent Configure
24. copy:
25. src: ./zabbix_agentd.d
26. dest: /etc/zabbix/
27. - name: Start Zabbix Agent
28. systemd:
29. name: zabbix-agent
30. state: started
31. enabled: yes
32.
33. handlers:
34. - name: Restart Zabbix Agent
35. systemd:
36. name: zabbix-agent
37. state: restarted
2、编写主机清单
1. [root@Ansible zabbix]# cat hosts
2. [web_group]
3. web03 ansible_ssh_host=172.16.1.9
3、编写zabbix客户端配置文件,方便进行推送
1. [root@Ansible zabbix]# grep -v '^$\|^#' zabbix_agentd.conf.j2
2. PidFile=/var/run/zabbix/zabbix_agentd.pid
3. LogFile=/var/log/zabbix/zabbix_agentd.log
4. LogFileSize=0
5. Server={{ SERVER_IP }}
6. ServerActive={{ SERVER_IP }}
7. Hostname={{ ansible_hostname }}
8. Include=/etc/zabbix/zabbix_agentd.d/*.conf
4、如果需要自定义监控项也可以放到zabbix_agentd.d目录,跟配置文件一起推送过去,最终目录结构如下
1. [root@Ansible zabbix]# ll
2. total 24
3. -rw-r--r-- 1 root root 46 Jul 2 17:37 hosts
4. -rw-r--r-- 1 root root 16012 Jul 8 11:51 zabbix_agentd.conf.j2
5. drwxr-xr-x 2 root root 6 Jul 2 17:13 zabbix_agentd.d
6. -rw-r--r-- 1 root root 947 Jul 8 11:45 zabbix.yaml
三、运行Ansible,查看监控效果
如果主机多的话就用脚本做免密钥
1. [root@Ansible ~]# ssh-copy-id -i ~/.ssh/id_rsa.pub root@10.0.0.9
2.
3. [root@Ansible zabbix]# ansible-playbook -i hosts zabbix.yaml
执行后发现动作日志以及执行了自动注册的动作

也触发了邮箱
主机列表成功添加了主机

也会自动关联我们设定的模板,数据也可以采集到,大功告成!

我是koten,10年运维经验,持续分享运维干货,感谢大家的阅读和关注!