安装
  推荐yum安装
    RHEL(CentOS)5版本:
      rpm -Uvh http://mirror.pnl.gov/epel/5/i386/epel-release-5-4.noarch.rpm
    RHEL(CentOS)6版本:
      rpm -Uvh http://ftp.linux.ncsu.edu/pub/epel/6/i386/epel-release-6-8.noarch.rpm
    pip安装
      pip install ansible
      要自己手动创建/etc/ansible/hosts等文件夹
    由于后面要使用sshpass和ssh-copy-id于是
      yum install -y ssh-client sshpass

  目录结构
    ├── copy
    │   ├── zabbix-agent-3.2.11-1.el6.x86_64.rpm
    │   └── zabbix_pip.sh 
    ├── hosts
    ├── scripts
    │   └── zabbix.py
    ├── zabbix_ansible
    │   ├── group_vars
    │   ├── hosts
    │   ├── roles
    │   │   ├── ab
    │   │   │   ├── handlers
    │   │   │   │   └── main.yml
    │   │   │   └── tasks
    │   │   │   └── main.yml
    │   │   ├── as
    │   │   │   ├── handlers
    │   │   │   │   └── main.yml
    │   │   │   └── tasks
    │   │   │   └── main.yml
    │   │   └── common
    │   │   ├── handlers
    │   │   │   └── main.yml
    │   │   └── tasks
    │   │   └── main.yml
    │   ├── site.yml
    │   └── start.sh
    └── zabbix_ansible.tar.gz

  hosts
    [ab]
    xx.xx.xx.xx //填写自己需要的IP,也可以使用变量
    [as]
    xx.xx.xx.xx
    xx.xx.xx.xx
    [zainstall:children]
    ab
    as

  site.yml
    - hosts: zainstall
      roles:
      - common
    - hosts: as
      roles:
      - as
    - hosts: ab
      roles:
      - ab

  start.sh

#!/bin/bash

read -p "Please input a IP:" IP
read -p "Please input ab or as:" TYPE

if [ $TYPE = 'as' ]; then
  sed "/\[as\]/a $IP" -i hosts
else
  sed "/\[ab\]/a $IP" -i hosts
fi
sshpass -p 'xxxxx' ssh-copy-id -i /root/.ssh/id_rsa.pub -o StrictHostKeyChecking=no root@$IP

ansible-playbook -i hosts site.yml

  zabbix_pip.sh //我在客户端安装agent时发现zabbix-agent虽然启动,但10050端口没有监听,所以写了这个脚本

if [ ! -d "/var/run/zabbix/zabbix_agentd.pid"]; thenmkdir -p /var/run/zabbix && chown zabbix.zabbix /var/run/zabbix && touch zabbix_agentd.pid
fi

  roles/common/tasks/main.yml  //as和ab都要执行的任务
    - name: Copy rpm file to server
      copy:
      src: "{{ item }}"
      dest: /tmp/
      with_fileglob:
      - /etc/ansible/copy/*

      - name: Install package.
      yum:
      name: /tmp/zabbix-agent-3.2.11-1.el6.x86_64.rpm
      state: present

    - name: change zabbix-agent.conf
      command: sed -i.ori 's#Server=127.0.0.1#Server=xx.xx.xx.xx#' /etc/zabbix/zabbix_agentd.conf

    - name: set hostname
      shell: hostname
      register: info

    - name: change zabbix-agent.conf
      command: sed -i.ori '147c Hostname={{info.stdout}}' /etc/zabbix/zabbix_agentd.conf
      #debug: msg={{info.stdout}}

    - name: touch zabbix_agentd.pid
      command: /bin/bash /tmp/zabbix_pip.sh

    - name: start zabbix agent
      service: name=zabbix-agent state=started

  roles/as/tasks/main.yml
    - name: set hostname
      shell: hostname
      register: info

    - name: add host in zabbix server
      script: /etc/ansible/scripts/zabbix.py -C {{ansible_ssh_host}} "My Templates" "Template for AnyBackup process num,Template for AnyBackup process mem" {{info.stdout}}
      #debug: msg={{ansible_ssh_host}}
      notify:
       restart zabbix-agent

  roles/as/handlers/main.yml
    - name: restart zabbix-agent
      service: name=zabbix-agent state=restarted

  zabbix.py //控制zabbix服务端配置主机

#!/usr/bin/python
#coding:utf-8import json
import sys
import urllib2
import argparsefrom urllib2 import URLErrorreload(sys)
sys.setdefaultencoding('utf-8')class zabbix_api:def __init__(self):self.url = 'http://xx.xx.xx.xx:9800/api_jsonrpc.php'self.header = {"Content-Type":"application/json"}def user_login(self):data = json.dumps({"jsonrpc": "2.0","method": "user.login","params": {"user": "xx","password": "xxxx"},"id": 0})request = urllib2.Request(self.url, data)for key in self.header:request.add_header(key, self.header[key])try:result = urllib2.urlopen(request)except URLError as e:print "\033[041m 认证失败,请检查URL !\033[0m",e.codeexcept KeyError as e:print "\033[041m 认证失败,请检查用户名密码 !\033[0m",eelse:response = json.loads(result.read())result.close()#print response['result']self.authID = response['result']return self.authIDdef hostid_get_hostname(self, hostId=''):data = json.dumps({"jsonrpc": "2.0","method": "host.get","params": {"output": "extend","filter": {"hostid": hostId}},"auth": self.user_login(),"id": 1})request = urllib2.Request(self.url, data)for key in self.header:request.add_header(key, self.header[key])try:result = urllib2.urlopen(request)except URLError as e:if hasattr(e, 'reason'):print 'We failed to reach a server.'print 'Reason: ', e.reasonelif hasattr(e, 'code'):print 'The server could not fulfill the request.'print 'Error code: ', e.codeelse:response = json.loads(result.read())#print response
            result.close()if not len(response['result']):print "hostId is not exist"return Falsehost_dict=dict()for host in response['result']:status = {"0": "OK", "1": "Disabled"}available = {"0": "Unknown", "1": "available", "2": "Unavailable"}host_dict['name']=host['name']host_dict['status']=status[host['status']]host_dict['available']=available[host['available']]return host_dictdef hostid_get_hostip(self, hostId=''):data = json.dumps({"jsonrpc": "2.0","method": "hostinterface.get","params": {"output": "extend","filter": {"hostid": hostId}},"auth": self.user_login(),"id": 1})request = urllib2.Request(self.url, data)for key in self.header:request.add_header(key, self.header[key])try:result = urllib2.urlopen(request)except URLError as e:if hasattr(e, 'reason'):print 'We failed to reach a server.'print 'Reason: ', e.reasonelif hasattr(e, 'code'):print 'The server could not fulfill the request.'print 'Error code: ', e.codeelse:response = json.loads(result.read())# print response
            result.close()if not len(response['result']):print "\033[041m hostid \033[0m is not exist"return Falsefor hostip in response['result']:return hostip['ip']def host_get(self,hostName=''):data=json.dumps({"jsonrpc": "2.0","method": "host.get","params": {"output": "extend",#"filter":{"host":""}"filter":{"host":hostName}},"auth": self.user_login(),"id": 1})request = urllib2.Request(self.url,data)for key in self.header:request.add_header(key, self.header[key])try:result = urllib2.urlopen(request)except URLError as e:if hasattr(e, 'reason'):print 'We failed to reach a server.'print 'Reason: ', e.reasonelif hasattr(e, 'code'):print 'The server could not fulfill the request.'print 'Error code: ', e.codeelse:response = json.loads(result.read())#print reqponse
            result.close()if not len(response['result']):print "\033[041m %s \033[0m is not exist" % hostNamereturn Falseprint "主机数量: \033[31m%s\033[0m"%(len(response['result']))for host in response['result']:status={"0":"OK","1":"Disabled"}available={"0":"Unknown","1":"available","2":"Unavailable"}#print hostif len(hostName)==0:print "HostID : %s\t HostName : %s\t HostIp : %s\t Status :%s \t Available :%s"%(host['hostid'],host['name'],self.hostid_get_hostip(hostId=host['hostid']),status[host['status']],available[host['available']])else:print "HostID : %s\t HostName : %s\t HostIp : %s\t Status :\033[32m%s\033[0m \t Available :\033[31m%s\033[0m"%(host['hostid'],host['name'],self.hostid_get_hostip(hostId=host['hostid']),status[host['status']],available[host['available']])return host['hostid']def hostip_get(self, hostIp=''):data = json.dumps({"jsonrpc": "2.0","method": "hostinterface.get","params": {"output": "extend","filter": {"ip": hostIp}},"auth": self.user_login(),"id": 1})request = urllib2.Request(self.url, data)for key in self.header:request.add_header(key, self.header[key])try:result = urllib2.urlopen(request)except URLError as e:if hasattr(e, 'reason'):print 'We failed to reach a server.'print 'Reason: ', e.reasonelif hasattr(e, 'code'):print 'The server could not fulfill the request.'print 'Error code: ', e.codeelse:response = json.loads(result.read())# print response
            result.close()if not len(response['result']):print "\033[041m hostip \033[0m is not exist"return Falseprint "主机数量: \33[31m%s\33[0m" % (len(response['result']))for hostip in response['result']:host = self.hostid_get_hostname(hostip['hostid'])if len(hostip) == 0:print "HostID : %s\t HostName : %s\t HostIp : %s\t Status :\33[32m%s\33[0m \t Available :\33[31m%s\33[0m"%(hostip['hostid'],host['name'],hostip['ip'],host['status'],host['available'])else:print "HostID : %s\t HostName : %s\t HostIp : %s\t Status :\33[32m%s\33[0m \t Available :\33[31m%s\33[0m"%(hostip['hostid'],host['name'],hostip['ip'],host['status'],host['available'])return hostip['hostid']def hostgroup_get(self, hostgroupName=''):data = json.dumps({"jsonrpc":"2.0","method":"hostgroup.get","params":{"output": "extend","filter": {"name": hostgroupName}},"auth":self.user_login(),"id":1,})request = urllib2.Request(self.url,data)for key in self.header:request.add_header(key, self.header[key])try:result = urllib2.urlopen(request)except URLError as e:print "Error as ", eelse:# result.read()response = json.loads(result.read())result.close()#print response()if not len(response['result']):print "\033[041m %s \033[0m is not exist" % hostgroupNamereturn Falsefor group in response['result']:if  len(hostgroupName)==0:print "hostgroup:  \033[31m%s\033[0m \tgroupid : %s" %(group['name'],group['groupid'])else:print "hostgroup:  \033[31m%s\033[0m\tgroupid : %s" %(group['name'],group['groupid'])self.hostgroupID = group['groupid']return group['groupid']def template_get(self,templateName=''):data = json.dumps({"jsonrpc":"2.0","method": "template.get","params": {"output": "extend","filter": {"name":templateName}},"auth":self.user_login(),"id":1,})request = urllib2.Request(self.url, data)for key in self.header:request.add_header(key, self.header[key])try:result = urllib2.urlopen(request)except URLError as e:print "Error as ", eelse:response = json.loads(result.read())result.close()#print responseif not len(response['result']):print "\033[041m %s \033[0m is not exist" % templateNamereturn Falsefor template in response['result']:if len(templateName)==0:print "template : %s \t id : %s" % (template['name'], template['templateid'])else:self.templateID = response['result'][0]['templateid']print "Template Name :%s"%templateNamereturn response['result'][0]['templateid']def hostgroup_create(self,hostgroupName):if self.hostgroup_get(hostgroupName):print "hostgroup  \033[42m%s\033[0m is exist !" % hostgroupNamesys.exit(1)data = json.dumps({"jsonrpc": "2.0","method": "hostgroup.create","params": {"name": hostgroupName},"auth": self.user_login(),"id": 1})request=urllib2.Request(self.url,data)for key in self.header:request.add_header(key, self.header[key])try:result = urllib2.urlopen(request)except URLError as e:print "Error as ", eelse:response = json.loads(result.read())result.close()print "添加主机组:%s  hostgroupID : %s"%(hostgroupName,self.hostgroup_get(hostgroupName))def host_create(self, hostIp, hostgroupName, templateName, hostName):if self.host_get(hostName) or self.hostip_get(hostIp):print "该主机已经添加!"sys.exit(1)group_list=[]template_list=[]for i in hostgroupName.split(','):var = {}var['groupid'] = self.hostgroup_get(i)group_list.append(var)for i in templateName.split(','):var={}var['templateid']=self.template_get(i)template_list.append(var)data = json.dumps({"jsonrpc":"2.0","method":"host.create","params":{"host": hostName,"interfaces": [{"type": 1,"main": 1,"useip": 1,"ip": hostIp,"dns": "","port": "10050"}],"groups": group_list,"templates": template_list,},"auth": self.user_login(),"id":1})request = urllib2.Request(self.url, data)for key in self.header:request.add_header(key, self.header[key])try:result = urllib2.urlopen(request)response = json.loads(result.read())result.close()print "add host : %s id :%s" % (hostIp, hostName)except URLError as e:print "Error as ", eexcept KeyError as e:print "\033[041m 主机添加有误,请检查模板正确性或主机是否添加重复 !\033[0m",eprint responsedef host_disable(self,hostip):data=json.dumps({"jsonrpc": "2.0","method": "host.update","params": {"hostid": self.host_get(hostip),"status": 1},"auth": self.user_login(),"id": 1})request = urllib2.Request(self.url,data)for key in self.header:request.add_header(key, self.header[key])try:result = urllib2.urlopen(request)except URLError as e:print "Error as ", eelse:response = json.loads(result.read())result.close()print '------------主机现在状态------------'print self.host_get(hostip)def host_enable(self,hostip):data=json.dumps({"jsonrpc": "2.0","method": "host.update","params": {"hostid": self.host_get(hostip),"status": 0},"auth": self.user_login(),"id": 1})request = urllib2.Request(self.url,data)for key in self.header:request.add_header(key, self.header[key])try:result = urllib2.urlopen(request)except URLError as e:print "Error as ", eelse:response = json.loads(result.read())result.close()print '------------主机现在状态------------'print self.host_get(hostip)def host_delete(self,hostNames):hostid_list=[]for hostName in hostNames.split(','):hostid = self.host_get(hostName=hostName)if not hostid:print "主机 \033[041m %s\033[0m  删除失败 !" % hostNamesys.exit()hostid_list.append(hostid)data=json.dumps({"jsonrpc": "2.0","method": "host.delete","params": hostid_list,"auth": self.user_login(),"id": 1})request = urllib2.Request(self.url,data)for key in self.header:request.add_header(key, self.header[key])try:result = urllib2.urlopen(request)result.close()print "主机 \033[041m %s\033[0m  已经删除 !" % hostNameexcept Exception,e:print  eif __name__ == "__main__":zabbix=zabbix_api()parser=argparse.ArgumentParser(description='zabbix api ',usage='%(prog)s [options]')parser.add_argument('-H','--host',nargs='?',dest='listhost',default='host',help='查询主机')parser.add_argument('-G','--group',nargs='?',dest='listgroup',default='group',help='查询主机组')parser.add_argument('-T','--template',nargs='?',dest='listtemp',default='template',help='查询模板信息')parser.add_argument('-A','--add-group',nargs=1,dest='addgroup',help='添加主机组')parser.add_argument('-C','--add-host',dest='addhost',nargs=4,metavar=('xx.xx.xx.xx', 'groupname', 'Template01,Template02', 'hostName'),help='添加主机,多个主机组或模板使用逗号')parser.add_argument('-d','--disable',dest='disablehost',nargs='+',metavar=('sh-aa-01'),help='禁用主机,填写主机名,多个主机名之间用逗号')parser.add_argument('-e','--enable',dest='enablehost',nargs=1,metavar=('sh-aa-01'),help='开启主机')parser.add_argument('-D','--delete',dest='deletehost',nargs='+',metavar=('sh-aa-01'),help='删除主机,多个主机之间用逗号')parser.add_argument('-v','--version', action='version', version='%(prog)s 1.0')if len(sys.argv) == 1:print zabbix.host_delete('hz-aaa-02')else:args = parser.parse_args()if args.listhost != 'host':if args.listhost:zabbix.host_get(args.listhost)else:zabbix.host_get()if args.listgroup != 'group':if args.listgroup:zabbix.hostgroup_get(args.listgroup)else:zabbix.hostgroup_get()if args.listtemp != 'template':if args.listtemp:zabbix.template_get(args.listtemp)else:zabbix.template_get()if args.addgroup:zabbix.hostgroup_create(args.addgroup[0])if args.addhost:zabbix.host_create(args.addhost[0], args.addhost[1], args.addhost[2], args.addhost[3])if args.disablehost:zabbix.host_disable(args.disablehost)if args.deletehost:zabbix.host_delete(args.deletehost[0])

最后执行./start.sh

转载于:https://www.cnblogs.com/MicoYang/p/10823937.html

ansible配置zabbix自动化安装和配置相关推荐

  1. 监控系统介绍和zabbix的安装及配置

    监控系统: 监控系统是运维人员的眼睛,当监控对象发生问题时,监控系统要第一时间发出警报,警报中除了出问题的点,还可以有一些数据和简单的分析,比如当时一段时间的cpu负载等,以帮助接收到报警的人员快速定 ...

  2. zabbix客户端安装及配置

    zabbix客户端安装及配置 linux客户版本为:zabbix_agents_2.4.4.linux2_6.i386.tar.gz 为了方便大家的时间里边有zabbix的服务端与win/linux的 ...

  3. 配置suse自动化安装

    配置suse自动化安装 作者:尹正杰   版权声明:原创作品,谢绝转载!否则将追究法律责任.       前言:不知道你习惯用那款虚拟器,我用的是VMware Workstation,别问我为什么,因 ...

  4. 配置zabbix及安装agent

    一.配置zabbix http://ip/zabbix/setup.php Next step Next step 输入数据库密码后,Next step Next step 默认用户名是Admin 密 ...

  5. zabbix mysql安装配置_ZABBIX4.4 安装及配置

    环境: ZABBIX版本 4.4 OS分布 CentOS OS版本 7 数据库 MySQL WEB SERVER Apache 选择您Zabbix服务器的平台 a. 安装 数据库 # rpm -Uvh ...

  6. Zabbix的安装、配置客户端

     1.关闭防火墙 sed -i 's/SELINUX=enforcing/SELINUX=disabled/' /etc/selinux/config #关闭selinux开机自启,可使用vi命令查看 ...

  7. 无人值守安装linux指定硬盘,Linux无人值守自动化安装详细配置流程!

    在生产环境中,往往需要给成百上千台服务器安装系统,手动安装略显蛋疼,网络自动化引导安装就能解决批量安装的问题,从此批量系统安装so easy! 以下配置流程均在CentOS 6.7实现 实现环境: P ...

  8. centos7 nginx配置php7,centos7安装并配置nginx+php,centos7nginx

    centos7安装并配置nginx+php,centos7nginx centos7安装并配置nginx+php 安装nginx yum install nginx 设置nginx开启起动 syste ...

  9. 环境部署(java安装和配置,Tomcat安装和配置)(tomcat下部署war包)

    1,上传环境部署安装包到服务器上 2,解压安装包,并部署java #  tar -xf jdk-8u201-linux-x64.tar.g # mkdir /usr/java # cp  jdk1.8 ...

最新文章

  1. Android中全屏或者取消标题栏
  2. JSP URL重写-urlrewrite
  3. Foundation和Core Foundation掺杂使用桥接 Toll-Free Bridging
  4. springboot工程打包时将application.properties放在jar包外
  5. scala 方法、函数定义小结
  6. 计算机桌面程序名,深度技术win7旗舰版电脑桌面图标只显示名称了怎么办
  7. MySQL MGR集群搭建
  8. phpcms v9 数据源
  9. 小学阅读方法六种_小学数学速算六种方法
  10. OCM考试经历:注意事项
  11. 年轻人开始“反推荐算法”:算法不讲武德!
  12. mysql 6.2 安装教程_CentOS 6.2 安装 MySQL 5.7.28的教程(mysql 笔记)
  13. 遥感技术在水利行业中的应用
  14. 候选公示!高工智能汽车金球奖第二批入围年度产品/方案亮相
  15. Activiti Explorer messages 国际化文件
  16. python logging日志分割_Python3测井曲线切割,python3logging,日志
  17. Xmind8 绿色版安装教程
  18. Windows新建文件快捷键(使用AutoHotKey脚本)
  19. python制作中文词云图_Python3制作中文词云图
  20. 理解直推式学习和归纳式学习

热门文章

  1. 计算机指令称,通俗解释什么叫计算机指令?
  2. 【Pytorch神经网络理论篇】 05 Module类的使用方法+参数Parameters类+定义训练模型的步骤与方法
  3. 图像目标分割_1 概述
  4. Packet Tracer实验——使用三层交换机实现vlan间的通信(详解)
  5. Paddle 使用预训练模型 实现快递单信息抽取
  6. LeetCode 1191. K 次串联后最大子数组之和(前缀和+分类讨论)
  7. LeetCode 528. 按权重随机选择(前缀和+二分查找)
  8. LeetCode 第 30 场双周赛(477/2545,前18.7%,第2次全部通过)
  9. LeetCode 1245. 树的直径(图的最大直径结论)
  10. LeetCode 1323. 6 和 9 组成的最大数字