파이썬3를 이용한, AWS ES 인덱싱 코드 예시

반응형

계속 업무 정리를 하다가, 나오게 되는 중간중간 코드 한줄입니다.

AWS 클라우드 네이티브 환경에서, 파이썬 런타임을 이용해,

 

  (1) ES 접근을 위한 토큰 발급

  (2) ES커넥터 생성

  (3) ES인덱싱

 

에 대한 과정을 간략히 요약한 코드입니다.

 

from requests_aws4auth import AWS4Auth
from elasticsearch import Elasticsearch, RequestsHttpConnection
import boto3 

#... 선행코드 중략

# boto3를 이용해, 본 파이썬이 기동되는 클라우드 베이스 호스트에서, ES에 접근하기 위한, 토큰을 획득합니다.
credentials = boto3.Session().get_credentials()
awsauth = AWS4Auth(
    credentials.access_key, 
    credentials.secret_key, 
    "ap-northeast-2", 
    "es", 
        session_token=credentials.token
)

# AWS 엘라스틱서치 매니지드 클러스터가 생성되어 있다고 가정하고, 그에 대한 엔드포인트를 기입합니다.
# 엘라스틱서치 커넥터를 생성하기 위한 포맷은 하기와 같습니다.
host = 'vpc-es-cloud-developer-angmond.ap-northeast-2.es.amazonaws.com'
es_connector = Elasticsearch(
    hosts = [{'host': host, 'port': 443}],
    http_auth = awsauth,
    use_ssl = True,
    verify_certs = True,
    connection_class = RequestsHttpConnection
)

# 엘라스틱서치 인덱스명을 위해, 시계열 패턴 yyyy.MM
today = datetime.today()
es_index = "k8sreport-" + str(today.year) + '.' + str(today.month)

# 무언가의_뒤죽박죽_데이터 콜렉션 루프를 돌며, 엘라스틱서치에 데이터를 인덱싱합니다.
for 아이템 in 무언가의_뒤죽박죽_데이터:
    es_connector.index(index=es_index, body=아이템)
반응형

설정

트랙백

댓글