The secret client is a custom wrapper built on KMS OpenAPI and KMS instance APIs. It handles credential caching and automatic refresh inside your application, so you can retrieve a secret value with a single method call instead of managing cache logic yourself. Because each call to the KMS API counts toward your usage quota, caching frequently accessed secrets reduces both latency and costs.
The secret client supports all credential types: generic secrets, RAM credentials, ECS credentials, and database credentials. Supported languages are Java (Java 8+), Python, and Go.
To perform management operations on secrets (create, update, delete), use the Alibaba Cloud SDK instead. The secret client is read-only.
How it works
All examples use the same two-call pattern:
Build a
SecretCacheClientwith your chosen authentication method and region.Call
getSecretInfo(or the language-specific equivalent) with a secret name to retrieve the cached value.
The client automatically handles caching, refresh on expiry, and server-side error retries. Its plug-in design lets you replace the default cache or retry behavior with your own implementation.
Prerequisites
Before you begin, make sure you have:
A KMS instance or access to the shared KMS gateway
A secret already created in KMS
Permissions to retrieve secrets (see System policies for KMS or configure resource-based policies)
Choose your gateway
| Gateway | Network type | Authentication | Recommended |
|---|---|---|---|
| Shared KMS gateway | Public network or VPC | Instance RAM role, RamRoleArn, Security Token Service (STS) token, AccessKey, ClientKey | Yes |
| Dedicated KMS gateway | KMS private network | ClientKey only | No |
Get a secret value through the shared gateway
Step 1: Create an access credential
The shared gateway supports several authentication methods. Use the most secure method available for your environment.
Instance RAM role (recommended)
An instance RAM role attached to an Elastic Compute Service (ECS) instance lets your application obtain temporary STS tokens automatically, without storing any long-term credentials.
In the RAM console, create a RAM role with Principal Type set to Cloud Service and Principal Name set to Elastic Compute Service / ECS.
Grant the RAM role access to retrieve KMS secrets using one of these methods:
Identity-based policies: Attach a KMS system policy or custom policy to the role. For available system policies, see System policies for KMS.

Resource-based policies: Configure access permissions on specific secrets. See Secret policies.
In the ECS console, attach the RAM role to your ECS instance.

RamRoleArn
Use RamRoleArn when your application needs to assume a RAM role at runtime rather than using a permanent access key. This is common in cross-account access or temporary data-processing tasks.
Log on to the RAM console.
Grant the RAM role access to KMS secrets using identity-based policies or resource-based policies (same methods as described in the Instance RAM role section above).
Find the RamRoleArn of the role. It follows the format
acs:ram::<accountID>:role/<roleName>.
STS token
An STS token grants a RAM user or role temporary, time-limited access to KMS. The token becomes invalid automatically after the validity period expires.
Log on to the RAM console.
Grant
AliyunSTSAssumeRoleAccesspermission to the RAM user or RAM role.
Grant the RAM user or role access to KMS secrets using identity-based policies or resource-based policies.
Call the AssumeRole API to obtain temporary credentials.
AccessKey
Alibaba Cloud root account AccessKeys carry full administrator access and cannot have permissions restricted. Create a dedicated RAM user for API access and apply the principle of least privilege. Never hardcode AccessKey pairs in your application code—store them in environment variables instead.
In the RAM console, go to Identities > Users and click your target RAM user.
On the Authentication tab, click Create AccessKey and follow the prompts.

Grant the RAM user access to retrieve KMS secrets using identity-based or resource-based policies.

ClientKey (not recommended)
Follow the standard creation steps in Create an application access point (AAP). When configuring parameters, set Network Type to Public or VPC and set the permission scope to Shared KMS Gateway.
Step 2: Install the secret client
Java
Add the following dependencies to your Maven project. Always use the latest available version — check alibabacloud-secretsmanager-client-java for the current release.
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>alibabacloud-secretsmanager-client</artifactId>
<version>1.4.x</version>
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-core</artifactId>
<version>4.5.x</version>
</dependency>Python
# If this command fails, use pip3 instead
pip install aliyun-secret-manager-clientFor source code and release notes, see aliyun-secretsmanager-client-python.
Go
go get -u github.com/aliyun/aliyun-secretsmanager-client-goThe alibaba-cloud-sdk-go version that this client depends on must be earlier than v1.63.0. Check the go.mod file of the client to confirm the required version before installing.
For source code and release notes, see aliyun-secretsmanager-client-go.
Step 3: Initialize the client and retrieve a secret value
All three initialization methods produce a SecretCacheClient that you use the same way: call getSecretInfo("<secretName>") to retrieve the cached value.
Java
Method 3: Inline parameters (AccessKey only)
Use this method when authenticating with an AccessKey and you prefer to pass credentials programmatically. Store credentials in environment variables, not in code.
Replace <regionId> with your region ID and <secretName> with your secret name.
import com.aliyuncs.kms.secretsmanager.client.SecretCacheClient;
import com.aliyuncs.kms.secretsmanager.client.SecretCacheClientBuilder;
import com.aliyuncs.kms.secretsmanager.client.exception.CacheSecretException;
import com.aliyuncs.kms.secretsmanager.client.model.SecretInfo;
import com.aliyuncs.kms.secretsmanager.client.service.BaseSecretManagerClientBuilder;
import com.aliyuncs.kms.secretsmanager.client.utils.CredentialsProviderUtils;
public class CacheClientSimpleParametersSample {
public static void main(String[] args) {
try {
SecretCacheClient client = SecretCacheClientBuilder.newCacheClientBuilder(
BaseSecretManagerClientBuilder.standard()
.withCredentialsProvider(CredentialsProviderUtils.withAccessKey(
System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"),
System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")))
.withRegion("<regionId>")
.build())
.build();
SecretInfo secretInfo = client.getSecretInfo("<secretName>");
System.out.println(secretInfo);
} catch (CacheSecretException e) {
e.printStackTrace();
}
}
}Python
Method 1: Environment variables or secretsmanager.properties (recommended)
Configure environment variables or a secretsmanager.properties file using the same parameters shown in the Java section above. The Python client reads the same parameter names.
For instructions on setting environment variables, see Configure environment variables.
On Linux, escape the JSON brackets when using export: [{\"regionId\":\"<your-region-id>\"}]
Sample code
Replace <secretName> with your secret name.
from alibaba_cloud_secretsmanager_client.secret_manager_cache_client_builder import SecretManagerCacheClientBuilder
if __name__ == '__main__':
# Build the secret client (reads config from environment variables or secretsmanager.properties)
secret_cache_client = SecretManagerCacheClientBuilder.new_client()
# Retrieve the cached secret value
secret_info = secret_cache_client.get_secret_info("<secretName>")
print(secret_info.__dict__)Method 2: Inline parameters (AccessKey only)
Store your AccessKey in environment variables, then pass them explicitly at client construction time.
Replace <regionId> with your region ID and <secretName> with your secret name.
import os
from alibaba_cloud_secretsmanager_client.secret_manager_cache_client_builder import SecretManagerCacheClientBuilder
from alibaba_cloud_secretsmanager_client.service.default_secret_manager_client_builder import DefaultSecretManagerClientBuilder
if __name__ == '__main__':
secret_cache_client = (
SecretManagerCacheClientBuilder
.new_cache_client_builder(
DefaultSecretManagerClientBuilder.standard()
.with_access_key(
os.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"),
os.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"))
.with_region("<regionId>")
.build())
.build()
)
secret_info = secret_cache_client.get_secret_info("<secretName>")
print(secret_info.__dict__)Go
Method 1: Environment variables or secretsmanager.properties (recommended)
Configure environment variables or a secretsmanager.properties file using the same parameters shown in the Java section above.
On Linux, escape the JSON brackets when using export: [{\"regionId\":\"<your-region-id>\"}]
Sample code
Replace <secretName> with your secret name.
package main
import (
"fmt"
"github.com/aliyun/aliyun-secretsmanager-client-go/sdk"
)
func main() {
// Build the secret client (reads config from environment variables or secretsmanager.properties)
client, err := sdk.NewClient()
if err != nil {
panic(err)
}
// Retrieve the cached secret value
secretInfo, err := client.GetSecretInfo("<secretName>")
if err != nil {
panic(err)
}
fmt.Printf("SecretValue:%s\n", secretInfo.SecretValue)
}Method 2: Inline parameters (AccessKey only)
Replace <regionId> with your region ID and <secretName> with your secret name.
package main
import (
"github.com/aliyun/aliyun-secretsmanager-client-go/sdk"
"github.com/aliyun/aliyun-secretsmanager-client-go/sdk/service"
"os"
)
func main() {
client, err := sdk.NewSecretCacheClientBuilder(
service.NewDefaultSecretManagerClientBuilder().
Standard().
WithAccessKey(
os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"),
os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")).
WithRegion("<regionId>").
Build()).
Build()
if err != nil {
panic(err)
}
secretInfo, err := client.GetSecretInfo("<secretName>")
if err != nil {
panic(err)
}
}Get a secret value through the dedicated gateway (not recommended)
The dedicated gateway uses the KMS private network and requires ClientKey as the only authentication method.
Step 1: Create a ClientKey
Two creation methods are available:
Method 1: Quick creation — suitable for testing and development. Uses a default permission policy granting access to all keys and secrets in the specified KMS instance. The policy cannot be modified.
Method 2: Standard creation — use this method for production to configure fine-grained access permissions.
Method 1: Quick creation
In the KMS console, click Application Access > Multi-Cloud Access (formerly AAP) in the left navigation pane.
On the Application Access tab, click Create AAP and configure the following parameters:
Parameter Value Mode Select Quick Creation Scope (KMS Instance) Select the KMS instance to access Application Access Point Name Enter a name for the application access point (AAP) Authentication Method ClientKey (default, cannot be changed) Default Permission Policy key/*secret/*(default, cannot be changed)Click OK. The browser automatically downloads two files:
`clientKey_**.json` — contains the Application Access Secret (ClientKeyContent)**
`clientKey_**_Password.txt` — contains the Password**
ImportantSave both files immediately. They are only available at creation time. If you lose them, create a new ClientKey in the AAP.
Method 2: Standard creation
Follow the standard creation steps. When configuring parameters, set Network Type to Private and set the permission scope to the specific KMS Instance ID.
Step 2: Install the secret client
The installation commands are the same as for the shared gateway. See Step 2: Install the secret client above.
Step 3: Initialize the client and retrieve a secret value
The dedicated gateway uses cache_client_dkms_config_info instead of cache_client_region_id. This parameter accepts a JSON array, so you can configure multiple KMS instances for higher availability.
cache_client_dkms_config_info parameters:
| Parameter | Description | Where to find it |
|---|---|---|
regionId | Region ID of the KMS instance | See Regions and zones |
endpoint | Domain name of the KMS instance, in the format {instanceId}.kms.aliyuncs.com | Instances page > instance details > Instance VPC Endpoint |
clientKeyFile | Absolute or relative path to the ClientKey JSON file (clientKey_****.json) | Downloaded when you created the ClientKey |
passwordFromEnvVariable | Name of the environment variable that stores the ClientKey password | Set by you; mutually exclusive with passwordFromFilePath |
passwordFromFilePath | Absolute or relative path to the password file (clientKey_****_Password.txt) | Downloaded when you created the ClientKey; mutually exclusive with passwordFromEnvVariable |
ignoreSslCerts | Whether to skip SSL certificate validation. Set to false in production. | — |
caFilePath | Absolute or relative path to the KMS instance CA certificate | Instances page > instance details > Download in the Instance CA Certificate section |
In production, always set ignoreSslCerts to false. When ignoreSslCerts is false, caFilePath is required.
Java
Method 1: Environment variables or secretsmanager.properties
Method 2: Custom configuration file
Replace <customConfigFileName> with your configuration file name and <secretName> with your secret name.
import com.aliyuncs.kms.secretsmanager.client.SecretCacheClient;
import com.aliyuncs.kms.secretsmanager.client.SecretCacheClientBuilder;
import com.aliyuncs.kms.secretsmanager.client.exception.CacheSecretException;
import com.aliyuncs.kms.secretsmanager.client.model.SecretInfo;
import com.aliyuncs.kms.secretsmanager.client.service.BaseSecretManagerClientBuilder;
public class CacheClientCustomConfigFileSample {
public static void main(String[] args) {
try {
SecretCacheClient client = SecretCacheClientBuilder.newCacheClientBuilder(
BaseSecretManagerClientBuilder.standard()
.withCustomConfigFile("<customConfigFileName>")
.build())
.build();
SecretInfo secretInfo = client.getSecretInfo("<secretName>");
System.out.println(secretInfo);
} catch (CacheSecretException e) {
System.out.println("CacheSecretException:" + e.getMessage());
}
}
}Method 3: Inline parameters (AccessKey only)
Replace <regionId> with your region ID and <secretName> with your secret name.
import com.aliyuncs.kms.secretsmanager.client.SecretCacheClient;
import com.aliyuncs.kms.secretsmanager.client.SecretCacheClientBuilder;
import com.aliyuncs.kms.secretsmanager.client.exception.CacheSecretException;
import com.aliyuncs.kms.secretsmanager.client.model.SecretInfo;
import com.aliyuncs.kms.secretsmanager.client.service.BaseSecretManagerClientBuilder;
import com.aliyuncs.kms.secretsmanager.client.utils.CredentialsProviderUtils;
public class CacheClientSimpleParametersSample {
public static void main(String[] args) {
try {
SecretCacheClient client = SecretCacheClientBuilder.newCacheClientBuilder(
BaseSecretManagerClientBuilder.standard()
.withCredentialsProvider(CredentialsProviderUtils.withAccessKey(
System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"),
System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")))
.withRegion("<regionId>")
.build())
.build();
SecretInfo secretInfo = client.getSecretInfo("<secretName>");
System.out.println(secretInfo);
} catch (CacheSecretException e) {
e.printStackTrace();
}
}
}Python
Method 1: Environment variables or secretsmanager.properties
Set cache_client_dkms_config_info using environment variables or a secretsmanager.properties file, using the same JSON format shown in the Java section above.
Sample code
Replace <secretName> with your secret name.
from alibaba_cloud_secretsmanager_client.secret_manager_cache_client_builder import SecretManagerCacheClientBuilder
if __name__ == '__main__':
# Build the secret client
secret_cache_client = SecretManagerCacheClientBuilder.new_client()
# Retrieve the cached secret value
secret_info = secret_cache_client.get_secret_info("<secretName>")
print(secret_info.__dict__)Method 2: Inline parameters (AccessKey only)
Replace <regionId> with your region ID and <secretName> with your secret name.
import os
from alibaba_cloud_secretsmanager_client.secret_manager_cache_client_builder import SecretManagerCacheClientBuilder
from alibaba_cloud_secretsmanager_client.service.default_secret_manager_client_builder import DefaultSecretManagerClientBuilder
if __name__ == '__main__':
secret_cache_client = (
SecretManagerCacheClientBuilder
.new_cache_client_builder(
DefaultSecretManagerClientBuilder.standard()
.with_access_key(
os.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"),
os.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"))
.with_region("<regionId>")
.build())
.build()
)
secret_info = secret_cache_client.get_secret_info("<secretName>")
print(secret_info.__dict__)Go
Method 1: Environment variables or secretsmanager.properties
Set cache_client_dkms_config_info using environment variables or a secretsmanager.properties file, using the same JSON format shown in the Java section above.
Sample code
Replace <secretName> with your secret name.
package main
import (
"fmt"
"github.com/aliyun/aliyun-secretsmanager-client-go/sdk"
)
func main() {
// Build the secret client
client, err := sdk.NewClient()
if err != nil {
panic(err)
}
// Retrieve the cached secret value
secretInfo, err := client.GetSecretInfo("<secretName>")
if err != nil {
panic(err)
}
fmt.Printf("SecretValue:%s\n", secretInfo.SecretValue)
}Method 2: Inline parameters (AccessKey only)
Replace <regionId> with your region ID and <secretName> with your secret name.
package main
import (
"github.com/aliyun/aliyun-secretsmanager-client-go/sdk"
"github.com/aliyun/aliyun-secretsmanager-client-go/sdk/service"
"os"
)
func main() {
client, err := sdk.NewSecretCacheClientBuilder(
service.NewDefaultSecretManagerClientBuilder().
Standard().
WithAccessKey(
os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"),
os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")).
WithRegion("<regionId>").
Build()).
Build()
if err != nil {
panic(err)
}
secretInfo, err := client.GetSecretInfo("<secretName>")
if err != nil {
panic(err)
}
}What's next
SDK reference — use the KMS instance SDK or Alibaba Cloud SDK for credential management operations
System policies for KMS — configure the minimum required permissions
Create an application access point — full AAP setup instructions