ES索引清理脚本-总结
之前写过一个日格式的索引清理脚本,目前所在公司用的是「周」格式清理,所以再更新一下
前言
脚本流程:通过时间匹配历史索引 -> 记录到文件 -> 按照记录文件清理
关键:因为在Filebeat 的配置文件中定义了索引的命名格式,索引我们主要按照这种格式匹配索引,然后清理
「周格式」
"%{[fields.servicename]}-%{+yyyy.ww}"
针对周的索引格式,需要定义具体xx周之前的清理目标
- 先在date 参数中找到 ,当前周属于一年中的第几周
[root@k8s-master ~]# date +%W
28
- 那xx周之前的可以这么定义
[root@k8s-svr-master ~]# CLEAR_TIME=`date -d "4 week ago" +%Y.%W`
# 这里的2022.24 是指一年中的 第24周,
[root@k8s-svr-master ~]# echo $CLEAR_TIME
2022.24
实际要清理的索引名称会是这样
xxx-xxx-2022.24
「日格式」
- index: "{[fields.servicename]}-%{+yyyy.MM.dd}"
针对这种索引格式,需要定义具体xx日之前的时间
当前日期获取)(因为索引是2022.07.17 这种格式的所以此处选择使用第二种)
[root@k8s-master ~]# date +%F
2022-07-17
或
[root@k8s-master ~]# date +%Y.%m.%d
2022.07.17
5日之前的时间可以这样取
[root@k8s-svr-master ~]# CLEAR_TIME=`date -d "5 day ago" +%Y.%m.%d`
[root@k8s-svr-master ~]# echo $CLEAR_TIME
2022.07.09
实际索引应该名称会是这样的
.monitoring-es-7-2022.07.09
一、清理脚本:ES有密码,索引按(周、日)时间命名的清理脚本
#/bin/bash
#[ES引清理脚本]
#Author: zhb | Time: 2022.07.13 12:00 | Version: v1.0
#crontab: 30 00 * * * /opt/clear_es_index/script/Clear_ES_Index.sh >> /opt/clear_es_index/clean_info.log 2>> /opt/clear_es_index/clean_error.log
# 清理xxx周前的索引
CLEAR_TIME=`date -d "4 week ago" +%Y.%W`
# 如果是日格式的索引,则将下边这行注释取消,更改日期即可使用
#CLEAR_TIME=`date -d "30 day ago" +%Y.%m.%d`
TODAY=$(date +%F-%H:%M)
ES_Clear_Dir=/opt/clear_es_index
ES_IP=<替换为实际IP或域名>
ES_PORT=<替换为实际端口>
#如果配置的有账号密码 就需要修改如下配置
ES_USER=<替换为实际用户>
ES_PASSWORD=<替换为实际密码>
#查找匹配清理日期的索引
curl -s -XGET --user $ES_USER:$ES_PASSWORD $ES_IP:$ES_PORT/_cat/indices | awk '{print $3}' | grep $CLEAR_TIME > $ES_Clear_Dir/index.$CLEAR_TIME
#开始清理(清理此处有带参数--user $ES_USER:$ES_PASSWORD,如果不需要可以去掉)
echo ">>>>>>>>>>于 $TODAY 开始清理"$CLEAR_TIME"的索引<<<<<<<<<<"
for i in `cat $ES_Clear_Dir/index.$CLEAR_TIME`
do
sleep 3
curl -s -XDELETE --user $ES_USER:$ES_PASSWORD $ES_IP:$ES_PORT/$i
done
echo ">>>>>>>>>>清理完成<<<<<<<<<<"
这里稍做解释,curl 账号密码访问 ES
可以看到上边的脚本中有一个 --user 的参数,是curl 请求时带用户密码访问ES,下边有2种方法
--user $ES_USER:$ES_PASSWORD
方法1:curl --user 用户名:密码 http://<ES的IP>:端口
方法2:添加证书(root-ca.pem)到文件 /etc/pki/tls/certs/ca-bundle.crt 【未实验】
curl -k --header "Content-Type: application/json;charset=UTF-8" --user 用户名:密码 -XPUT https://IP:9200/_template/history_dbl_template -d '{...}'
二、for循环直接手动批量删除
# 根据想删除的情况来过滤,比如很长时间以前的、大数据量等
# 同样,如果有密码需要带 --user参数
[root@k8s-node1 opt]# curl -s -XGET <ES的IP>:<ES的端口>/_cat/indices | grep 2021-* > 2021_all.index
[root@k8s-node1 opt]# for i in `cat 2021_all.index`;do curl -s -XDELETE <ES的IP>:<ES的端口>/$i;done
三、kibana 索引管理中手动删除
【索引管理】
Tips,最好在删除索引前都确认一下,索引删除之后没有备份是无法还原的哦
参考
Curl带账号密码访问ES https://blog.csdn.net/czltx224/article/details/103879323
利用Curator清理ES历史索引 https://www.cnblogs.com/nf01/articles/15480020.html
清理脚本 https://blog.csdn.net/qq_36196879/article/details/103040226?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-12.control&dist_request_id=&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-12.control