"""Factory function for creating an es client.""" import boto3 from elasticsearch import Elasticsearch from elasticsearch import RequestsHttpConnection from requests_aws4auth import AWS4Auth def create_es_client(hosts: list): """Create a new ElasticSearch client.""" username = password = creds = None if hosts[0]: username = hosts[0].get("username") password = hosts[0].get("password") if username and password: # If we have user creds, prefer these over v4 signature. creds = (username, password) return Elasticsearch( hosts=hosts, http_auth=creds or get_signature(), use_ssl=True, verify_certs=True, connection_class=RequestsHttpConnection) def get_signature(): """Get a aws auth v4 signature.""" session = boto3.session.Session() credentials = session.get_credentials() return AWS4Auth( credentials.access_key, credentials.secret_key, session.region_name, "es", session_token=credentials.token)