Search code examples
pythonboto3opensearch

AWS cannot connect to opensearch severless, getting error 'Session' object has no attribute 'token' using python


I am trying to create indexes on a new opensearch setup as we are going to start migrating from elasticsearch to opensearch serverless in aws. I have the configuraton below, I am able to get an aws_session_token without any issues however I am unable to actually connect to the botosession. Please let me know if there is something I am missing on either the botosession configuration or if I need to configure something for botocore?


botoclient = boto3.client('sts', region_name = region, aws_access_key_id=aws_access_key_id, aws_secret_access_key=aws_secret_access_key,verify = False)
response = botoclient.get_session_token()
aws_session_token = response["Credentials"]["SessionToken"]


session1 = boto3.Session(
    aws_access_key_id=aws_access_key_id,
    aws_secret_access_key=aws_secret_access_key,
    aws_session_token=aws_session_token
)

auth = AWSV4SignerAuth(session1, region, service)


botosession = OpenSearch(
    hosts = [{'host': host, 'port': 443}],
    http_auth = auth,
    use_ssl = True,
    verify_certs = True,
    connection_class = RequestsHttpConnection,
    pool_maxsize = 20
)


index_name = 'python-test-index'
index_body = {
  'settings': {
    'index': {
      'number_of_shards': 4
    }
  }
}

response1 = botosession.indices.create(index_name, body=index_body)
print('\nCreating index:')
print(response1)

I read the documentation on opensearch, boto, botocore, and boto.session and I made progress, however I stumped on this error message. I think it has something to do with botocore but I could be wrong. I also have limited access to aws so it is possible there is a permissioning I am missing but I do not think that is the case. I am looking to be able to create a test index on opensearch


Solution

  • The first argument to the AWSV4SignerAuth-object should be the credentials of the Session, not the Session itself.

    session1 = boto3.Session(
        aws_access_key_id=aws_access_key_id,
        aws_secret_access_key=aws_secret_access_key,
        aws_session_token=aws_session_token
    )
    session1_creds = session1.get_credentials()
    
    auth = AWSV4SignerAuth(session1_creds, region, service)
    

    This is based on the documentation from the OpenSearch-client: https://opensearch.org/docs/latest/clients/python-low-level/