-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathcreate_client.py
More file actions
59 lines (48 loc) · 2.07 KB
/
create_client.py
File metadata and controls
59 lines (48 loc) · 2.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import os
from dotenv import load_dotenv
import certifi
import boto3
from opensearchpy import OpenSearch, RequestsHttpConnection, AWSV4SignerAuth
'''
This function creates an OpenSearch client. If the environment variables OPENSEARCH_HOST if OPENSEARCH_PORT are not
set, an error is raised. If the host is set to 'localhost', the client is created with basic authentication. Otherwise,
the client is created with AWS request signing. The function returns the OpenSearch client.
All code that depends on whether we are connecting to a local or production OpenSearch instance is inside of this function.
Outside of the function, interaction with the client is the same regardless of the environment.
'''
def create_client():
load_dotenv()
host = os.getenv('OPENSEARCH_HOST')
port = os.getenv('OPENSEARCH_PORT')
region = 'us-east-1'
if host is None or port is None:
raise ValueError('Please set the environment variables OPENSEARCH_HOST and OPENSEARCH_PORT')
if host == 'localhost':
auth = ('admin', os.getenv('OPENSEARCH_INITIAL_PASSWORD'))
ca_certs_path = certifi.where()
# Create the client with SSL/TLS enabled, but hostname verification disabled.
client = OpenSearch(
hosts = [{'host': host, 'port': port}],
http_compress = True, # enables gzip compression for request bodies
http_auth = auth,
use_ssl = True,
verify_certs = False,
ssl_assert_hostname = False,
ssl_show_warn = False,
ca_certs = ca_certs_path
)
return client
service = 'aoss'
credentials = boto3.Session().get_credentials()
auth = AWSV4SignerAuth(credentials, region, service)
# Create the client using AWS request signing
client = OpenSearch(
hosts=[{'host': host, 'port': port}],
http_compress = True, # enables gzip compression for request bodies
http_auth=auth,
use_ssl=True,
verify_certs=True,
connection_class=RequestsHttpConnection,
pool_maxsize=20,
)
return client