Alibaba Cloud STS (Security Token Service) SDK
The `alibabacloud-sts20150401` library is the official Alibaba Cloud SDK for interacting with the Security Token Service (STS) API version 2015-04-01. It allows you to issue temporary access credentials for Alibaba Cloud resources, commonly used for granting temporary permissions or cross-account access. The current version is 1.2.0. Like most Alibaba Cloud SDKs, it follows a stable release cadence, with updates primarily for bug fixes or minor enhancements rather than frequent new features.
Common errors
-
ModuleNotFoundError: No module named 'alibabacloud_sts20150401'
cause The 'alibabacloud_sts20150401' package is not installed in the Python environment.fixInstall the package using pip: 'pip install alibabacloud-sts20150401'. -
ImportError: cannot import name 'Sts20150401Client' from 'alibabacloud_sts20150401'
cause Incorrect import statement; 'Sts20150401Client' should be imported from 'alibabacloud_sts20150401.client'.fixUse the correct import: 'from alibabacloud_sts20150401.client import Client as Sts20150401Client'. -
AttributeError: module 'alibabacloud_sts20150401' has no attribute 'AssumeRoleRequest'
cause Attempting to access 'AssumeRoleRequest' directly from the 'alibabacloud_sts20150401' module instead of its 'models' submodule.fixImport 'AssumeRoleRequest' from the 'models' submodule: 'from alibabacloud_sts20150401 import models as sts_20150401_models'. -
InvalidAccessKeyId.NotFound: Specified access key is not found.
cause The AccessKey ID provided for authentication is either incorrect, contains typographical errors, or does not exist in your Alibaba Cloud account.fixVerify that your `AccessKeyId` is correct and active in the Alibaba Cloud console. Ensure there are no leading or trailing spaces. -
NoPermission: No permission perform sts:AssumeRole on this Role.
cause The RAM user or RAM role attempting to call the `AssumeRole` operation does not have the necessary permissions (e.g., `sts:AssumeRole`) or the target RAM role's trust policy does not allow the calling entity to assume it.fixGrant the `AliyunSTSAssumeRoleAccess` system authorization permission to the RAM user, or modify the trust policy of the target RAM role to allow the calling entity to assume it.
Warnings
- gotcha Alibaba Cloud SDKs often use `alibabacloud-SERVICEAPIVERSION` for their package names. This `sts20150401` package is specifically for the 2015-04-01 API version. Ensure you are using the correct package for the API version you intend to target, as there might be other STS packages for different versions or older SDK styles (e.g., `aliyun-python-sdk-sts`).
- gotcha The base `Config` object for client initialization (e.g., `Config(access_key_id=..., endpoint=...)`) must be imported from `alibabacloud_tea_openapi.models`, not from `alibabacloud_sts20150401.models` or other service-specific packages. Misimporting `Config` is a common mistake that leads to `AttributeError` or unexpected behavior.
- gotcha Authentication credentials (AccessKeyId and AccessKeySecret) should be managed securely. Hardcoding them directly in your code is strongly discouraged. It's recommended to use environment variables, instance RAM roles, or a secrets management service.
- gotcha Although STS is a global service, explicitly setting the `endpoint` in the `Config` object (e.g., `endpoint='sts.aliyuncs.com'`) is a good practice to prevent potential issues if the default resolution changes or if you need to connect through a specific region's endpoint proxy for network reasons.
Install
-
pip install alibabacloud-sts20150401
Imports
- Client
from alibabacloud_sts20150401.client import Client as StsClient
- Config
from alibabacloud_sts20150401.models import Config
from alibabacloud_tea_openapi.models import Config
- AssumeRoleRequest
from alibabacloud_sts20150401.models import AssumeRoleRequest
Quickstart
import os
from alibabacloud_sts20150401.client import Client as StsClient
from alibabacloud_tea_openapi.models import Config
from alibabacloud_sts20150401.models import AssumeRoleRequest
from alibabacloud_tea_util.models import RuntimeOptions
# Ensure environment variables are set for security
access_key_id = os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_ID', '')
access_key_secret = os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_SECRET', '')
role_arn = os.environ.get('ALIBABA_CLOUD_ROLE_ARN', 'acs:ram::xxxxxxxxxxxxxxx:role/YourRoleName')
role_session_name = os.environ.get('ALIBABA_CLOUD_ROLE_SESSION_NAME', 'my-sts-session')
if not access_key_id or not access_key_secret:
print("Error: ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET must be set.")
exit(1)
# Configure the client
config = Config(
access_key_id=access_key_id,
access_key_secret=access_key_secret,
# STS is a global service, default endpoint is sts.aliyuncs.com
endpoint='sts.aliyuncs.com'
)
# Create a client instance
try:
client = StsClient(config)
print("STS Client initialized successfully.")
# Prepare the AssumeRole request
assume_role_request = AssumeRoleRequest(
role_arn=role_arn,
role_session_name=role_session_name,
duration_seconds=3600 # Optional: specify duration of token in seconds (default is 3600s)
)
# Create a runtime option, useful for setting timeout or retry policy
runtime = RuntimeOptions()
# Call the AssumeRole API
response = client.assume_role_with_options(assume_role_request, runtime)
# Print the temporary credentials
credentials = response.body.credentials
print("\nAssumed Role Credentials:")
print(f"AccessKeyId: {credentials.access_key_id}")
print(f"AccessKeySecret: {credentials.access_key_secret}")
print(f"SecurityToken: {credentials.security_token[:10]}...{credentials.security_token[-10:]}") # Truncate for display
print(f"Expiration: {credentials.expiration}")
except Exception as error:
print(f"An error occurred: {error}")
# In a real application, you'd log the full error or specific details
# print(error.args[0].get('Code') if hasattr(error, 'args') and len(error.args) > 0 and isinstance(error.args[0], dict) else error)