1、背景
前段时间给公司新机房上的服务器部署了一套EFK日志监控系统,但过了一段时间后发现索引很多,同时也会对服务器的存储造成不小的压力,特此来编写一个定期删除索引的脚本。
2、需求分析
- 定义es主机的相关账号信息
- 定义对es命令行操作的api
- 定义过期的索引数量(保留的索引数量)
- 定义删除索引的函数
3、脚本编写
cat ES_index_delete.sh
#!/bin/bash
#description:定期删除es索引
#Author:wangkx
#date:2021/04/12
#es的主机信息
ip=192.168.155.1
port=9200
user='elastic'
pswd='elastic'
num=10 #指定保留所有的天数,也可以称为保留最近的索引的数量
#编写es操作的函数
es_cmd(){
if [ $# -ne 2 ];then
echo Parameter is not enough
exit
else
curl -u ${user}:${pswd} http://${ip}:${port}/_cat/indices?pretty | grep $1 | sort -nr > $2
index_num=$(cat $2 | wc -l)
fi
}
#获取索引system-index
#es_cmd system-2021 > ./system-index.txt
#获取索引metricbeat-index
#es_cmd metricbeat-2021 > ./metricbeat-index.txt
#获取索引switch-index
#es_cmd switch-2021 > ./switch-index.txt
#获取索引的数量
#num_system=$(cat ./system-index.txt | wc -l)
#num_metricbeat=$(cat ./metricbeat-index.txt | wc -l)
#num_switch=$(cat ./switch-index.txt | wc -l)
#编写es的delete函数
es_delete(){
curl -XDELETE -u ${user}:${pswd} http://${ip}:${port}/$1
}
#删除索引
ES_Delete(){
es_cmd $1 $2
[ $? -eq 0 ] && echo ok || exit
if [ $index_num -le ${num} ];then
echo index num is need not delete
exit
else
for index in $(cat $2 | tail -n $(expr ${
index_num} - ${
num}) | awk '{print $3}')
do
es_delete ${index}
[ $? -eq 0 ] && echo ok || echo "es_delete is failed"
done
fi
}
4、脚本验证
删除索引
source ES_index_delete.sh
ES_Delete switch-2021 switch-index.txt #switch-2021是索引名,模糊匹配得到后然后从定向为switch-index.txt文件
ES_Delete switch-2021 switch-index.txt #再次执行是为了验证脚本的健壮性
ES_Delete system-2021 system-index.txt
head上查看验证
5、crontab定时执行
01 00 * * 6 cd /u01/isi/ && source ES_index_delete.sh && ES_Delete metricbeat-2021 metricbeat-index.txt
02 00 * * 6 cd /u01/isi/ && source ES_index_delete.sh && ES_Delete system-2021 system-index.txt
03 00 * * 6 cd /u01/isi/ && source ES_index_delete.sh && ES_Delete switch-2021 switch-index.txt
都到这儿了,更多文章,详见个人微信公众号ALL In Linux,来扫一扫吧!