因elk每天产生大量的es索引,占用服务器的磁盘空间,所以编写一个脚本用来定时清理时间久的索引,可以使用crontab定时执行脚本。
#!/bin/bash
# Elasticsearch 服务器地址
ES_HOST="http://192.168.99.82:9200"
# 当前日期
CURRENT_DATE=$(date +%Y.%m.%d)
# 获取 10 天前的日期
OLD_DATE=$(date -d "-10 days" +%Y.%m.%d)
# 获取所有索引
#all_indices=$(curl -s "$ES_HOST/_cat/indices?h=index" | grep 'index-')
all_indices=$(curl -s "$ES_HOST/_cat/indices?h=index")
# 遍历所有索引
for index in $all_indices; do
# 提取索引日期
index_date=$(echo $index | grep -oE '[0-9]{4}\.[0-9]{2}\.[0-9]{2}')
# 如果索引日期比10天前的日期早,删除索引
if [[ $index_date < $OLD_DATE ]]; then
echo "Deleting index: $index"
curl -X DELETE "$ES_HOST/$index"
fi
done