ni3
ni3

Reputation: 53

How to I access Security token for Python SDK boto3

I want to access AWS comprehend api from python script. Not getting any leads of how do I remove this error. One thing I know that I have to get session security token.

try:
  client = boto3.client(service_name='comprehend', region_name='us-east-1', aws_access_key_id='KEY ID', aws_secret_access_key= 'ACCESS KEY')
  text = "It is raining today in Seattle"
  print('Calling DetectEntities')
  print(json.dumps(client.detect_entities(Text=text, LanguageCode='en'), sort_keys=True, indent=4))
  print('End of DetectEntities\n')

except ClientError as e:
  print (e)

Error : An error occurred (UnrecognizedClientException) when calling the DetectEntities operation: The security token included in the request is invalid.

Upvotes: 3

Views: 6863

Answers (3)

gotit
gotit

Reputation: 727

Create a profile using aws configure or updating ~/.aws/config. If you only have one profile to work with = default, you can omit profile_name parameter from Session() invocation (see example below). Then create AWS service specific client using the session object. Example;

import boto3
session = boto3.session.Session(profile_name="test")
ec2_client = session.client('ec2')
ec2_client.describe_instances()
ec2_resource = session.resource(‘ec2’)

Upvotes: 1

congbaoguier
congbaoguier

Reputation: 1045

One useful tool I use daily is this: https://github.com/atward/aws-profile/blob/master/aws-profile

This makes assuming role so much easier!

After you set up your access key in .aws/credentials and your .aws/config

you can do something like:

AWS_PROFILE=**you-profile** aws-profile [python x.py]

The part in [] can be substituted with anything that you want to use AWS credentials. e.g., terraform plan

Essentially, this utility simply put your AWS credentials into os environment variables. Then in your boto script, you don't need to worry about setting aws_access_key_id and etc..

Upvotes: 0

John Rotenstein
John Rotenstein

Reputation: 270174

This error suggesting that you have provided invalid credentials.

It is also worth nothing that you should never put credentials inside your source code. This can lead to potential security problems if other people obtain access to the source code.

There are several ways to provide valid credentials to an application that uses an AWS SDK (such as boto3).

If the application is running on an Amazon EC2 instance, assign an IAM Role to the instance. This will automatically provide credentials that can be retrieved by boto3.

If you are running the application on your own computer, store credentials in the .aws/credentials file. The easiest way to create this file is with the aws configure command.

See: Credentials — Boto 3 documentation

Upvotes: 1

Related Questions