Alibaba Cloud STS (Security Token Service) SDK

1.2.0 · active · verified Wed Apr 15

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

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize the STS client and call the `AssumeRole` API to obtain temporary credentials. It retrieves AccessKeyId and SecretKey from environment variables for security best practices and specifies a placeholder Role ARN. Remember to replace `YourRoleName` with your actual RAM Role ARN.

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)

view raw JSON →