Boto3 assume role with IAM user credentials

Viewed 1193

How can one assume an IAM role using IAM user credential?

import boto3

sts_client = boto3.client(
      'sts',
      aws_access_key_id=ACCESS_KEY,
      aws_secret_access_key=SECRET_KEY,
    )
)

sts_client.assume_role(RoleArn=some-role, RoleSessionName='boto3_client')

The above code for some reason produces:

An error occurred (InvalidClientTokenId) when calling the AssumeRole operation: The security token included in the request is invalid.

I have tested the aws_access_key_id and aws_secret_access_key using aws sts assume-role and I can indeed assume that role using the CLI. What am I doing wrong?

If it makes any difference, the IAM user is in the Chinese partition of AWS.

1 Answers

Setting AWS_DEFAULT_REGION (not even AWS_REGION) environment variable fixes it.

AWS_DEFAULT_REGION is not mentioned anywhere in boto3 documentation. And turns out you can pass the region to boto3.client() with region_name argument. Odd name (aws_region would be a more consistent choice), and this is not mentioned in the documention either. I hope this helps someone out someday.

Related