一键初始化zabbix

该文档展示了如何使用Ansible剧本自动化安装和配置CentOS及Ubuntu系统的Zabbix Agent,并通过Python脚本来管理Zabbix主机。剧本涵盖了安装Zabbix发布源、更新包、安装Agent、配置Agent参数以及启动和启用服务。Python脚本则用于验证IP地址有效性、获取Zabbix API token,并根据输入的参数创建和配置Zabbix主机。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

centos

---
  - hosts: zabbix
    gather_facts: no
    user: root
    #become: yes
    #become_user: root
    #become_method: sudo
    vars:
      addres: zabbix
    tasks: 
       - name: install zabbix-release
         yum:
           name: https://repo.zabbix.com/zabbix/5.0/rhel/7/x86_64/zabbix-release-5.0-1.el7.noarch.rpm
           state: present
       
       - name: yum clean all
         shell: yum clean all

       - name: install zabbix-agent
         yum:
           name: zabbix-agent
           state: present

       - name: "set zabbix config LogFileSize"
         replace:
           dest: /etc/zabbix/zabbix_agentd.conf
           regexp: ^LogFileSize=.*
           replace: LogFileSize=5
           backup: yes
       - name: "set zabbix config Server"
         replace:
           dest: /etc/zabbix/zabbix_agentd.conf
           regexp: ^Server=.*
           replace: Server=172.63.251.123
           backup: yes
       - name: "set zabbix config ServerActive"
         replace:
           dest: /etc/zabbix/zabbix_agentd.conf
           regexp: ^ServerActive=.*
           replace: ServerActive=172.63.251.123
           backup: yes
       - name: "set zabbix config Hostname"
         replace:
           dest: /etc/zabbix/zabbix_agentd.conf
           regexp: ^Hostname=.*
           replace: Hostname={{addres}}
           backup: yes

       - name: enable zabbix-agent
         shell: systemctl enable zabbix-agent.service && systemctl restart zabbix-agent.service

ubuntu

---
  - hosts: "{{host}}"
    gather_facts: no
    user: ubuntu
    become: yes
    become_user: root
    become_method: sudo
    vars:
      addres: "{{host}}"
    tasks: 
       - name: get zabbix-release
         get_url:
           url: https://repo.zabbix.com/zabbix/4.4/ubuntu/pool/main/z/zabbix-release/zabbix-release_4.4-1+bionic_all.deb
           dest: "/tmp/"
           validate_certs: no

       - name: install zabbix-release
         shell: dpkg -i /tmp/zabbix-release_4.4-1+bionic_all.deb

       #- name: install zabbix-release
       #  yum:
       #    name: https://repo.zabbix.com/zabbix/4.4/ubuntu/pool/main/z/zabbix-release/zabbix-release_4.4-1+bionic_all.deb 
       #    state: present

       - name: apt update
         shell: apt update

       - name: install zabbix-agent
         yum:
           name: zabbix-agent
           state: present

       - name: "set zabbix config LogFileSize"
         replace:
           dest: /etc/zabbix/zabbix_agentd.conf
           regexp: ^LogFileSize=.*
           replace: LogFileSize=5
           backup: yes
       - name: "set zabbix config Server"
         replace:
           dest: /etc/zabbix/zabbix_agentd.conf
           regexp: ^Server=.*
           replace: Server=172.31.28.173
           backup: yes
       - name: "set zabbix config ServerActive"
         replace:
           dest: /etc/zabbix/zabbix_agentd.conf
           regexp: ^ServerActive=.*
           replace: ServerActive=172.31.28.173
           backup: yes
       - name: "set zabbix config Hostname"
         replace:
           dest: /etc/zabbix/zabbix_agentd.conf
           regexp: ^Hostname=.*
           replace: Hostname={{addres}}
           backup: yes

       - name: enable zabbix-agent
         shell: systemctl enable zabbix-agent.service && systemctl restart zabbix-agent.service

执行python脚本

---
  - hosts: "{{host}}"
    gather_facts: no
    user: ubuntu
    become: yes
    become_user: root
    become_method: sudo
    vars:
      addres: "{{host}}"
    tasks: 
       - name: get zabbix-release
         get_url:
           url: https://repo.zabbix.com/zabbix/4.4/ubuntu/pool/main/z/zabbix-release/zabbix-release_4.4-1+bionic_all.deb
           dest: "/tmp/"
           validate_certs: no

       - name: install zabbix-release
         shell: dpkg -i /tmp/zabbix-release_4.4-1+bionic_all.deb

       #- name: install zabbix-release
       #  yum:
       #    name: https://repo.zabbix.com/zabbix/4.4/ubuntu/pool/main/z/zabbix-release/zabbix-release_4.4-1+bionic_all.deb 
       #    state: present

       - name: apt update
         shell: apt update

       - name: install zabbix-agent
         yum:
           name: zabbix-agent
           state: present

       - name: "set zabbix config LogFileSize"
         replace:
           dest: /etc/zabbix/zabbix_agentd.conf
           regexp: ^LogFileSize=.*
           replace: LogFileSize=5
           backup: yes
       - name: "set zabbix config Server"
         replace:
           dest: /etc/zabbix/zabbix_agentd.conf
           regexp: ^Server=.*
           replace: Server=172.31.28.173
           backup: yes
       - name: "set zabbix config ServerActive"
         replace:
           dest: /etc/zabbix/zabbix_agentd.conf
           regexp: ^ServerActive=.*
           replace: ServerActive=172.31.28.173
           backup: yes
       - name: "set zabbix config Hostname"
         replace:
           dest: /etc/zabbix/zabbix_agentd.conf
           regexp: ^Hostname=.*
           replace: Hostname={{addres}}
           backup: yes

       - name: enable zabbix-agent
         shell: systemctl enable zabbix-agent.service && systemctl restart zabbix-agent.service
       
 
[root@ip-172-63-251-171 ~]# cat  /root/ops/play/addZabbixHost.py
from urllib import request
import json
import argparse
import re

parser = argparse.ArgumentParser()
parser.add_argument("host", help="Add host IP", default=None)
parser.add_argument("name", help="Add host Name", default=None)
parser.add_argument("--env",help="Add host Env",default=False,type=bool)
opt = parser.parse_args()

def checkIP(opt):
    compile_ip = re.compile(
        '^((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)$')
    if compile_ip.match(opt.host):
        if len(opt.name) > 4:
            return True
        else:
            return False
    else:
        return False

def requestJson(post_data):
    url = 'http://172.31.28.173:8099/zabbix/api_jsonrpc.php'
    post_header = {'Content-Type': 'application/json'}
    retset = request.Request(url, headers=post_header, data=bytes(
        json.dumps(post_data), encoding="utf8"))
    response = request.urlopen(retset)
    resulte = json.loads(response.read())
    return resulte


def get_token():
    post_data = {
        "jsonrpc": "2.0",
        "method": "user.login",
        "params": {
            "user": "Admin",
            "password": "huke@MJ6ShI5XWQ"
        },
        "id": 1
    }
    resulte = requestJson(post_data)
    return resulte["result"]

def get_groups(token):
    post_data = {
        "jsonrpc": "2.0",
        "method": "hostgroup.get",
        "params": {
            "output": ["groupid", "name"],
        },
        'auth': "{}".format(token),
        'id':  '1'
    }
    resulte = requestJson(post_data)
    return resulte["result"]


def get_hosts(token):
    post_data = {
        "jsonrpc": "2.0",
        "method": "host.get",
        "params": {
            "output": ["groupid", "name"],
            "groupids": 15,
        },
        'auth': token,
        'id':  '1'
    }
    resulte = requestJson(post_data)
    return resulte["result"]


def get_host_item(token, id):
    post_data = {
        "jsonrpc": "2.0",
        "method": "item.get",
        "params": {
            "output": ["itemids",  "key_"],
            "hostids": id,
        },
        'auth': token,
        'id':  '1'
    }
    resulte = requestJson(post_data)
    return resulte["result"]


def get_template(token):
    post_data = {
        "jsonrpc": "2.0",
        "method": "template.get",
        "params": {
            "output": ["templateid", "name"],
        },
        'auth': "{}".format(token),
        'id':  '1'
    }
    resulte = requestJson(post_data)
    return resulte["result"]


# print(get_template(token))

def add_hosts(token, hosts, name, groups=[16]):
    post_data = {
        "jsonrpc": "2.0",
        "method": "host.create",  # 定义方法为创建主机
        "params": {
            "host": "{}".format(hosts),  # 此名称需要与agent配置文件中的hostname一致
            "name": "{}".format(name),  # 指定主机的可见名称
            "interfaces": [
                    {
                        "type": 1,  # 类型为1表示agent,2是SNMP,3是IMPI,4是JMX
                        "main": 1,  # 主要接口
                        "useip": 1,  # 0是使用DNS,1是使用IP地址
                        # 添加的zabbix agent的IP地址
                        "ip": "{}".format(hosts),
                        "dns": "",
                        "port": "10050"  # agent端口
                    }
            ],
            "groups": [
                {
                    "groupid": "1"  # 添加到的组的ID    测试:1 2 16,线上:1 2 15 17
                },
                {
                    "groupid": "2"
                }
            ],
            "templates": [
                {
                    "templateid": "10001"
                    # 关联的模板的ID;如果指定的ID的模板,也链接了别的模板,则新创建的主机也相当于关联了多个模板;如果一个模板链接了多个模板,则模板ID指向最初的基础模板ID即可
                },
                {
                    "templateid": "10309"
                }
            ]
        },
        "auth": "{}".format(token),
        "id": 1
    }
    for group in groups:
        post_data["params"]["groups"].append({"groupid": str(group)})
    # print(post_data)
    resulte = requestJson(post_data)
    return resulte


if checkIP(opt):
    token = get_token()
    group = [15,17] if opt.env else [16]
    res = add_hosts(token, opt.host, opt.name,group)
    print(res)
    if "error" in res.keys():
        print("====="*3,"error","====="*3)
        print(res['error'])
        exit(1)
    else:
        print("====="*3,"success","====="*3)
        print(res['result'])
        exit(0)
else:
    print("IP Error")
    exit(1)

执行命令
python3 /root/ops/play/addZabbixHost.py ${host} name−−env={name} --env=nameenv={isOnline}(True/False)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

yunson_Liu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值