Keepalived 设置切换告警通知
## Keepalived 切换告警> Keepalived本身自带了一个邮箱告警功能,不过大家貌似都不用它自带的邮件配置,原因是不适用生产环境。不过个人认为主要是无法自定义告警媒介,达不到生产环境的需要。通过查询相关资料,实现了可以通过钉钉机器人来达到告警的需求,当然同个脚本稍微的改一下也可实现邮件的告警。主要配置与脚本的编写如下👇:
1. 首先需要编写告警脚本,并授予执行权限
```bash
cat /etc/keepalived/notify.sh
#!/bin/bash
# 这是一个邮件的告警脚本
contact='test@test.com'
notify() {
local mailsubject="$(hostname) to be $1, vip转移"
local 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
-----------------------------------------------------------------------------------------------------------------------------
cat /etc/keepalived/notify.sh
#!/bin/bash
# 这是一个钉钉的告警通知
notify() {
local mailsubject="$(hostname) to be $1, vip转移"
local mailbody="$(date +'%F %T'): vrrp transition, $(hostname) changed to be $1"
#echo "$mailbody" | mail -s "$mailsubject" $contact
curl 'https://oapi.dingtalk.com/robot/send?access_token=xxxxxxxxxxxxxxxxxxx' \
-H 'Content-Type: application/json' \
-d '{"msgtype": "text",
"text": {
"content": "'"测试 ${mailsubject}\n ${mailbody}"'"
}
}'
}
case $1 in
master)
notify master
;;
backup)
notify backup
;;
fault)
notify fault
;;
*)
echo "Usage: $(basename $0) {master|backup|fault}"
exit 1
;;
esac
chmod +x notify.sh
```
> 以上两个脚本区别不大,就是将发送的媒介修改了。如果使用的其他媒介,同理修改即可。
2. 修改配置文件
```bash
cat /etc/keepalived/keepalived.conf
! Configuration File for keepalived
global_defs {
router_id lvs-nginx02
}
vrrp_script chknginx
{
script "/etc/keepalived/chknginx.sh"
interval 2
weight -20
}
vrrp_instance nginx-ha {
state BACKUP
interface eth0
virtual_router_id 100
priority 90
advert_int 1
nopreempt
authentication {
auth_type PASS
auth_pass 1111
}
virtual_ipaddress {
172.23.36.248
}
track_script {
chknginx
}
#主要是添加下面这些配置,这样可以在你 keepalived 产生一个切换动作的时候,运行告警脚本。
# 配置说明依次为:
# 定义通知脚本,当前节点成为主节点时触发的脚本
# 定义通知脚本,当前节点转为备节点时触发的脚本
#
notify_master "/etc/keepalived/notify.sh master"
notify_backup "/etc/keepalived/notify.sh backup"
notify_fault "/etc/keepalived/notify.sh fault"
}
```
3. 如果是邮件的话还需要安装一下`mailx`服务,并进行配置
```bash
yum install mailx -y
cat >> /etc/mail.rc<< EOF
#set from=server@domainname.com #发件箱
#set smtp=smtp.exmail.qq.com #smtp地址,腾讯企业邮就是这个了
#set smtp-auth-user=server@domainname.com
#set smtp-auth-password=vT6K1234543XdsqV ##<--这里填的是邮箱授权码
#set smtp-auth=login
EOF
```
4. 模拟测试
```bash
# 重启 keepalived 服务,刚刚我们修改了 keepalived 配置还未重启,现在重启一下让它配置文件生效,重启的时候 也会有相对应的告警通知的,两台都需要操作哦
systemctl restart keepalived.service
```
!(https://image.98record.top/Typora/2021/07/1627034195-828.png)
!(https://image.98record.top/Typora/2021/07/1627034274-82c.png) 感谢分享
页:
[1]