
Logstashデータですべてのストレージを埋めるのを防ぐために、Elasticsearchクラスタのインデックスを削除する小さなスクリプトを作成しています。
レコードのリストがあり、最新のnレコード(たとえば7つ)を保持し、他のすべてのレコードを削除したいと思います。
カールを使用してインデックスのリストを取得できます。
drakaris:~/ # curl -sL localhost:9200/_cat/indices/logstash-* | awk '{print $3;}' | sort
logstash-2022.12.30
logstash-2022.12.31
logstash-2023.01.01
logstash-2023.01.02
logstash-2023.01.03
logstash-2023.01.04
logstash-2023.01.05
logstash-2023.01.06
logstash-2023.01.07
logstash-2023.01.08
logstash-2023.01.09
私のスクリプトでは、最新の7番目のインデックスだけを保持し、 "curl -XDELETE localhost:9200 / index"を使用したいと思います。
Bashの配列からこれらのレコードをどのように取得できますか?
ありがとう
[編集] 誰かが役に立つと思う場合に備えてこの方法で解決しました。
RETENTION=7
nbk=$(curl -sL localhost:9200/_cat/indices/logstash-* | awk '{print $3;}' | wc -l)
if [ $nbk -gt $RETENTION ]; then
echo -e "======== Delete obsolete indexes (retention: $RETENTION)"
let ntodel=$nbk-$RETENTION
for efile in $(curl -sL localhost:9200/_cat/indices/logstash-* | awk '{print $3;}' | sort -r | /usr/bin/tail -$ntodel); do
curl -XDELETE localhost:9200/$efile
sleep 10
done
fi
答え1
これは簡単なはずです。これを試してみてください(テストされていません!)
drakaris:~/ # curl -sL localhost:9200/_cat/indices/logstash-* | awk '{print $3;}' | sort | tail -n +8
logstash-2022.12.30
logstash-2022.12.31
logstash-2023.01.01
logstash-2023.01.02
必要なものを取得するために、head
またはここを使用して各エンドポイントに対してエンドポイントを呼び出すなどのものをパイプできます。tail
xargs curl...
DELETE
とのマンページを確認し、head
コマンドtail
の使い方をメモしてください。+
答え2
Bashでは、リストを配列にマップできます。パイプ/サブシェルは変数を返さないため、readarray
プロセスの置き換えに(またはエイリアス)を使用します。mapfile
readarray -t indexes < <(curl -sL localhost:9200/_cat/indices/logstash-* | awk '{print $3;}' | sort)
# now iterate the array, except the last 7 entries
# (if the array size is < 7, the loop would not enter)
for (( i=0; i < (${#indexes[*]}-7); i++ )); do
# delete unwanted indexes
curl ... ${indexes[$i]}
done