`

根据配置实现不同ES索引保留天数不同

    博客分类:
  • ELK
阅读更多
由于ES接入的项目变多,之前所有索引都保留30天,现在需要根据业务不同,索引保留的天数可以配置,所以写了shell命令,可以根据配置删除过期索引,配合cron执行

索引按照天进行分隔,格式统一为:xxxx_yyyy.mm.dd

#/bin/bash


ES_URL="http://127.0.0.1:9200" #填写你的es对外http连接地址
ES_USER="username" #name代表你的你的es用户名
ES_PASSWORD="password" #password代表你的es用户密码


delete_index() {
    echo -e "\nstart close and delete $1 days index"
    beforeday=$(date -d '-'$1'days' +'%Y%m%d')
    for i in `cat ./del_es_index_$1`; do
        echo -e "\nstart to detect index of $i"
        index_seq=`curl -s -u $ES_USER:$ES_PASSWORD $ES_URL/_cat/indices | awk '{print $3}' | grep "$i" | sort -n | sed -r 's/$i_(.*)/\1/'`
        for j in `echo $index_seq`;do
            indexday=`echo ${j:0-10}`
            indexFormatDate=`echo $indexday | head -n 1 | sed 's/\.//g'`
            if [[ $beforeday -ge $indexFormatDate ]]; then
                echo -e "\n$(date '+%Y-%m-%d %H:%M:%S')   es_index match successful,当前索引:\e[0;35m$j\e[0m"
                curl -XPOST -u $ES_USER:$ES_PASSWORD "$ES_URL/$j/_close"
                echo -e "$(date '+%Y-%m-%d %H:%M:%S')   索引\e[0;35m$j\e[0m, 关闭完成"
                if [[ ` echo $? ` == 0 ]];then
                    curl -XDELETE -u $ES_USER:$ES_PASSWORD "$ES_URL/$j"
                    echo -e "$(date '+%Y-%m-%d %H:%M:%S')   索引\e[0;35m$j\e[0m, 删除完成"
                else
                    echo -e "$(date '+%Y-%m-%d %H:%M:%S')   索引\e[0;35m$j\e[0m, 关闭失败,无法进行删除"
                fi
            else
                echo -e "\n$(date '+%Y-%m-%d %H:%M:%S')   es_index match fail,当前索引:\e[0;35m$j\e[0m"
                echo -e "$(date '+%Y-%m-%d %H:%M:%S')   索引\e[0;35m$j\e[0m, 没有过期,不需要关闭,over.."
            fi
        done
    done
}


delete_index 7 # 索引保留7天
delete_index 15 # 索引保留15天



在shell文件同目录放del_es_index_7,del_es_index_15两个文件,里面是需要保留7天或15天的索引名,不包括_yyyy.mm.dd,每个索引一行

如果要增加一个保留3天的配置,则新建del_es_index_3文件,并在shell里添加
delete_index 3 # 索引保留3天
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics