Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Connecting Django/Haystack to AWS ElasticSearch using IAM rotating credentials
import boto3
import os
import requests
from botocore.auth import SigV4Auth
from requests_aws4auth import AWS4Auth
from elasticsearch import RequestsHttpConnection
class AWSRequestsHttpConnection(RequestsHttpConnection):
def perform_request(self, *args, **kwargs):
credentials = boto3.session.Session().get_credentials()
signed_creds = SigV4Auth(credentials, 'es', os.environ['AWS__REGION'])
secure_auth = AWS4Auth(
credentials.access_key, credentials.secret_key,
os.environ['AWS__REGION'], 'es',
session_token = signed_creds.credentials.token
)
self.session.auth = secure_auth
return super(AWSRequestsHttpConnection, self).perform_request(*args, **kwargs)
requests_aws4auth
boto3
from boto_auth_requests import AWSRequestsHttpConnection
from urllib.parse import urlparse
es = urlparse(os.environ.get('AWS_ELASTICSEARCH_URL') or 'http://127.0.0.1:9200/')
es_index_name = os.environ.get('AWS_ELASTICSEARCH_INDEX_NAME', ("I_FORGOT_TO_SET_AN_INDEX__%s" % random_string(15)))
port = es.port or 80
HAYSTACK_CONNECTIONS = {
'default': {
'ENGINE': 'haystack_elasticsearch.elasticsearch5.Elasticsearch5SearchEngine',
'URL': es.scheme + '://' + es.hostname + ':' + str(port),
'INCLUDE_SPELLING': True,
'INDEX_NAME': 'haystack',
'TIMEOUT' : 60 ,
'KWARGS': {
'port': port,
'use_ssl': True,
'verify_certs': True,
'connection_class': AWSRequestsHttpConnection,
}
},
}
@daxaxelrod

This comment has been minimized.

Copy link

@daxaxelrod daxaxelrod commented Mar 4, 2021

I_FORGOT_TO_SET_AN_INDEX__ lol

Thanks for this!

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