Curator を使って elasticsearch に何かする [cloudpack OSAKA blog]
ナスです。
先日、こんな記事を書きました。
nasrinjp1.hatenablog.com
この中で、Curator の Amazon ES のサポートが微妙って書いたんですが、でもやっぱり楽したいですし、あるものはパクろうの精神で実際に試してみました。
インストール
今回は自分の mac に入れてみました。pip で入れるので、環境が変わっても手順は同じです。バージョン4は Amazon ES のサポートが No となっていたので、3 の最新を入れました。
$ pip install 'elasticsearch-curator<4.0' Collecting elasticsearch-curator<4.0 Downloading elasticsearch_curator-3.5.1-py2.py3-none-any.whl (47kB) 100% |████████████████████████████████| 51kB 1.5MB/s Collecting elasticsearch<3.0.0,>=2.3.0 (from elasticsearch-curator<4.0) Downloading elasticsearch-2.4.1-py2.py3-none-any.whl (55kB) 100% |████████████████████████████████| 61kB 2.8MB/s Collecting click>=3.3 (from elasticsearch-curator<4.0) Downloading click-6.7-py2.py3-none-any.whl (71kB) 100% |████████████████████████████████| 71kB 2.0MB/s Requirement already satisfied: urllib3<2.0,>=1.8 in /Library/Python/2.7/site-packages (from elasticsearch<3.0.0,>=2.3.0->elasticsearch-curator<4.0) Installing collected packages: elasticsearch, click, elasticsearch-curator Found existing installation: elasticsearch 5.3.0 Uninstalling elasticsearch-5.3.0: Successfully uninstalled elasticsearch-5.3.0 Successfully installed click-6.7 elasticsearch-2.4.1 elasticsearch-curator-3.5.1 $ curator --version curator, version 3.5.1
インデックス一覧取得
インデックス一覧を取ってみました。この例は、作成されてから 1 日以上経過したインデックスだけを取ります。1 個しか作ってないので、一覧と言っても 1 個だけ表示されてます。
$ curator --host search-domainname-hogehoge.ap-northeast-1.es.amazonaws.com --port 80 --debug show indices --older-than 1 --time-unit days --timestring %Y.%m.%d 2017-04-05 10:11:04,901 INFO Job starting: show indices 2017-04-05 10:11:05,046 INFO Action show will be performed on the following indices: [u'cwl-test-2017.04.01'] 2017-04-05 10:11:05,046 INFO Matching indices: cwl-test-2017.04.01
–debug をつけると詳細が見れます。なんか WARNING が出てますが、/cluster/state/metadata へのアクセスは AWS から許可されていないので、これが出ています。いろいろやってみてわかったんですが、どんな操作をしても、Curator は /cluster/state/metadata にアクセスしています。たぶんどうにもなりません。
2017-04-05 10:52:45,008 WARNING elasticsearch log_request_fail:88 GET /_cluster/state/metadata/cwl-test-2017.04.01 [status:401 request:0.030s]
■サポートされるオペレーション docs.aws.amazon.com
インデックスの close
closeは、削除はしないけど検索対象から外す(隠す)ってことっぽいです。
www.elastic.co
で、試してみたんですが、なんかエラー出ました。
$ curator --host search-domainname-hogehoge.ap-northeast-1.es.amazonaws.com --port 80 close indices --older-than 1 --time-unit days --timestring %Y.%m.%d Error closing indices. Run with --debug flag and/or check Elasticsearch logs for more information.
–debug つけてやってみると、エラーの原因が出ました。単に AWS が /_close に対するアクセスを許可してなかっただけでした。サポートされるオペレーションの中にも確かになかったです。
2017-04-05 10:15:41,716 WARNING elasticsearch log_request_fail:88 POST /cwl-test-2017.04.01/_close?ignore_unavailable=true [status:401 request:0.030s] 2017-04-05 10:15:41,716 DEBUG elasticsearch log_request_fail:99 < {"Message":"Your request: '/cwl-test-2017.04.01/_close' is not allowed by Amazon Elasticsearch Service."}
インデックス削除
インデックスの削除は問題なくできました。
$ curator --host search-domainname-hogehoge.ap-northeast-1.es.amazonaws.com --port 80 --debug delete indices --older-than 1 --time-unit days --timestring %Y.%m.%d 2017-04-05 10:20:41,340 INFO Job starting: delete indices 2017-04-05 10:20:41,451 INFO Pruning Kibana-related indices to prevent accidental deletion. 2017-04-05 10:20:41,451 INFO Action delete will be performed on the following indices: [u'cwl-test-2017.04.01'] 2017-04-05 10:20:41,520 INFO Deleting indices as a batch operation: 2017-04-05 10:20:41,520 INFO ---deleting index cwl-test-2017.04.01 2017-04-05 10:20:41,600 INFO Job completed successfully.
というわけで、インデックスのハウスキープ処理をするだけなら Curator を使えば ok ってことですね。次に機会があったら使ってみようと思います。
Lambda から elasticsearch service に何かする [cloudpack OSAKA blog]
ナスです。
elasticsearch service (ES) 2.3 の古くなったインデックスを削除することにしたんですが、完成までわりと苦労したので書きます。
まずは ES への接続
通常、ES へは curl で操作するんですが、この curl に AWS の認証情報をつけることができません。(いや、できるかもしれんけどわからない
今回は、Python で ES に接続します。elasticsearch モジュールがあったので、これも使います。
Python Elasticsearch Client — Elasticsearch 5.2.0 documentation
AWS 認証情報を作るところは、この aws4auth を使います。 pypi.python.org
ES 側は、アクセスポリシーで特定の IAM ロールからのみアクセス許可するようにしています。
{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "AWS": "arn:aws:iam::123456789012:role/rolename" }, "Action": "es:*", "Resource": "arn:aws:es:ap-northeast-1:123456789012:domain/domainname/*" } ] }
あとは、Lambda から ES へ接続するだけです。今回は下記のサンプルからほぼパクリました。本当にありがとうございます! docs.aws.amazon.com blog.youyo.info
接続できたらやりたいことを実装
テスト的に 1 週間経ったインデックスは削除するように作りました。作ったのがこれ↓
インデックス名に年月日が含まれていたので、この文字列から何日経過したかを判定しました。普段コードはあまり書かないので、変数名がもう一つかもしれません…
# -*- coding: utf-8 -*- from elasticsearch import Elasticsearch, RequestsHttpConnection from requests_aws4auth import AWS4Auth import requests import json, os import boto3 import datetime region = 'ap-northeast-1' es_endpoint = 'search-domainname-hogehoge.ap-northeast-1.es.amazonaws.com' role_name = 'rolename' def lambda_handler(event, context): es = connect_to_es() for key in (es.indices.get_alias()).keys(): datename=key.split("-") pastdate=datetime.datetime.strptime(datename[len(datename)-1], '%Y.%m.%d') today=datetime.datetime.now() delta=(today-pastdate).days print(str(delta) + ' days has passed since index ' + key + ' was created.') if delta > 7 and es.indices.exists(index=key): if es.indices.delete(index=key): print('[INFO] Index ' + key + ' was deleted successfully.') else: print("[ERROR] Index " + key + " couldn't be deleted.") def connect_to_es(): credentials = get_credential() awsauth = AWS4Auth( credentials['access_key'], credentials['secret_key'], region, 'es', session_token=credentials['token'] ) es = Elasticsearch( hosts=[{'host': es_endpoint, 'port': 443}], http_auth=awsauth, use_ssl=True, verify_certs=True, connection_class=RequestsHttpConnection ) return es def get_credential(): sts_client = boto3.client('sts') assumedRoleObject = sts_client.assume_role( RoleArn="arn:aws:iam::123456789012:role/rolename", RoleSessionName="Access_to_ES_from_lambda" ) credentials = assumedRoleObject['Credentials'] return { 'access_key': credentials['AccessKeyId'], 'secret_key': credentials['SecretAccessKey'], 'token': credentials['SessionToken'] }
今まで curl で取ってきた JSON からデータ取り出していろいろして、ってやってたのが、elasticsearch モジュールに変えただけでむちゃくちゃシンプルなコードになりました!
本当は、Curator ってのを使って楽をしたかったのですが、Amazon ES のサポートが微妙だったので、今回はやめました。そのうち普通に使えるようになると信じてます。 github.com
ここまでたどり着くのに 1 週間弱もかかってしまったけど、これでもう困らないだろう。