ansible批量添加hosts到zabbix-server

运维自动化,ansible就是军火库。

通过ansible批量执行命令可以在被监控主机批量安装和配置zabbix-agent,但是添加主机到zabbix-server还是要手动执行。曾经写了一个python脚本批量生成hosts的xml然后再导入link,实现了批量添加。今天研究了ansible监控模块zabbix_host实现了通过zabbix API批量添加。

环境准备

1
2
3
yum install ansible
yum install python-pip
pip install zabbix-api --proxy 172.x.x.x:3182

代码

playbook add-hosts.yaml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
---
- hosts: test
tasks:
- name: wget repo file
get_url:
url: http://172.x.x.x/CentOS-Base.repo
dest: /etc/yum.repos.d/
- name: install zabbix-agent
yum:
name: http://172.x.x.x/zabbix/zabbix-agent.rpm
state: present
update_cache: yes
- name: config zabbix-agent
lineinfile:

- name: start and enable zabbix-agent
service :
name: zabbix-agent
state: started
enabled: yes
- name: create a new host
local_action:
module: zabbix_host
server_url: http://172.23.20.250/zabbix
login_user: Admin
login_password: zabbix
force: yes
host_name: "{{ ansible_default_ipv4.address }}"
visible_name: "{{ ansible_default_ipv4.address }}-责任人"
host_groups:
- Linux servers
link_templates:
- Linux-Templates
status: enabled
state: present
inventory_mode: automatic
interfaces:
- type: 1
main: 1
useip: 1
ip: "{{ ansible_default_ipv4.address }}"
dns: ""
port: 10050

hosts

1
2
3
4
5
[test]
172.23.0.1
[test:vars]
ansible_ssh_user=xxx
ansible_ssh_pass=aaa

执行

1
ansible-playbook -i hosts add-hosts.yaml

参考链接

http://blog.csdn.net/felix_yujing/article/details/78166295
https://github.com/igogorevi4/ansible/blob/master/roles/zabbix-agent/tasks/add_to_zabbix.yml