keepalived 邮件通知

邮件通知需要先定义一个邮件发送的脚本,然后在虚拟IP的配置实例中添加相应的触发机制来实现当keepalived主备发生变化时进行发送邮件,以通知运维人员的目的。

实现方法

准备主机两台

server hostname ip
keepalived s1 172.20.27.10
keepalived s2 172.20.27.11

S1 节点操作

1.安装mailx

[root@s1 ~]# yum install mailx -y

2.设置发件人的配置

[root@s1 ~]# vim /etc/mail.rc
set [email protected]  
set smtp=smtp.qq.com 
set [email protected]  
set smtp-auth-password=ugfwthlnfossbiif
set smtp-auth=login
set ssl-verify=ignore

3.编写邮件通知脚本

[root@s1 ~]# vim /etc/keepalived/notify.sh 
#!/bin/bash
contact='[email protected]'
notify() {
    mailsubject="$(hostname) to be $1, vip转移"
    mailbody="$(date +'%F %T'): vrrp transition, $(hostname) changed to be $1"
    echo "$mailbody" | mail -s "$mailsubject" $contact
}
case $1 in
master)
    notify master
    ;;
backup)
    notify backup
    ;;
fault)
    notify fault
    ;;
*)
    echo "Usage: $(basename $0) {master|backup|fault}"
    exit 1
    ;;
esac

4.在配置文件中调用脚本

[root@s1 ~]# vim /etc/keepalived/keepalived.conf 

        [email protected]
   }
   notification_email_from [email protected]
   smtp_server 127.0.0.1
   smtp_connect_timeout 30
   router_id s1.mylinuxops.com
   vrrp_skip_check_adv_addr
   #vrrp_strict
   vrrp_iptables
   vrrp_garp_interval 0
   vrrp_gna_interval 0
}

vrrp_instance VI_1 {
    state MASTER
    interface ens33
    virtual_router_id 27
    priority 100
    advert_int 2
    authentication {
        auth_type PASS
        auth_pass 1111
    }
    unicast_src_ip 172.20.27.10
    unicast_peer {
    172.20.27.11
    }
    virtual_ipaddress {
        172.20.27.100 dev ens33 label ens33:0
    }
    #以下三行为调用通知脚本
    notify_master "/etc/keepalived/notify.sh master"   
    #当前节点成为主节点时触发的脚本 
    notify_backup "/etc/keepalived/notify.sh backup"
    #当前节点转为备节点时触发的脚本
    notify_fault "/etc/keepalived/notify.sh fault"
    #当前节点转为失败状态时触发的脚本
}

重启服务

[root@s1 ~]# systemctl restart keepalived

s1节点配置完毕后,s2节点也执行相同的操作。

测试

当s1节点停止服务后,s2节点而发送邮件通知
keepalived 邮件通知_第1张图片