Ansible playbook批量安装zabbix agent

自动化工具大家都有自己的选择,有人喜欢slatstack,有人喜欢puppet,我选择ansible,原因有两条,简单的同时适合我的环境。没有最好的工具只有最适合你自己的工具。使用ansible就是为了解决很多简单而需要频繁执行的任务,我现在的环境中的zabbix 监控的agent和插件就有这样的特性,每次新机器上线需要在机器上部署zabbix agent,手工一台台的安装实在是费时,同时也容易出现问题,当然解决这样的问题最好的方式是自己做一套PXE的部署系统,打好自己的镜像,但是目前我们的环境中还没有做,所以就用ansible来代劳了。
通过ansible 的play 写好安装脚本之后推到各个新节点上,之后再通过zabbix 的discover功能实现zabbix server 自动添加监控节点。这样就会省去当了的手动工作,也就相当于ansible+zabbix disable 配合实现了zabbix 节点添加全自动化的功能,别的不说了,先上代码。

#server 是个变量,执行ansible-playbook 的时候需要加上 -e “server=xxx” 这个是指你在ansible host 定义的组

  • hosts: "{{ server }}"
    vars:
    zabbix_agent_ip: "{{ ansible_em1['ipv4']['address'] }}"
    zabbix_server_ip: xxx.xxx.xxx.xxx
    remote_user: root
    tasks:
    #当系统为 centos 7 的时候安装centos 7 的rpm 包
  • name: Install zabbix rpm source when OS version eq 7
    shell: "rpm -ivh http://repo.zabbix.com/zabbix/3.4/rhel/7/x86_64/zabbix-release-3.4-2.el7.noarch.rpm"
    when: ansible_distribution == "CentOS" and ansible_distribution_major_version == "7"
    #当系统为centos 6 的时候安装centos 6的rpm 包
  • name: Install zabbix rpm source when OS version eq 6
    shell: "rpm -ivh http://repo.zabbix.com/zabbix/3.4/rhel/6/x86_64/zabbix-release-3.4-1.el6.noarch.rpm"
    when: ansible_distribution == "CentOS" and ansible_distribution_major_version == "6"
    安装zabbix agent
  • name: Install zabbix agent
    shell: "yum -y install zabbix-agent"
    #通过变量替换默认配置中的zabbix server地址
  • name: modify zabbix server ip address
    shell: "sed -i 's#Server=127.0.0.1#Server='{{zabbix_server_ip}}'#g' /etc/zabbix/zabbix_agentd.conf"
  • name: modify zabbix server active ip addr
    shell: "sed -i 's/ServerActive=127.0.0.1/ServerActive='{{zabbix_server_ip}}'/g' /etc/zabbix/zabbix_agentd.conf"
    #开启远程执行命令功能,这个功能是zabbix
  • name: Enable remote command execution
    shell: "sed -i 's/# EnableRemoteCommands=0/EnableRemoteCommands=1'/g /etc/zabbix/zabbix_agentd.conf"
  • name: Enable remote command logs
    shell: "sed -i 's/# LogRemoteCommands=0/LogRemoteCommands=1'/g /etc/zabbix/zabbix_agentd.conf"
    #引用变量zabbix_agent_ip 设置agent hostname
  • name: modify zabbix agent hostname
    shell: "sed -i 's/Hostname=Zabbix server/Hostname='{{zabbix_agent_ip}}'/g' /etc/zabbix/zabbix_agentd.conf"
    #启动agent 同时加入开机启动项
  • service: name=zabbix-agent enabled=yes state=started

猜你喜欢

转载自blog.51cto.com/seekerwolf/2306927