API Key Authentication in Elasticsearch with python
working configuration for me was :
es = Elasticsearch(['localhost:9200'], api_key=('DuSkVm8BZ5TMcIF99zOC','2rs8yN26QSC_uPr31R1KJg'))
Elasticsearch's documentation shows how to generate and use (at the bottom of the page) an API key: https://www.elastic.co/guide/en/elasticsearch/reference/current/security-api-create-api-key.html
curl -H "Authorization: ApiKey ..." http://localhost:9200/_cluster/health
-H
means "header", so to do the same in Python you will need to set this header. Rummaging through the elasticsearch module source code tells me that you might just be able to do the following:
Elasticsearch([f'http://{host}:{port}'], api_key=api_key)
The reason for this is that **kwargs
of the Elasticsearch.__init__
method are passed to Transport.__init__
, the **kwargs
of that are passed to Connection.__init__
, which takes an api_key
arg which is then used in _get_api_key_header_val
to construct the appropriate header.
The following code shows that the api key header gets added to the HTTP headers of the request:
import elasticsearch, logging, http.clienthttp.client.HTTPConnection.debuglevel = 5logging.basicConfig(level=logging.DEBUG)c = elasticsearch.Elasticsearch(['localhost'], api_key='TestApiKey')print(c.cluster.health(wait_for_status='green'))
This is definitely something that should be added to Elasticsearch's docs.