kibana 自动创建索引模式
kibana 自动创建索引模式由于elk 索引过多,自己手动创建索引模式会很麻烦,因此根据官方提供的API 接口编写一个自动创建索引模式的脚本官方文档接口链接: https://www.elastic.co/guide/en/kibana/current/saved-objects-api-create.html#saved-objects-api-create-example我的ELK 集群均为
·
kibana 自动创建索引模式
由于elk 索引过多,自己手动创建索引模式会很麻烦,因此根据官方提供的API 接口编写一个自动创建索引模式的脚本
官方文档接口链接: https://www.elastic.co/guide/en/kibana/current/saved-objects-api-create.html#saved-objects-api-create-example
我的ELK 集群均为7.3.0版本,单节点单机
脚本
#!/bin/bash
# 新增索引add,删除索引del 后续用$1来替换
action=add
#kibana 路径
URL="http://localhost:5601"
#新增/删除索引名存放文件
middle_file=/usr/local/kibana-7.3.0/create_index/middle.txt
#日志文件
log_file=/usr/local/kibana-7.3.0/create_index/update_index.log
#获取所有索引后存放的文件夹
index_log=/usr/local/kibana-7.3.0/create_index/index_log.txt
#获取新索引前情况上一次遗留的索引数据,避免冲突
echo "" > $middle_file
# 获取索引
curl "http://elasticsearch.915.com/_cat/indices" > $index_log
#获取更新时间
date=`date +%Y-%m`
time_field="@timestamp"
#获取最新的索引设置为默认索引
default_index=`date +%Y.%m-%Y.%V`
#记录更新时间
echo "${date}" >> ${log_file}
#整理所需索引
cat $index_log | grep access | awk '{print $3}' >> $middle_file
cat $index_log | grep errorlog | awk '{print $3}' >> $middle_file
domain_name_num=`wc -l ${middle_file} | awk '{print $1}'`
echo $domain_name_num
#开始循环创建索引
for((i=1;i<=${domain_name_num};i++));
do
echo "for循环--$i"
domain_name_type=`sed -n "${i}p" $middle_file | awk '{print $1}'`
echo "索引名称: "$domain_name_type
# 开始新增索引
if [ $domain_name_type != "" ];then
if [ $1 == "add" ];then
echo "新增索引"
curl -f -XPOST -H 'Content-Type: application/json' -H 'kbn-xsrf: anything' \
"${URL}/api/saved_objects/index-pattern/${domain_name_type}" -d"{\"attributes\":{\"title\":\"${domain_name_type}\",\"timeFieldName\":\"${time_field}\"}}" >> ${log_file}
elif [ $1 == "del" ];then
curl -XDELETE "${URL}/api/saved_objects/index-pattern/${domain_name_type}" -H 'kbn-xsrf: true'
else
echo "未知参数 $1,正确参数:新增索引--> add 删除索引--> del" >> ${log_file}
exit 100
fi
fi
# 记录日志用于监控警报,及时发现脚本错误
if [ $? -eq 0 ];then
echo "success ${domain_name_type}" >> ${log_file}
else
echo "error ${domain_name_type}" >> ${log_file}
fi
done
#添加默认索引
curl -f -XPOST -H 'Content-Type: application/json' -H 'kbn-xsrf: anything' http://localhost:5601/api/kibana/settings/defaultIndex -d "{\"value\":\"accesslog-${default_index}\"}" >> ${log_file}
注意:
需要先删除后新增,不然会重复,导致报错
其实也可以不需要那么麻烦,就好像我的索引按周划分,只需要每周定时新增当前周的索引就好,不过上面这样直接获取索引后新增索引模式会稳一些
更多推荐
已为社区贡献1条内容
所有评论(0)