This topic provides a code example and step-by-step instructions for using the Alibaba Cloud SDK for Python to call the Security Token Service (STS) AssumeRole operation.
Before you begin
The AssumeRole operation allows a principal, such as a Resource Access Management (RAM) user, to obtain temporary security credentials for a RAM role. You can then use these temporary credentials to access authorized cloud resources.
To learn more about the operation, its request parameters, and required permissions, see the AssumeRole API reference.
Prerequisites
Python 3 is installed. For more information, see Python downloads. After installation, verify the version by running
python3 --versionin your terminal.A RAM role is created. The role's trust policy must allow the RAM user you will create in the next step to assume it. The trusted principal can be the current account or another account. For instructions, see Create a RAM role for a trusted Alibaba Cloud account and Modify a RAM role's trust policy.
Step 1: Create a RAM user and grant permissions
In the RAM console, create a RAM user. For instructions, see Create a RAM user.
Create an AccessKey pair for the RAM user. Record the AccessKey ID and AccessKey secret for use in a later step. For instructions, see Create an AccessKey pair.
ImportantThe AccessKey secret is displayed only upon creation. You must save it in a secure location. If you lose it, you must create a new one.
Attach the
AliyunSTSAssumeRoleAccesssystem policy to the RAM user. This policy grants the minimum permissions required to call theAssumeRoleoperation.
Step 2: Set up your environment and run the code
This example uses the STS SDK for Python. For information about SDKs for other languages, see STS SDKs.
Install dependencies
Run the following commands to install the required libraries:
pip install alibabacloud_sts20150401 pip install alibabacloud_tea_console # The credentials library is typically installed as a dependency. # Run this command if it is missing. pip install alibabacloud_credentialsConfigure environment variables
For security, avoid hard-coding your credentials in your code. Configure your AccessKey pair as environment variables. For more information, see Configure credentials.
Run the code example
You can get pre-generated code samples from OpenAPI Explorer. Go to the AssumeRole page in OpenAPI Explorer, enter your request parameters, and click the SDK Sample Code tab to get a downloadable project.
Create a Python file (such as
sample.py) with the following code. Replace the placeholder values:<Your-Endpoint>: The STS endpoint for your region. For example,sts.ap-southeast-1.aliyuncs.com. For a list of endpoints, see Endpoints.<Role-Arn>: The Alibaba Cloud Resource Name (ARN) of the RAM role you want to assume. To find the ARN, go to the RAM role's details page in the RAM console. The ARN is displayed on the Basic Information section. For more information, see View the ARN of a RAM role.<Your-Session-Name>: A custom name for the session, such asmy-app-session. This name is used to identify the session in audit logs.
import os import sys import json from typing import List from alibabacloud_sts20150401.client import Client as Sts20150401Client from alibabacloud_credentials.client import Client as CredentialClient from alibabacloud_tea_openapi import models as open_api_models from alibabacloud_sts20150401 import models as sts_20150401_models from alibabacloud_tea_util import models as util_models from alibabacloud_tea_util.client import Client as UtilClient class Sample: def __init__(self): pass @staticmethod def create_client() -> Sts20150401Client: """ Initialize the Client with the credentials @return: Client @throws Exception """ # It is recommended to use the default credential. For more credentials, please refer to: https://www.alibabacloud.com/help/en/alibaba-cloud-sdk-262060/latest/configure-credentials-378659. credential = CredentialClient() config = open_api_models.Config( credential=credential ) # See https://api.alibabacloud.com/product/Sts. config.endpoint = f'<Your-Endpoint>' return Sts20150401Client(config) @staticmethod def main( args: List[str], ) -> None: client = Sample.create_client() assume_role_request = sts_20150401_models.AssumeRoleRequest( role_arn='<Role-Arn>', role_session_name='<Your-Session-Name>' ) runtime = util_models.RuntimeOptions() try: resp = client.assume_role_with_options(assume_role_request, runtime) print(json.dumps(resp, default=str, indent=2)) except Exception as error: # Only a printing example. Please be careful about exception handling and do not ignore exceptions directly in engineering projects. # print error message print(error.message) # Please click on the link below for diagnosis. print(error.data.get("Recommend")) @staticmethod async def main_async( args: List[str], ) -> None: client = Sample.create_client() assume_role_request = sts_20150401_models.AssumeRoleRequest( role_arn='<Role-Arn>', role_session_name='<Your-Session-Name>' ) runtime = util_models.RuntimeOptions() try: resp = await client.assume_role_with_options_async(assume_role_request, runtime) print(json.dumps(resp, default=str, indent=2)) except Exception as error: # Only a printing example. Please be careful about exception handling and do not ignore exceptions directly in engineering projects. # print error message print(error.message) # Please click on the link below for diagnosis. print(error.data.get("Recommend")) if __name__ == '__main__': Sample.main(sys.argv[1:])Run the file from your terminal:
python sample.py
Step 3: Review the output
If the call is successful, the output shows the temporary security credentials provided by STS. You can now use this temporary AccessKey pair and security token to access other Alibaba Cloud resources that the role has permissions for.
"headers": {
"date": "Thu, 17 Aug 2023 10:17:04 GMT",
"content-type": "application/json;charset=utf-8",
"content-length": "846",
"connection": "keep-alive",
"keep-alive": "timeout=25",
"access-control-allow-origin": "*",
"access-control-expose-headers": "*",
"x-acs-request-id": "79E360B6-FAC5-5B18-8081-BC0F8E90A238",
"x-acs-trace-id": "b2fb071a47e03e6d6cd507fd05438021",
"etag": "8bZ4pA7U/ulImlQiwhQnxXw6"
},
"statusCode": 200,
"body": {
"AssumedRoleUser": {
"Arn": "acs:ram::151266687691****:role/test-role/test",
"AssumedRoleId": "30081280744271****:test"
},
"Credentials": {
"AccessKeyId": "STS.NTdbdgE5zgL2qcb5pAify****",
"AccessKeySecret": "Fyk6ab1xfCFn88hXFxzV44QnF6cDi9T2PiTJgsqU****",
"Expiration": "2023-08-17T11:17:04Z",
"SecurityToken": "CAIS7AF1q6Ft5B2yfSjIr5fRKd7TqOpb0ISgUnocHLFUE6eDM****"
},
"RequestId": "79E360B6-FAC5-5B18-8081-BC0F8E90A238"
}
}