Home > Software engineering >  Java's DefaultAWSCredentialsProviderChain equivalent in Boto3
Java's DefaultAWSCredentialsProviderChain equivalent in Boto3

Time:09-17

I have a service that needs to authenticate either 1. by getting the credentials from ec2 instance metadata 2. or by using sts

In java I'm using the DefaultAWSCredentialsProviderChain which works fine. Is there a equivalent in python's boto3?

At the moment if I'm connecting through ec2 metadata i'm using:

    provider = InstanceMetadataProvider(iam_role_fetcher=InstanceMetadataFetcher(timeout=1000, num_attempts=2))
    creds = provider.load()

    session = boto3.Session(
        aws_access_key_id=creds.access_key,
        aws_secret_access_key=creds.secret_key,
        aws_session_token=creds.token
    )

but if I use sts I change it to:

    sts = boto3.client('sts')
    response = sts.assume_role(
        RoleArn='aws:arn:iam::account_id:role/role-that-allows-s3-access',
        RoleSessionName='my-random-session-name',
        DurationSeconds=2000  # how many seconds these credentials will work
    )

    session = boto3.Session(
        aws_access_key_id=response['Credentials']['AccessKeyId'],
        aws_secret_access_key=response['Credentials']['SecretAccessKey'],
        aws_session_token=response['Credentials']['SessionToken']
    )

CodePudding user response:

You don't need to use InstanceMetadataProvider and explicitly set credetnails in your client. boto3 by default works like DefaultAWSCredentialsProviderChain as explained in Configuring credentials.

So if you, for example, what to use s3 on the instance, you do:

s3 = boto3.client('s3')

This will automatically get credentials from the metadata.

CodePudding user response:

sts_client = boto3.client("sts")

  • Related