For endpoint URLs in AWS China, check this page: https://docs.amazonaws.cn/en_us/aws/latest/userguide/endpoints-arns.html
Some sample code:
# First, use the following PowerShell code to set environment variable. If you are using PyCharm, you need to restart PyCharm to let it read the updated environment variable after setting it in PowerShell.
# [Environment]::SetEnvironmentVariable("AWS_ACCESS_KEY_ID", "AKIATUAXUNK4LCTA4YA4", [EnvironmentVariableTarget]::User)
# [Environment]::SetEnvironmentVariable("AWS_SECRET_ACCESS_KEY", "", [EnvironmentVariableTarget]::User)
region_name = 'cn-north-1' # cn-northwest-1 is Ningxia, cn-north-1 is Beijing
# Initialize stat client for Role Assuming / Account Switch
sts_client = boto3.client(
service_name='sts',
region_name=region_name,
# you can refer to these links for China Region endpoint URL:
# https://docs.amazonaws.cn/en_us/aws/latest/userguide/endpoints-arns.html
# https://docs.amazonaws.cn/en_us/aws/latest/userguide/endpoints-Beijing.html
endpoint_url=f'https://sts.{region_name}.amazonaws.com.cn'
)
# Input your role ARN here
role_arn = 'arn:aws-cn:iam::4907xxxxx:role/RoleName'
# Get access token using assume_role method
assumed_role = sts_client.assume_role(
RoleArn=role_arn,
RoleSessionName='AssumeRoleSession1',
# ExternalId=external_id # only use this line if you have set up external id for your to-be-assumed role.
)
# Create session
credentials = assumed_role['Credentials']
session = boto3.Session(
aws_access_key_id=credentials['AccessKeyId'],
aws_secret_access_key=credentials['SecretAccessKey'],
aws_session_token=credentials['SessionToken']
)
# Initialize the actual client.
# Here I am using the AWS config service. You can change to any services per your requirement
config_client = session.client(
service_name='config',
region_name=region_name,
# https://docs.amazonaws.cn/en_us/config/latest/developerguide/config-region-support.html
endpoint_url=f'https://config.{region_name}.amazonaws.com.cn'
)