Manage access credentials
The Alibaba Cloud SDK uses the Credentials tool to centrally manage credentials, such as your AccessKey and STS Token. This topic describes the supported credential types and their configuration methods.
Prerequisites
The Credentials tool requires Python 3.7 or later. For more information, see Alibaba Cloud SDK maintenance policy.
Use a V2.0 Alibaba Cloud SDK. For more information, see V2.0 SDK and V1.0 SDK.
Install the Credentials tool
We recommend that you use pip to install the Credentials tool:
pip install alibabacloud_credentialsTo check the latest version of the alibabacloud_credentials library, see the alibabacloud-credentials package page on PyPI or the change log on GitHub. Use the latest version to ensure that all features are supported.
Credential types and parameters
The Config class in the alibabacloud_credentials.models module defines the credential types that the Credentials tool supports and the configuration parameters of each type. The type parameter specifies the credential type, and each credential type requires a different set of configuration parameters. In the following table, each column corresponds to a valid value of type, and each row corresponds to a configuration parameter. indicates a required parameter, - indicates an optional parameter, and indicates that the parameter is not supported.
We recommend that you use only the credential types and parameters that are listed in the following table.
| Parameter | access_key | sts | ram_role_arn | ecs_ram_role | oidc_role_arn | credentials_uri | bearer |
| access_key_id: the AccessKey ID. | |||||||
| access_key_secret: the AccessKey secret. | |||||||
| security_token: the Security Token Service (STS) token. | - | ||||||
| role_arn: the Alibaba Cloud Resource Name (ARN) of the Resource Access Management (RAM) role. | |||||||
role_session_name: the name of the custom session. The default format is credentials-python-The current timestamp. | - | - | |||||
| role_name: the name of the RAM role. | - | ||||||
disable_imds_v1: specifies whether to forcibly use the security hardening mode (IMDSv2). Default value: False. | - | ||||||
| bearer_token: a bearer token. | |||||||
| policy: a custom policy. | - | - | |||||
| role_session_expiration: the session expiration time. Default value: 3600. Unit: seconds. | - | - | |||||
| oidc_provider_arn: the ARN of the OpenID Connect (OIDC) IdP. | |||||||
| oidc_token_file_path: the path to the OIDC token file. | |||||||
| external_id: the external ID of the role, which is mainly used to prevent the confused deputy problem. For more information, see Prevent the confused deputy problem with external IDs. | - | ||||||
| credentials_uri: the URI of the credentials. | |||||||
sts_endpoint: the endpoint of STS. VPC endpoints and Internet endpoints are supported. For the valid values, see STS endpoints. Default value: sts.aliyuncs.com. | - | - | |||||
| timeout: the read timeout period of HTTP requests. Default value: 5000. Unit: milliseconds. | - | - | - | - | |||
| connect_timeout: the connection timeout period of HTTP requests. Default value: 10000. Unit: milliseconds. | - | - | - | - |
Using the Credentials tool
The previous section describes the credential types and configuration parameters supported by the Credentials tool. The following sections provide code examples showing how to use the tool. Select the method that best fits your scenario.
-
Hard-coding an AccessKey in your project creates security risks. Improperly managed repository permissions can expose all resources in your account. It is recommended to store the AccessKey in environment variables or configuration files.
-
Use a singleton pattern with the Credentials tool. This pattern enables the tool's built-in credential caching to prevent rate limiting from frequent API calls and avoid resource waste from creating multiple instances. For more information, see Automatic refresh of session credentials.
Method 1: Default credential chain
This is the default method used in the sample code on the OpenAPI Portal.
If you use the Credentials tool without passing any configuration parameters, the tool retrieves credentials from the default credential chain. Before you use this method, make sure that the runtime environment of your application is configured with one of the credential sources that the default credential chain supports.
from alibabacloud_credentials.client import Client as CredentialClient
from alibabacloud_tea_openapi import models as open_api_models
# If no configuration parameter is specified, credentials are retrieved from the default credential chain.
credentialsClient = CredentialClient()
credential = credentialsClient.get_credential()
access_key_id = credential.get_access_key_id()
access_key_secret = credential.get_access_key_secret()
security_token = credential.get_security_token()
# When you use a V2.0 SDK for a cloud service, pass the credential by using the Config class of the alibabacloud_tea_openapi.models module.
config = open_api_models.Config(
credential=credentialsClient,
endpoint='<endpoint>'
)
# Use config to initialize the client of the cloud service. For more information, see the SDK documentation of each cloud service.Method 2: AccessKey pair
The Credentials tool uses the AccessKey you provide as the access credential.
An Alibaba Cloud account (root account) has full permissions over all its resources, so an exposed AK poses a significant security risk. Do not use the AK of a root account.
Use the AK of a RAM user with least-privilege permissions.
import os
from alibabacloud_credentials.client import Client as CredentialClient
from alibabacloud_credentials.models import Config as CredentialConfig
from alibabacloud_tea_openapi import models as open_api_models
credentialsConfig = CredentialConfig(
type='access_key',
# Required. In this example, the AccessKey ID is retrieved from an environment variable.
access_key_id=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_ID'),
# Required. In this example, the AccessKey secret is retrieved from an environment variable.
access_key_secret=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_SECRET')
)
credentialsClient = CredentialClient(credentialsConfig)
credential = credentialsClient.get_credential()
access_key_id = credential.get_access_key_id()
access_key_secret = credential.get_access_key_secret()
security_token = credential.get_security_token()
# When you use a V2.0 SDK for a cloud service, pass the credential by using the Config class of the alibabacloud_tea_openapi.models module.
config = open_api_models.Config(
credential=credentialsClient,
endpoint='<endpoint>'
)
# Then, use config to initialize the client of the corresponding cloud service.Method 3: STS token
The Credentials tool uses the static STS token you provide as the access credential.
import os
from alibabacloud_credentials.client import Client as CredentialClient
from alibabacloud_credentials.models import Config as CredentialConfig
from alibabacloud_tea_openapi import models as open_api_models
credentialsConfig = CredentialConfig(
type='sts',
# Required. In this example, the AccessKey ID is retrieved from an environment variable.
access_key_id=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_ID'),
# Required. In this example, the AccessKey secret is retrieved from an environment variable.
access_key_secret=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_SECRET'),
# Required. In this example, the temporary security token is retrieved from an environment variable.
security_token=os.environ.get('ALIBABA_CLOUD_SECURITY_TOKEN')
)
credentialsClient = CredentialClient(credentialsConfig)
credential = credentialsClient.get_credential()
access_key_id = credential.get_access_key_id()
access_key_secret = credential.get_access_key_secret()
security_token = credential.get_security_token()
# When you use a V2.0 SDK for a cloud service, pass the credential by using the Config class of the alibabacloud_tea_openapi.models module.
config = open_api_models.Config(
credential=credentialsClient,
endpoint='<endpoint>'
)
# The code that uses config to initialize the client of the cloud service is omitted.Method 4: AccessKey pair and RAM role ARN
The Credentials tool uses the AccessKey pair and the RAM role ARN that you provide to call AssumeRole and obtain an STS token. The tool then uses the STS token as the access credential. Credentials obtained in this way support automatic refresh. For more information, see Automatic refresh mechanism of session credentials.
import os
from alibabacloud_credentials.client import Client as CredentialClient
from alibabacloud_credentials.models import Config as CredentialConfig
from alibabacloud_tea_openapi import models as open_api_models
credentialsConfig = CredentialConfig(
type='ram_role_arn',
# Required. In this example, the AccessKey ID is retrieved from an environment variable.
access_key_id=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_ID'),
# Required. In this example, the AccessKey secret is retrieved from an environment variable.
access_key_secret=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_SECRET'),
# Required. The ARN of the RAM role to assume. Example: acs:ram::123456789012****:role/adminrole. You can also use the ALIBABA_CLOUD_ROLE_ARN environment variable to set this parameter.
role_arn='<role_arn>',
# Optional. The role session name. You can also use the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable to set this parameter.
role_session_name='<role_session_name>',
# Optional. A more restrictive policy. Example: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"}
policy='<policy>',
# Optional. The external ID of the role, which is mainly used to prevent the confused deputy problem.
external_id='<external_id>',
# Optional. The session expiration time. Default value: 3600 seconds.
role_session_expiration=3600
)
credentialsClient = CredentialClient(credentialsConfig)
credential = credentialsClient.get_credential()
access_key_id = credential.get_access_key_id()
access_key_secret = credential.get_access_key_secret()
security_token = credential.get_security_token()
# When you use a V2.0 SDK for a cloud service, pass the credential by using the Config class of the alibabacloud_tea_openapi.models module.
config = open_api_models.Config(
credential=credentialsClient,
endpoint='<endpoint>'
)
# The code that uses config to initialize the client of the cloud service is omitted.Method 5: ECS instance RAM role
If your application runs on an Elastic Compute Service (ECS) or Elastic Container Instance (ECI) instance that has a RAM role attached, the Credentials tool can obtain the STS token of the RAM role from the instance metadata and use the token as the access credential. Credentials obtained in this way support automatic refresh. For more information, see Automatic refresh mechanism of session credentials.
By default, the Credentials tool uses the security hardening mode (IMDSv2) to access ECS instance metadata. If an error occurs in the security hardening mode, use the disable_imds_v1 parameter or the ALIBABA_CLOUD_IMDSV1_DISABLED environment variable to control how the tool handles the error:
If the value is
False, which is the default value, the Credentials tool tries to switch to the normal mode (IMDSv1) to continue obtaining credentials.If the value is
Whether an instance supports the security hardening mode depends on how the instance is configured.True, the Credentials tool obtains credentials only in the security hardening mode. If access in the security hardening mode fails, an exception is thrown.
You can also set the ALIBABA_CLOUD_ECS_METADATA_DISABLED=true environment variable to prevent the Credentials tool from obtaining credentials from the instance metadata.
For more information about instance metadata, see Instance metadata.
For more information about how to attach a RAM role to an ECS or ECI instance, see Step 1: Create a RAM role and Attach an instance RAM role to an ECI instance.
To obtain temporary identity credentials in the security hardening mode, use
alibabacloud_credentials0.3.6 or later.
from alibabacloud_credentials.client import Client as CredentialClient
from alibabacloud_credentials.models import Config as CredentialConfig
from alibabacloud_tea_openapi import models as open_api_models
credentialsConfig = CredentialConfig(
type='ecs_ram_role',
# Optional. The name of the ECS role. If you leave this parameter empty, the name is obtained automatically. We recommend that you specify the name to reduce the number of requests. You can also use the ALIBABA_CLOUD_ECS_METADATA environment variable to set this parameter.
role_name='<role_name>',
# Optional. Default value: False. True: credentials are obtained only in the security hardening mode (IMDSv2), and an exception is thrown if access fails, so set True only for instances that support the security hardening mode. False: the tool first tries to obtain credentials in the security hardening mode. If the attempt fails, the tool switches to the normal mode (IMDSv1).
disable_imds_v1=True
)
credentialsClient = CredentialClient(credentialsConfig)
credential = credentialsClient.get_credential()
access_key_id = credential.get_access_key_id()
access_key_secret = credential.get_access_key_secret()
security_token = credential.get_security_token()
# When you use a V2.0 SDK for a cloud service, pass the credential by using the Config class of the alibabacloud_tea_openapi.models module.
config = open_api_models.Config(
credential=credentialsClient,
endpoint='<endpoint>'
)
# The code that uses config to initialize the client of the cloud service is omitted.Method 6: OIDC role ARN
If you use the OIDC authentication protocol and have created a RAM role for an OIDC identity provider, you can pass the ARN of the OIDC IdP, the OIDC token, and the RAM role ARN to the Credentials tool. The tool automatically calls the AssumeRoleWithOIDC operation of STS to obtain the STS token of the RAM role and uses the STS token as the access credential. Credentials obtained in this way support automatic refresh. For more information, see Automatic refresh mechanism of session credentials.
For example, if your application runs in a Container Service for Kubernetes (ACK) cluster that has RRSA enabled, the Credentials tool reads the OIDC configuration from the pod environment variables and calls the AssumeRoleWithOIDC operation to obtain the STS token of the service role. Your application then uses the STS token to access Alibaba Cloud services.
from alibabacloud_credentials.client import Client as CredentialClient
from alibabacloud_credentials.models import Config as CredentialConfig
from alibabacloud_tea_openapi import models as open_api_models
credentialsConfig = CredentialConfig(
type='oidc_role_arn',
# Required. The RAM role ARN. You can also use the ALIBABA_CLOUD_ROLE_ARN environment variable to set this parameter.
role_arn='<role_arn>',
# Required. The ARN of the OIDC IdP. You can also use the ALIBABA_CLOUD_OIDC_PROVIDER_ARN environment variable to set this parameter.
oidc_provider_arn='<oidc_provider_arn>',
# Required. The path to the OIDC token file. You can also use the ALIBABA_CLOUD_OIDC_TOKEN_FILE environment variable to set this parameter.
oidc_token_file_path='<oidc_token_file_path>',
# Optional. The role session name. You can also use the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable to set this parameter.
role_session_name='<role_session_name>',
# Optional. A more restrictive policy. Example: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"}
policy='<policy>',
# Optional. The session expiration time. Default value: 3600 seconds.
role_session_expiration=3600
)
credentialsClient = CredentialClient(credentialsConfig)
credential = credentialsClient.get_credential()
access_key_id = credential.get_access_key_id()
access_key_secret = credential.get_access_key_secret()
security_token = credential.get_security_token()
# When you use a V2.0 SDK for a cloud service, pass the credential by using the Config class of the alibabacloud_tea_openapi.models module.
config = open_api_models.Config(
credential=credentialsClient,
endpoint='<endpoint>'
)
# The code that uses config to initialize the client of the cloud service is omitted.Method 7: URI credentials
You can encapsulate the STS service and expose a URI so that external services can obtain an STS token through the URI. This approach reduces the risk of exposing sensitive information such as an AccessKey pair. The Credentials tool accesses the URI that you provide to obtain an STS token and uses the token as the access credential. Credentials obtained in this way support automatic refresh. For more information, see Automatic refresh mechanism of session credentials.
The URI must meet the following conditions:
GET requests are supported.
The response status code is 200.
The response body has the following structure:
{
"Code": "Success",
"AccessKeySecret": "yourAccessKeySecret",
"AccessKeyId": "STS.****************",
"Expiration": "2021-09-26T03:46:38Z",
"SecurityToken": "yourSecurityToken"
}The following example shows how to obtain credentials from a URI:
from alibabacloud_credentials.client import Client as CredentialClient
from alibabacloud_credentials.models import Config as CredentialConfig
from alibabacloud_tea_openapi import models as open_api_models
credentialsConfig = CredentialConfig(
type='credentials_uri',
# Required. The URI from which the credentials are obtained. The format is http://local_or_remote_uri/. You can also use the ALIBABA_CLOUD_CREDENTIALS_URI environment variable to set this parameter.
credentials_uri='<credentials_uri>',
)
credentialsClient = CredentialClient(credentialsConfig)
credential = credentialsClient.get_credential()
access_key_id = credential.get_access_key_id()
access_key_secret = credential.get_access_key_secret()
security_token = credential.get_security_token()
# When you use a V2.0 SDK for a cloud service, pass the credential by using the Config class of the alibabacloud_tea_openapi.models module.
config = open_api_models.Config(
credential=credentialsClient,
endpoint='<endpoint>'
)
# The code that uses config to initialize the client of the cloud service is omitted.Method 8: Bearer token
Currently, only Alibaba Cloud Call Center (CCC) supports bearer token authentication.
from alibabacloud_credentials.client import Client as CredentialClient
from alibabacloud_credentials.models import Config as CredentialConfig
from alibabacloud_tea_openapi import models as open_api_models
credentialsConfig = CredentialConfig(
type='bearer',
# Required. Enter your bearer token.
bearer_token='<BearerToken>',
)
credentialsClient = CredentialClient(credentialsConfig)
credential = credentialsClient.get_credential()
access_key_id = credential.get_access_key_id()
access_key_secret = credential.get_access_key_secret()
security_token = credential.get_security_token()
# When you use the CCC V2.0 SDK, pass the credential by using the Config class of the alibabacloud_tea_openapi.models module.
config = open_api_models.Config(
credential=credentialsClient,
endpoint='<endpoint>'
)
# The code that uses config to initialize the client of the cloud service is omitted.Default credential provider chain
The default credential provider chain is a fallback mechanism that searches for a credential by checking a predefined sequence of locations. The search continues until a credential is found. If no credential is found after checking all locations, a CredentialException is thrown. The search order is as follows:
1. Obtain the credential information from environment variables
If no credential is found in the system properties, the provider chain then checks for environment variables.
-
If both ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET are present and not empty, the provider chain uses them as the default credential.
-
If ALIBABA_CLOUD_ACCESS_KEY_ID, ALIBABA_CLOUD_ACCESS_KEY_SECRET, and ALIBABA_CLOUD_SECURITY_TOKEN are also set, the provider chain uses an STS token as the default credential.
2. Obtain the credential information by using the RAM role of an OIDC IdP
If no credential has been found, the provider chain checks for the following environment variables related to an OIDC RAM role:
-
ALIBABA_CLOUD_ROLE_ARN: The ARN of the RAM role.
-
ALIBABA_CLOUD_OIDC_PROVIDER_ARN: The ARN of the OIDC provider.
-
ALIBABA_CLOUD_OIDC_TOKEN_FILE: The file path of the OIDC token.
If all three environment variables are present and not empty, the provider chain uses these values to call the AssumeRoleWithOIDC API of the Security Token Service (STS) to obtain an STS token.
3. Obtain the credential information from a configuration file
This feature requires alibabacloud_credentials 1.0rc3 or later.
If no credential has been found, the provider chain attempts to load the shared credentials file, config.json, from its default location and uses the credential specified in the file.
-
Linux/macOS:
~/.aliyun/config.json -
Windows:
C:\Users\USER_NAME\.aliyun\config.json
To configure a credential this way, you can use the Alibaba Cloud CLI or manually create a config.json file in the appropriate path. The following example shows the content format:
{
"current": "<PROFILE_NAME>",
"profiles": [
{
"name": "<PROFILE_NAME>",
"mode": "AK",
"access_key_id": "<ALIBABA_CLOUD_ACCESS_KEY_ID>",
"access_key_secret": "<ALIBABA_CLOUD_ACCESS_KEY_SECRET>"
},
{
"name": "<PROFILE_NAME1>",
"mode": "StsToken",
"access_key_id": "<ALIBABA_CLOUD_ACCESS_KEY_ID>",
"access_key_secret": "<ALIBABA_CLOUD_ACCESS_KEY_SECRET>",
"sts_token": "<SECURITY_TOKEN>"
},
{
"name":"<PROFILE_NAME2>",
"mode":"RamRoleArn",
"access_key_id":"<ALIBABA_CLOUD_ACCESS_KEY_ID>",
"access_key_secret":"<ALIBABA_CLOUD_ACCESS_KEY_SECRET>",
"ram_role_arn":"<ROLE_ARN>",
"ram_session_name":"<ROLE_SESSION_NAME>",
"expired_seconds":3600
},
{
"name":"<PROFILE_NAME3>",
"mode":"EcsRamRole",
"ram_role_name":"<RAM_ROLE_ARN>"
},
{
"name":"<PROFILE_NAME4>",
"mode":"OIDC",
"oidc_provider_arn":"<OIDC_PROVIDER_ARN>",
"oidc_token_file":"<OIDC_TOKEN_FILE>",
"ram_role_arn":"<ROLE_ARN>",
"ram_session_name":"<ROLE_SESSION_NAME>",
"expired_seconds":3600
},
{
"name":"<PROFILE_NAME5>",
"mode":"ChainableRamRoleArn",
"source_profile":"<PROFILE_NAME>",
"ram_role_arn":"<ROLE_ARN>",
"ram_session_name":"<ROLE_SESSION_NAME>",
"expired_seconds":3600
}
]
}
|
Parameter |
Description |
|
current |
Specify the credential name to retrieve the corresponding credential configuration. The credential name is the value of the |
|
profiles |
Contains a collection of credential configurations. The
|
4. Obtain the credential information by using the RAM role of an ECS instance
If no credential has been found, the provider chain attempts to retrieve an STS token for the instance RAM role from the instance metadata. This token is then used as the default credential. To do this, the chain first retrieves the name of the RAM role assigned to the instance and then uses that role to obtain the corresponding STS token. To reduce credential retrieval time and improve efficiency, you can specify the RAM role name directly by using the ALIBABA_CLOUD_ECS_METADATA environment variable.
By default, the provider chain accesses instance metadata in security-hardened mode (IMDSv2). If an exception occurs in security-hardened mode, you can use the ALIBABA_CLOUD_IMDSV1_DISABLED environment variable to control the fallback behavior:
-
When the value is
false(default), the system attempts to switch to legacy mode to retrieve the credential. -
When the value is
true, security-hardened mode is enforced. If access fails in this mode, an exception is thrown.
Additionally, you can prevent the provider chain from accessing instance metadata for credentials by setting the ALIBABA_CLOUD_ECS_METADATA_DISABLED=true environment variable.
For more information about instance metadata, see Instance metadata.
For more information about how to attach a RAM role to an ECS or ECI instance, see Step 1: Create a RAM role and Attach an instance RAM role to an ECI instance.
To obtain temporary identity credentials in the security hardening mode, use
alibabacloud_credentials0.3.6 or later.
5. Obtain the credential information based on a URI
If no credential has been found, the provider chain checks for the ALIBABA_CLOUD_CREDENTIALS_URI environment variable. If this variable is set and points to a valid URI, the chain accesses the URI to retrieve an STS token.
Automatic refresh mechanism of session credentials
Session credential types, such as ram_role_arn, ecs_ram_role, oidc_role_arn, and credentials_uri, support automatic refresh through a built-in mechanism in the credential provider. When a credential client retrieves a credential for the first time, the provider stores it in a cache. In subsequent operations, the same client instance automatically retrieves the credential from this cache. If the cached credential has expired, the client instance fetches a new one and updates the cache accordingly.
For ecs_ram_role credentials, the credential provider proactively refreshes them 15 minutes before they expire.
The following example uses the singleton pattern to create a credential client. It demonstrates the refresh mechanism by fetching a credential at different time intervals and calling an OpenAPI operation to verify that the credential is usable.
import os
import sys
import time
import threading
from functools import wraps
from threading import Lock
from alibabacloud_credentials.client import Client as CredentialClient
from alibabacloud_credentials.models import Config as CredentialConfig
from alibabacloud_ecs20140526.client import Client
from alibabacloud_ecs20140526.models import DescribeRegionsRequest
from alibabacloud_tea_openapi.models import Config as EcsConfig
#
# Thread-safe singleton decorator.
#
def singleton(cls):
"""Implements a thread-safe singleton pattern."""
instances = {}
lock = Lock()
@wraps(cls)
def wrapper(*args, **kwargs):
with lock:
if cls not in instances:
instances[cls] = cls(*args, **kwargs)
return instances[cls]
return wrapper
#
# Singleton service class.
#
@singleton
class Credential:
def __init__(self):
self._client = self._init_client()
@staticmethod
def _init_client() -> CredentialClient:
try:
config = CredentialConfig(
type="ram_role_arn",
access_key_id=os.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"),
access_key_secret=os.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"),
role_arn=os.getenv("ALIBABA_CLOUD_ROLE_ARN"),
role_session_name="RamRoleArnTest",
role_session_expiration=3600,
)
return CredentialClient(config)
except Exception as e:
raise RuntimeError(f"Credential initialization failed: {e}") from e
@property
def client(self) -> CredentialClient:
return self._client
@singleton
class EcsClient:
def __init__(self, credential: CredentialClient):
self._client = self._init_client(credential)
@staticmethod
def _init_client(credential: CredentialClient) -> Client:
try:
ecs_config = EcsConfig(credential=credential)
ecs_config.endpoint = 'ecs.cn-hangzhou.aliyuncs.com'
return Client(ecs_config)
except Exception as e:
raise RuntimeError(f"ECS client initialization failed: {e}") from e
@property
def client(self) -> Client:
return self._client
#
# Task function.
#
def execute_task():
try:
# Obtain the credential and the ECS client.
credential = Credential().client.get_credential()
ecs_client = EcsClient(Credential().client).client
# Print the credential information.
print("Time:", time.strftime("%Y-%m-%d %H:%M:%S"))
print("AK ID:", credential.access_key_id)
print("AK Secret:", credential.access_key_secret)
print("STS Token:", credential.security_token)
# Call an API operation to query the region list.
request = DescribeRegionsRequest()
response = ecs_client.describe_regions(request)
print("Invoke result:", response.to_map()["statusCode"])
except Exception as e:
print(f"ECS client execution failed: {e}")
raise
def schedule_task():
def run_execute_task():
try:
execute_task()
except Exception as e:
print(f"Task execution failed: {e}")
finally:
nonlocal task_count
task_count += 1
if task_count == len(DELAYS):
print("All tasks completed. Exiting program.")
sys.exit(0)
def schedule_execution(delay):
task_timer = threading.Timer(delay, run_execute_task)
task_timer.start()
return task_timer
# Define the delays of the scheduled tasks.
DELAYS = [0, 600, 4200, 4300]
task_count = 0
timers = [schedule_execution(delay) for delay in DELAYS]
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
print("Program interrupted by user.")
for timer in timers:
timer.cancel()
if __name__ == "__main__":
schedule_task()Time: 2025-05-28 14:51:51
AK ID: STS.NXC2_xxx_3e8nhx6
AK Secret: 89HQ_xxx_3pVFMsJzbStqUQn
STS Token: CAISxAJ1q6Ft5B2yfSjIr5v2ed2M3uhT3JKAb3b9h3AdS+oUga3T1Dz2IHhMeXZoA+4YsPw2mmFW6/sdLqdJQpp
/QkjJRNF20pLM7VtilmAGIpbng4YfgbiJREKxaXeiru_xxx_3XUiTnmW3NFkFlyGEe4CFdkf3jm5bHu0WB0gCkK7FO/trLT8L6P5U2DvBWSMyo2eF6TK3F3RNL5gJCnKUM1/Qcp6if5I
/DXQEIvUTYbreL6L9mNxRkY6UgHKpJvCxxBmi0fUW5f_xxx_+UxM3D2hT+Bi3HLQztRLNaRsQdpz0agA6vG9rqhiMsdPZDiIoh5FHnB/fZ
+F9ol26SXsmquJdjfFgX9FFPVOqvnsHYRXUS2abqNKD_xxx_1GzLDX26i+hM2jxG6CFc9BJ3S5iElyLCAA
Invoke result: 200
Time: 2025-05-28 15:01:51
AK ID: STS.NXC2_xxx_3e8nhx6
AK Secret: 89HQ_xxx_3pVFMsJzbStqUQn
STS Token: CAISxAJ1q6Ft5B2yfSjIr5v2ed2M3uhT3JKAb3b9h3AdS+oUga3T1Dz2IHhMeXZoA+4YsPw2mmFW6/sdLqdJQpp
/QkjJRNF20pLM7VtilmAGIpbng4YfgbiJREKxaXeiru_xxx_3XUiTnmW3NFkFlyGEe4CFdkf3jm5bHu0WB0gCkK7FO/trLT8L6P5U2DvBWSMyo2eF6TK3F3RNL5gJCnKUM1/Qcp6if5I
/DXQEIvUTYbreL6L9mNxRkY6UgHKpJvCxxBmi0fUW5f_xxx_+UxM3D2hT+Bi3HLQztRLNaRsQdpz0agA6vG9rqhiMsdPZDiIoh5FHnB/fZ
+F9ol26SXsmquJdjfFgX9FFPVOqvnsHYRXUS2abqNKD_xxx_1GzLDX26i+hM2jxG6CFc9BJ3S5iElyLCAA
Invoke result: 200
Time: 2025-05-28 16:01:53
AK ID: STS.NVw9_xxx_QZ3M4mu
AK Secret: 2mP6_xxx_Xvp38ai4mJTazm
STS Token: CAISxAJ1q6Ft5B2yfSjIr5XCctz4vp1A9qmocRChqE4hXdUfovH6Lzz2IHhMeXZoA+4YsPw2mmFW6/sdLqdJQpp
/QkjJRNF20pLM7VtoxWAYIpbng4YfgbiJREKxaXeiru_xxx_iTnmW3NFkFlyGEe4CFdkf3jm5bHu0WB0gCkK7FO/trLT8L6P5U2DvBWSMyo2eF6TK3F3RNL5gJCnKUM1/Qcp6if5I
/DXQEIvUTYbreL6L9mNxRkY6UgHKpJvCxxBmi0fUW5f_xxx_xM3D2hT+Bi3HLQztXxScP8Qdpz0agAG61LMbLwCjTNi3juW48l
+/w3E16v00Wet2c9vr1Ftp3qaJ8zuQJIMgixWIvAXa4_xxx_eAMf+DaoEa0gUg1lQ7096D76vMDDr1eTiiAA
Invoke result: 200
Time: 2025-05-28 16:03:31
AK ID: STS.NVw9_xxx_QZ3M4mu
AK Secret: 2mP6_xxx_Xvp38ai4mJTazm
STS Token: CAISxAJ1q6Ft5B2yfSjIr5XCctz4vp1A9qmocRChqE4hXdUfovH6Lzz2IHhMeXZoA+4YsPw2mmFW6/sdLqdJQpp
/QkjJRNF20pLM7VtoxWAYIpbng4YfgbiJREKxaXeiru_xxx_iTnmW3NFkFlyGEe4CFdkf3jm5bHu0WB0gCkK7FO/trLT8L6P5U2DvBWSMyo2eF6TK3F3RNL5gJCnKUM1/Qcp6if5I
/DXQEIvUTYbreL6L9mNxRkY6UgHKpJvCxxBmi0fUW5f_xxx_xM3D2hT+Bi3HLQztXxScP8Qdpz0agAG61LMbLwCjTNi3juW48l
+/w3E16v00Wet2c9vr1Ftp3qaJ8zuQJIMgixWIvAXa4_xxx_eAMf+DaoEa0gUg1lQ7096D76vMDDr1eTiiAA
Invoke result: 200Analysis based on the log output:
-
On the first call, the cache is empty. The system retrieves a credential based on your configuration and then stores it in the cache.
-
The second call uses the same credential as the first, indicating it was retrieved from the cache.
-
On the third call, the cached credential has expired. Its expiration time (
RoleSessionExpiration) is 3,600 seconds, but this call is made 4,200 seconds after the first one. Consequently, the SDK's automatic refresh mechanism fetches a new credential and updates the cache. -
The fourth call uses the same credential as the third, confirming that the cache was updated.
Related documents
-
For an overview of the basic concepts of RAM, see Basic concepts.
-
To create an AccessKey, see Create an AccessKey.
-
To programmatically create RAM users, AccessKeys, and RAM roles; define permission policies; and grant permissions, see RAM SDK overview.
-
To programmatically assume a role, see STS SDK overview.
-
For details about the RAM and STS APIs, see the API reference.
-
Best practices for using access credentials to call Alibaba Cloud OpenAPI