通过Liunx 系统下中的crontab 命令,创建任务。调用elasticsearch的api 。实现自动删除索引。设置的shell 脚本如下:
#!/bin/bash
current_path=$(pwd)
read -p "请确定当前是root用户(Y/N):" isRootUser
if [ "$isRootUser" != "Y" ]; then
echo "请先切换至root再执行此脚本"
exit 1
fi
echo "请输入es的用户名(不输入默认为elastic):"
read esUser
if [ -z "$esUser" ]; then
esUser="elastic"
fi
echo "es的用户名:$esUser"
while true; do
echo "请输入es的用户密码:"
read esPassword
if [ -n "$esPassword" ]; then
break
fi
done
echo "es的用户密码:$esPassword"
echo "请输入es的IP地址(不输入默认为localhost):"
read esIP
if [ -z "$esIP" ]; then
esIP="localhost"
fi
echo "es的IP地址:$esIP"
echo "请输入es的端口(不输入默认为9200):"
read esPort
if [ -z "$esPort" ]; then
esPort="9200"
fi
echo "es的端口:$esPort"
while true; do
echo "请输入es索引前缀(日期前面部分,包含-符号):"
read esIndexPrefix
if [ -n "$esIndexPrefix" ]; then
break
fi
done
echo "es索引前缀:$esIndexPrefix"
echo "请输入日志保留天数(不输入默认为30天):"
read esLogKeepDay
if [ -z "$esLogKeepDay" ]; then
esLogKeepDay="30"
fi
echo "日志保留天数:$esLogKeepDay"
echo "请输入清理日志任务日志保留位置(不输入默认当前路径):"
read taskLogDir
if [ -z "$taskLogDir" ]; then
taskLogDir=$current_path
fi
echo "清理日志任务日志保留位置:$taskLogDir"
#测试es
echo "测试设置es用户、密码、网络是否正确"
response=$(curl -u $esUser:$esPassword http://$esIP:$esPort)
# 检查响应信息是否包含节点信息
if echo "$response" | grep -q "cluster_name"; then
echo "登录成功!"
else
echo "登录失败!"
read -p "是否继续(Y/N):" isContinue
if [ "$isContinue" != "Y" ]; then
exit 1
fi
fi
#创建命令文件
echo "LATS_DATE=\$(date -d '-${esLogKeepDay} day' +%Y.%m.%d)" >> $taskLogDir/clear-es-index-task.sh
echo "echo \"执行删除$esIndexPrefix\${LATS_DATE}索引,执行结果如下\" >> $taskLogDir/clear-es-index-task.log" >> $taskLogDir/clear-es-index-task.sh
echo "curl -XDELETE \"http://$esUser:$esPassword@$esIP:$esPort/$esIndexPrefix\${LATS_DATE}\" >> $taskLogDir/clear-es-index-task.log" >> $taskLogDir/clear-es-index-task.sh
#添加可执行权限
chmod +x $taskLogDir/clear-es-index-task.sh
# 创建crontab任务
(crontab -l 2>/dev/null; echo "*/3 * * * * $taskLogDir/clear-es-index-task.sh") | crontab -
#重启任务
systemctl restart cron