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. See the Alibaba Cloud SDK maintenance policy for details.
-
A V2.0 Alibaba Cloud SDK is required. For more information, see the V2.0 SDK and V1.0 SDK.
Install the Credentials tool
We recommend using pip to install the package.
pip install alibabacloud_credentials
You can find the latest version of the alibabacloud_credentials library on alibabacloud-credentials · PyPI or GitHub. We recommend using the latest version to ensure support for all features.
Credential types and parameters
The Config class of the alibabacloud_credentials.models module defines the credential types and configuration parameters for the credentials tool. The type parameter specifies the credential type. Each credential type requires a different set of configuration parameters. The following table describes the valid values for type and their supported configuration parameters. In the table, indicates a required parameter, a hyphen (-) indicates an optional parameter, and indicates that the parameter is not used.
We recommend that you do not use parameters that are not listed in the following table.
type | 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: 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 |
|
|
- |
|
- |
|
|
role_name: specifies the name of the RAM role. |
|
|
|
- |
|
|
|
disable_imds_v1: specifies whether to forcibly use the security hardening mode (IMDSv2). If you set this parameter to true, the security hardening mode (IMDSv2) is used. Default value: |
|
|
|
- |
|
|
|
bearer_token: a bearer token. |
|
|
|
|
|
|
|
policy: a custom policy. |
|
|
- |
|
- |
|
|
role_session_expiration: the session timeout period. Default value: 3600. Unit: seconds. |
|
|
- |
|
- |
|
|
oidc_provider_arn: the ARN of the OpenID Connect (OIDC) identity provider (IdP). |
|
|
|
|
|
|
|
oidc_token_file_path: the absolute path to the OIDC token. |
|
|
|
|
|
|
|
external_id: the external ID of the role, which is used to prevent the confused deputy issue. 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. Default value: |
|
|
- |
|
- |
|
|
timeout: the timeout period of HTTP read requests. Default value: 5000. Unit: milliseconds. |
|
|
- |
- |
- |
- |
|
connect_timeout: the timeout period of HTTP connection 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 initialize the credentials tool without providing any configuration parameters, the tool automatically retrieves credentials from the default credential chain. To use this method, ensure at least one credential source supported by the default credential chain is configured in your application's runtime environment.
from alibabacloud_credentials.client import Client as CredentialClient
from alibabacloud_tea_openapi import models as open_api_models
# If no configuration parameters are specified, the client retrieves credentials 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()
# For V2.0 cloud product SDKs, pass the credential client to the `Config` class.
config = open_api_models.Config(
credential=credentialsClient,
endpoint='<endpoint>'
)
# Use the config object to initialize the client for a cloud product. For details, see the SDK documentation for the specific cloud product.
Method 2: AK
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
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. This example retrieves the AccessKey ID from an environment variable.
access_key_id=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_ID'),
# Required. This example retrieves the AccessKey Secret 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 product, pass the credential by using the Config class from the alibabacloud_tea_openapi.models module.
config = open_api_models.Config(
credential=credentialsClient,
endpoint='<endpoint>'
)
# Then, use the config object to initialize the client for the corresponding cloud product.
Method 3: STS token
The Credentials tool uses the static STS token you provide as the access credential.
import os
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. This example retrieves the AccessKey ID from an environment variable.
access_key_id=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_ID'),
# Required. This example retrieves the AccessKey Secret from an environment variable.
access_key_secret=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_SECRET'),
# Required. This example retrieves the temporary Security Token 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 using a V2.0 SDK for a cloud product, pass the `credentialsClient` to the SDK's `Config` object.
config = open_api_models.Config(
credential=credentialsClient,
endpoint='<endpoint>'
)
# The code to initialize the cloud product client by using the config object is omitted...
Method 4: AccessKey and RAM role ARN
The credentials tool calls the AssumeRole operation with your AccessKey and RAM Role ARN to obtain an STS Token, which serves as the credential. These credentials refresh automatically. For more information, see Automatic refresh of session-type 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. This example retrieves the AccessKey ID from an environment variable.
access_key_id=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_ID'),
# Required. This example retrieves the AccessKey Secret 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 set this by using the ALIBABA_CLOUD_ROLE_ARN environment variable.
role_arn='<role_arn>',
# Optional. The role session name. You can also set this by using the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable.
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 for the role, used to prevent the confused deputy problem.
external_id='<external_id>',
# Optional. The session expiration time in seconds. The default value is 3600.
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 product, pass the credential by using the Config class from the alibabacloud_tea_openapi.models module.
config = open_api_models.Config(
credential=credentialsClient,
endpoint='<endpoint>'
)
# The code to initialize the cloud product client by using the config object is omitted...
Method 5: ECS instance RAM role
When your application runs on an ECS or ECI instance with a RAM role, the credentials tool retrieves the role's STS token from instance metadata to use as access credentials. The tool automatically refreshes these credentials. For more information, see Automatic refresh of session-type credentials.
By default, the credentials tool uses hardened mode (IMDSv2) to access ECS instance metadata. If an error occurs in hardened mode, you can control the fallback behavior with the disable_imds_v1 parameter or the ALIBABA_CLOUD_IMDSV1_DISABLED environment variable:
-
If set to
False(the default), the tool attempts to fall back to normal mode on failure. -
If set to
True, the tool uses only hardened mode and throws an exception on failure.
Support for IMDSv2 depends on your server's configuration.
You can also disable credential access from instance metadata by setting the ALIBABA_CLOUD_ECS_METADATA_DISABLED=true environment variable.
-
For more information about instance metadata, see Instance metadata.
-
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.
-
Using hardened mode to retrieve temporary credentials requires
alibabacloud_credentialsversion 0.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. Specifies the role name. If omitted, the tool retrieves the name automatically, but we recommend setting it to reduce requests. You can also set this with the ALIBABA_CLOUD_ECS_METADATA environment variable.
role_name='<role_name>',
# Optional. Default: False. If True, the tool uses only hardened mode. If False, the tool attempts hardened mode first and falls back to normal mode (IMDSv1) on failure.
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()
# For V2.0 SDKs, pass the credentialsClient object to the Config class from alibabacloud_tea_openapi.models.
config = open_api_models.Config(
credential=credentialsClient,
endpoint='<endpoint>'
)
# Client initialization code is omitted for brevity.
Method 6: OIDCRoleArn
If you use the OIDC authentication protocol and have created a RAM role for an OIDC identity provider, provide the OIDC identity provider ARN, the OIDC token file path, and the RAM role ARN to the credentials tool. The tool automatically calls the STS AssumeRoleWithOIDC operation to obtain an STS token for the RAM role, and uses this token as the access credential. These credentials refresh automatically. For more information, see Automatic refresh of session-type credentials. For example, if your application runs in an ACK cluster with RRSA enabled, the credentials tool reads the OIDC configuration from pod environment variables and calls the AssumeRoleWithOIDC operation to obtain an STS token for the service role. Your application then uses this 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 set this by using the ALIBABA_CLOUD_ROLE_ARN environment variable.
role_arn='<role_arn>',
# Required. The ARN of the OIDC identity provider. You can also set this by using the ALIBABA_CLOUD_OIDC_PROVIDER_ARN environment variable.
oidc_provider_arn='<oidc_provider_arn>',
# Required. The OIDC token file path. You can also set this by using the ALIBABA_CLOUD_OIDC_TOKEN_FILE environment variable.
oidc_token_file_path='<oidc_token_file_path>',
# Optional. The role session name. You can also set this by using the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable.
role_session_name='<role_session_name>',
# Optional. A more restrictive permission policy. Example: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"}
policy='<policy>',
# Optional. The session expiration time, in seconds. The default value is 3600.
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 product, pass the credential using the Config class from the alibabacloud_tea_openapi.models module.
config = open_api_models.Config(
credential=credentialsClient,
endpoint='<endpoint>'
)
# The code to initialize the cloud product client using the config object is omitted.
Method 7: URI credentials
You can wrap the STS service and expose it through a URI to retrieve an STS token. This method reduces the risk of exposing sensitive information, such as access keys. The credentials tool can fetch an STS token from a URI and use it as an access credential. These credentials refresh automatically. For more information, see Automatic refresh of session credentials.
The URI must meet the following conditions:
-
It must support GET requests.
-
The response status code must be 200.
-
The response body must be a JSON object with the following structure:
{ "Code": "Success", "AccessKeySecret": "yourAccessKeySecret", "AccessKeyId": "STS.****************", "Expiration": "2021-09-26T03:46:38Z", "SecurityToken": "yourSecurityToken" }
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 credential URI, such as http://local_or_remote_uri/. You can also set this with the ALIBABA_CLOUD_CREDENTIALS_URI environment variable.
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 using a V2.0 SDK for a cloud product, pass the credential to the Config class from the alibabacloud_tea_openapi.models module.
config = open_api_models.Config(
credential=credentialsClient,
endpoint='<endpoint>'
)
# The code to initialize the cloud product client using the config object 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.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. 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 using the CCC V2.0 SDK, pass the credential using the Config class from the alibabacloud_tea_openapi.models module.
config = open_api_models.Config(
credential=credentialsClient,
endpoint='<endpoint>'
)
# Code to initialize the cloud product client with the config object 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 version 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.
-
To learn 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.
-
Retrieving temporary credentials in security hardening mode requires alibabacloud_credentials version 0.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 update 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 classes.
#
@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:
# Get 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 to query the list of regions.
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 delays for 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 e8nhx6
AK Secret: 89HQ xxx 3pVFMsJzbStqUQn
STS Token: CAISxAJ1q6Ft5B2yfSjIr5v2ed2M3uhT3JKAb3b9h3AdS+oUga3T1Dz2IHhMeXZoA+4YsPw2mmFW6/sdLqdJQpp
/QkjJRNF20pLM7VtilmAGIpbng4YfgbiJREKxaXeiru xxx XUiTnmW3NFkFlyGEe4CFdkf3jm5bHu0WB0gCkK7FO/trLT8L6P5U2DvBWSMyo2eF6TK3F3RNL5gJCnKUM1/Qcp6if5I
/DXQEIvUTYbreL6L9mNxRkY6UgHKpJvCxxBmi0fUW5f xxx +UxM3D2hT+Bi3HLQztRLNaRsQdpz0agA6vG9rqhiMsdPZDiIoh5FHnB/fZ
+F9ol26SXsmquJdjfFgX9FFPVOqvnsHYRXUS2abqNKD xxx GzLDX26i+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 TnmW3NFkFlyGEe4CFdkf3jm5bHu0WB0gCkK7FO/trLT8L6P5U2DvBWSMyo2eF6TK3F3RNL5gJCnKUM1/Qcp6if5I
/DXQEIvUTYbreL6L9mNxRkY6UgHKpJvCxxBmi0fUW5f xxx M3D2hT+Bi3HLQztXxScP8Qdpz0agAG61LMbLwCjTNi3juW48l
+/w3E16v00Wet2c9vr1Ftp3qaJ8zuQJIMgixWIvAXa4 xxx AMf+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