Skip to content

Instantly share code, notes, and snippets.

@be-hase
Last active October 14, 2017 08:14
Show Gist options
  • Save be-hase/e97aea92abfd7749ca09 to your computer and use it in GitHub Desktop.
Save be-hase/e97aea92abfd7749ca09 to your computer and use it in GitHub Desktop.
elasticsearchのindex削除用のcron script

elasticsearchのindexを定期的にcronを使用して削除するscript。

indexにTTLを設定すればいいじゃないかという指摘もありそうですが、
公式ブログに大量のログを保存するときは、TTL設定しているとオーバーヘッドが大きいと書いてあったので、
cronで消すようにします。
http://www.elasticsearch.org/tutorials/using-elasticsearch-for-logs/

Curatorを使えばこういったことも楽にできそうではあるが、
わざわざそのためにPythonをいじるのもアレなので、簡単にシェルスクリプトで書いてみました。

#!/bin/sh

# ----------------------------------
# functions
# ----------------------------------
function detele_index
{
    local index=$1
    local ttl=$2
    local ttl_format=$3
    if [ -z $index -o -z $ttl -o -z $ttl_format ]; then
        echo "[detele_index] invalid argument." 1>&2
        exit 1
    fi

    local ttl_suffix=`get_ttl $ttl $ttl_format`
    if [ -z $ttl_suffix ]; then
        echo "[detele_index] invalid ttl_suffix." 1>&2
        exit 1
    fi

    local curl_str="curl -X DELETE http://$host_port/$index-$ttl_suffix"
    echo "execute... $curl_str"
    curl -X DELETE http://$host_port/$index-$ttl_suffix
}

function get_ttl
{
    local ttl=$1
    local ttl_format=$2
    local result=`date +"$ttl_format" --date "$ttl ago" 2>/dev/null`
    if [ -z $result ]; then
        echo "[get_ttl] invalid argument. $ttl, $ttl_format" 1>&2
        exit 1
    fi
    echo $result
}

# ----------------------------------
# main
# ----------------------------------
filepath=$1
if [ -z $filepath ]; then
    echo "Specify index_ttl_list file path. (ex) sh es-ttl.sh index_ttl_list.txt localhost:9200" 1>&2
    exit 1
fi
if [ ! -f $filepath ]; then
    echo "invalid file path : $filepath" 1>&2
    exit 1
fi

host_port=$2
if [ -z $host_port ]; then
    echo "Specify host_port. (ex) sh es-ttl.sh index_ttl_list.txt localhost:9200" 1>&2
    exit 1
fi

cat $filepath | while read LINE
do
    _LINE=`echo $LINE | sed -e 's/,/ /g'`
    COLS=($_LINE)
    index=${COLS[0]}
    ttl=${COLS[1]}
    ttl_format=${COLS[2]}

    detele_index $index $ttl $ttl_format
done

exit 0

※ BSD系ではdateコマンドの動きが違うので、多分動かないと思います。(少なくともMac OSはダメ)

動かし方は、

sh es-ttl.sh index-ttl-list.txt localhost:9200

といったように、コマンドライン引数に、indexとTTLを記載したファイルと、host&portを渡して実行します。

indexとTTLを記載したファイルは以下の様に書きます。

event,7days,%Y.%m.%d
access,7days,%Y.%m.%d

カンマ区切りで、順番にインデクッス名、保存期間、日付format。

上記の例でいえば、現在の日付が2014/09/08ならば、event-2014.09.01とaccess-2014.09.01のindexが削除される。

このscriptを一日1回実行するようにcronで設定しておけばいい。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment