定期删除ES索引

#!/bin/bash
# Filename   :  delete_es_indices.sh
# Date       :  2021/04/21
# Author     :  DingHao 
# Email      :  oct_hao@163.com 
# Crontab    :  10 00 * * 6 /bin/bash $BASE_PATH/delete_es_indices.sh >/dev/null 2>&1
# Notes      :  将脚本加入crontab中,每周六0点10分执行
# Description:  每周删除Elasticsearch X个月前的索引,索引格式示例:index-2021.04.11


check_args(){
    if [ "$#" -ne 2 ];then
        echo "Usage: $0 [ES_URL] [DEL DAYS]"
        echo "ES_URL示例: http://1.1.1.1:9200,DEL DAYS:表示要删除多少天前的索引。"
        exit 1
    fi
}


# 删除索引函数
DeleteIndices(){
    indices="$1"
    time="$(echo $indices | awk -F'-' '{print $NF}')"
    delete_time="$(date -d "-${DELETE_DAYS_AGO} day" +'%Y-%m-%d')"
   
    # 过滤时间是不是 2021.04.11 格式的,如果不是就退出函数
    if ! echo "$time" | egrep -o "[0-9]{4}\.[0-9]{2}\.[0-9]{2}" &>/dev/null;then
        return   
    fi

    # 转换为unix好时间,date识别不了2021.04.11日志,所以转换为2021-04-11
    format_time=$(date -d "$(echo $time | tr '.' '-')" +'%s')
    format_delete_time=$(date -d "$delete_time" +'%s')

    # 如果索引时间小于要删除的时间并且索引名字不是monitor开头的,则删除
    if [[ "$format_time" -lt "$format_delete_time" && ! "$indices" =~ ^monitor.* ]];then
        curl -XDELETE "$ES_IP/$indices"
    fi
}

main(){
    check_args $@
    # ES URL
    ES_IP="$1"
    # 删除多少天前的索引
    DELETE_DAYS_AGO="$2"

    curl $ES_IP/_cat/indices | awk '{print $3}' | while read line
    do
        DeleteIndices $line
    done
}

main $@

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值