#!/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 $@
定期删除ES索引
最新推荐文章于 2024-04-29 23:25:26 发布