2

When I simply run the following code, I always gets this error.

import boto3 as boto
import sys
import json



role_to_assume_arn="arn:aws:iam::xxxxxxxxxxxx:role/AWSxxxx_xxxxxxAdminaccess_xxxxx24fexxx"
role_session_name='AssumeRoleSession1'

sts_client=boto.client('sts')


assumed_role_object=sts_client.assume_role(
    RoleArn="arn:aws:iam::xxxxxxxxxxxx:role/AWSxxxx_xxxxxxAdminaccess_xxxxx24fexxx",
    RoleSessionName="Sess1",
)

creds=assumed_role_object['Credentials']

sts_assumed_role = boto3.client('sts',
    aws_access_key_id=creds['AccessKeyId'],
    aws_secret_access_key=creds['SecretAccessKey'],
    aws_session_token=creds['SessionToken'],
)

rds_client = boto.client('rds',
                         aws_access_key_id=creds['AccessKeyId'],
                         aws_secret_access_key=creds['SecretAccessKey'],
                         aws_session_token=creds['SessionToken']
                         )

I don't want to set and change the temporary session keys frequently, instead I want them to be set directly through a code like I've just written.

Am I wrong? Is there a way to set the credentials like this directly in the program or not?

Or is it mandatory to give the credentials in the "~/.aws/credentials"

1 Answer 1

5

I assume you are running this code in your local machine.

The STS client you created is expecting access key and secret access key.

You have to either configure it using credentials file or you can directly hardcode your access key and secret access key like below(Not recommended).

client = boto3.client('sts', aws_access_key_id=key, aws_secret_access_key=sec_key, region_name=region_name)

https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/guide_credentials_profiles.html

If you are running this code in EC2 instance, install boto3 and do AWS Configure. Follow the below link.

https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html

2
  • So is there no way to set the credentials directly in the program, without setting the credentials file? Commented Jan 28, 2020 at 6:39
  • You can directly hardcode the keys in program or keep them in credentials file. For additional security, you can encrypt your keys using a crypto package -> add the encrypted keys-> decrypt while creating client. If you are deploying your code in AWS, you can store your credentials in AWS Secrets Manager link Commented Jan 28, 2020 at 13:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.