公司的金山区云服务器是由我负责的,每一次新购买了金山区的服务器都要把这些新服务器添加到zabbix监控里,于是我就编写了一个ansible的playbook,这样以后就可以在执行playbook的时候“带薪拉屎”了。


ansible主机准备:

1)准备一个已经填写好zabbix_server同时hostname为空的zabbix_agentd.conf放在/root/路径下;

2)把新购买的机器ip地址填写到/etc/ansible/hosts里,原有的hosts要另外保存一份;

3)playbook跑完之后,具体的自定义项目比如pid、端口检查等监控项就是自己单独配置了;

4)别忘了去zabbix的web页面确认;


整个playbook如下文:

---

- hosts: all
  tasks:
        - name: 给新购买的机器安装zabbix 2.2版本(2.2.14版本)
          yum: name=zabbix22 state=latest
          yum: name=zabbix22-agent state=latest
          
        - name: 备份原来的zabbix_agentd.conf
          shell: mv /etc/zabbix/zabbix_agentd.conf /etc/zabbix/zabbix_agentd.conf-bak
          
        - name: 将控制端上的zabbix_agent.conf下发到目标机器
          copy: src=/root/zabbix_agentd.conf dest=/etc/zabbix/ owner=root group=root mode=0777
          
        - name: 对应更改Hostname
          shell: sed -i s/Hostname=/Hostname=$(hostname)/ /etc/zabbix/zabbix_agentd.conf
          notify: Start Zabbix-agent Service

  handlers:
        - name: Start Zabbix-agent Service
          service: name=zabbix-agent start=restarted


执行之后,会有一个提示,如图:

wKiom1foxBjgjALdAAAYp_w56a0036.png

ansible提示,最好使用template或者lineinfile模块,而不要用sed命令。


既然ansible这么说,那咱们就用呗,而且再把上面的语言整理一下。如下文:

---

- hosts: all
  tasks:
        - name: 给新购买的机器安装zabbix 2.4版本
          yum: name={{ item }} state=latest
          with_items:
          - zabbix24
          - zabbix24-agent

        - name: 备份原来的zabbix_agentd.conf
          shell: mv /etc/zabbix/zabbix_agentd.conf /etc/zabbix/zabbix_agentd.conf-bak

        - name: 将控制端上的zabbix_agent.conf下发到目标机器
          copy: src=/root/zabbix_agentd.conf dest=/etc/zabbix/ owner=root group=root mode=0777

        - name: 在新的zabbix_agent.conf添加Hostname
          lineinfile: dest=/etc/zabbix/zabbix_agentd.conf regexp=^Hostname line=Hostname=`ansible_nodename` 
          notify: Start Zabbix-agent Service

  handlers:
        - name: Start Zabbix-agent Service
          service: name=zabbix-agent start=retarted


多说一下lineinfile模块,lineinfile模块具备“文件备份、语句替换、语句删除、新语句插入”功能。其格式是:

lineinfile: dest=目标文件绝对路径  具体内容

其中具体内容可以是以下几项:

1)backup=yes,将原来的dest文件备份,默认是No;

2)regexp= ,接正则表达式,本文用的是“^Hostname”,即匹配以Hostname开头的行;

3)state= ,不单独写出来的话,默认是present,如果是state=absent,就是把regexp= 满足的语句删除;

4)line="要插入的话",如果前面没有regexp匹配出来的语句,那么默认是把“要插入的话”插入到文件最后一行。