当前位置: > 其它学习 > Elasticsearch >

shell实现按日期删除elk系统产生的logstash日志索引数据

时间:2019-12-27 13:46来源:linux.it.net.cn 作者:IT
分享一个简单的按日期删除elk系统产生的logstash日志索引数据的shell脚本,直接上代码:
 
#/bin/bash
#author: john li 
#created at 2017/9/15 16:00
 
if test ! -f "/var/log/elkDailyDel.log" ;then
    touch /var/log/elkDailyDel.log
fi
#请将该行当中的localhost:9200改成你自己elasticsearch服务对应的Ip及端口
indices=$(curl -s "localhost:9200/_cat/indices?v"|grep 'logstash'|awk '{print $3}') 
#可将60改成你所需要的时间段,改成40则保留最近40天的日志数据,以此类推
sixtyDaysAgo=$(date -d "$(date "+%Y%m%d") -60 days" "+%s") 
function DelOrNot(){
    if [ $(($1-$2)) -ge 0 ] ;then
        echo 1
    else
        echo 0
    fi
}
for index in ${indices}
do
    indexDate=`echo ${index}|cut -d '-' -f 2|sed 's/\./-/g'`
    indexTime=`date -d "${indexDate}" "+%s"`
    if [ `DelOrNot ${indexTime} ${sixtyDaysAgo}` -eq 0 ] ;then
    #请将下行当中的localhost:9200改成你自己elasticsearch服务对应的Ip及端口
        delResult=`curl -s -XDELETE "localhost:9200/${index}"` 
        echo "delResult is ${delResult}" >> /var/log/elkDailyDel.log
        if [ `echo ${delResult}|grep 'acknowledged'|wc -l` -eq 1 ] ;then
            echo "${index} had already been deleted!" >> /var/log/elkDailyDel.log
        else
            echo "there is something wrong happend when deleted ${index}" >> /var/log/elkDailyDel.log
        fi
    fi
done
 
在上面的shell脚本当中,首先会检测是否存在/var/log/elkDailyDel.log文件,没有的话会创建该文件。接着利用curl命令调用elasticsearch的restful api获取全部以logstash开头的索引名。此时定义了一个函数判断是否应该删除,思路是通过date命令获取60天前的时钟秒数,然后解析logstash-xxxx.xx.xx索引名后面的日期字符串将其转换成对应的时钟秒数,然后将两个时钟秒数相减判断该索引是不是60天之前产生的。如果是就调用elasticsearch的delete api将该索引删除。调用结果会打印到/var/log/elkDailyDel.log中
基本思路就是这样,配合linux的crontab命令每日定时执行,就可以实现elk系统只保留最近的60天日志数据的功能,假设该脚本名称为dailyDel.sh,放置于/usr/bin/目录下。对应linux命令如下:
 
chmod 744 /usr/bin/dailyDel.sh #确保该sh具有执行权限
crontab -e                     #进入任务编辑页面,跟vi编辑器是一样 
0 0 * * * /usr/bin/dailyDel.sh #在编辑页面里面输入该行后按 :wq保存退出即可
 
此时就全部设置完成了,这个shell就会每天的00:00:00执行一次,被删除的索引可以在/var/log/elkDailyDel.log里面看到对应的记录,也可以查看/var/log/cron看定期任务的执行情况。
 


(责任编辑:IT)
------分隔线----------------------------