The Secrets Manager Client is a custom wrapper built on top of KMS OpenAPI and KMS instance APIs. It provides built-in secret caching and refresh capabilities for application integration, improving business stability and simplifying developer workflows. The client supports retrieving secret values for all secret types.
Secrets Manager Client SDK
The Secrets Manager Client SDK wraps KMS APIs and incorporates best practices and design patterns for secret caching, making it easier to integrate secret management into your application systems. The SDK provides the following advantages:
Integrate secret management into your applications with a single line of code to read secret values.
Built-in secret caching and refresh functionality within your application.
Automatic retry logic for API errors, with intelligent handling of server-side errors.
Plugin-based architecture that allows you to customize caching, retry logic, and other modules.
Alibaba Cloud also provides the KMS Instance SDK and the Alibaba Cloud SDK, which can also be used to retrieve secret values. For more information, see SDK references.
To perform management operations on secrets, you must use the Alibaba Cloud SDK.
SDK versions
SDK 2.0 is now available. We recommend using SDK 2.0. The following table compares SDK 1.0 and SDK 2.0.
Credential Support
Credential Type
SDK 1.0
SDK 2.0
AccessKey
OIDC Role Arn
ECS RAM Role
RAM Role Arn
NoteThe SDK 2.0 does not support reading RAM Role ARN information from default environment variables and configuration files. You must use the hard-coded approach. If you need this feature, contact technical support.
Client Key
Security Features
Feature
SDK 1.0
SDK 2.0
Built-in CA Certificate
SDK authentication flow
The Secrets Manager Client authenticates using access credentials. The authentication process varies slightly depending on the gateway type you connect to. The SDK automatically detects the configured parameters and selects the appropriate gateway. With this flexible authentication mechanism, you do not need to manually configure the gateway type. The authentication steps are as follows:
Set environment variables or prepare the configuration file, ensuring that all necessary credential information is included. Parameters differ between dedicated gateways and shared gateways.
Initialize the client. The SDK automatically reads the configuration and identifies the gateway type.
After authentication completes, you can proceed with gateway operations.
Scope
Supported secret types: generic secret, RAM secret, ECS secret, database secret.
Supported programming languages: Java (Java 8 or later), Python, Go, Node.js.
Install the Secrets Manager Client
The following instructions show how to install SDK 2.0. For SDK 1.0 installation, refer to the respective SDK source code repositories.
Java
Install the Secrets Manager Client in your project using Maven.
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>alibabacloud-secretsmanager-client-v2</artifactId>
<version>x.x.x</version>
</dependency>
Use the latest version of SDK 2.0 for the latest features and optimizations. Visit alibabacloud-secretsmanager-client-java-v2 for SDK 2.0 sample code and source code. For SDK 1.0, visit alibabacloud-secretsmanager-client-java.
Python
Install the Secrets Manager Client using pip.
# If the following command fails, replace pip with pip3
pip install alibabacloud_secretsmanager_client_v2
Installing the Secrets Manager Client Python SDK V2 requires Python 3.7 or later. Run
python3 --versionto check your current version. If your version is below 3.7, upgrade Python before running the installation command.Use SDK 2.0 for the latest features and optimizations. Visit aliyun-secretsmanager-client-python-v2 for SDK 2.0 sample code and source code. For SDK 1.0, visit aliyun-secretsmanager-client-python.
Go
Install the Secrets Manager Client using the go get command.
go get -u github.com/aliyun/alibabacloud-secretsmanager-client-go-v2 For Go, the
alibaba-cloud-sdk-godependency must be earlier than V1.63.0. Check yourgo.modfile to confirm the version and avoid compatibility issues.Use SDK 2.0 for the latest features and optimizations. Visit alibabacloud-secretsmanager-client-go-v2 for SDK 2.0 sample code and source code. For SDK 1.0, visit aliyun-secretsmanager-client-go.
Node.js
Install the Secrets Manager Client using npm or yarn.
npm
npm install alibabacloud-secretsmanager-client-v2yarn
yarn add alibabacloud-secretsmanager-client-v2
Installing the Secrets Manager Client SDK V2 requires Node.js 16.0.0 or later.
Use SDK 2.0 for the latest features and optimizations. Visit alibabacloud-secretsmanager-client-nodejs-v2 for SDK 2.0 sample code and source code.
Configure access credentials
ECS RAM Role
Step 1: Create a RAM role and configure permissions
An ECS instance RAM role allows you to obtain a temporary access credential (STS token) from within an ECS instance to call KMS API operations, without needing to configure an AccessKey pair.
For more information, see Instance RAM roles.
Log on to the RAM console and create a RAM role for a trusted Alibaba Cloud service.
Trusted Entity Type: Select Elastic Compute Service.
Trusted entity: Select Elastic Compute Service (ECS).
Grant the RAM role permissions to access KMS.
Method 1: Configure an identity-based policy
In the Actions column of the RAM role, click Grant Permission to attach a built-in system permission policy for KMS to the RAM role. For more information about the system permission policies for KMS, see System policies for KMS.
NoteYou can also create custom permission policies. For more information, see Create a custom policy.
Method 2: Configure a resource-based policy
KMS supports resource-based policies that grant access permissions for individual keys and secrets. You can use these policies to control which Alibaba Cloud accounts, RAM users, and RAM roles can manage or use KMS keys and secrets. For more information, see Key policies and Secret policies.
Log on to the ECS console and attach the RAM role to an ECS instance.

Step 2: Set environment variables or configuration file
The SDK supports the following two methods to obtain access credentials:
Environment variables: Configuration methods vary by operating system. For more information, see .
WarningDo not modify the parameter names. Otherwise, the SDK cannot recognize them.
Configuration file: The default configuration file is
secretsmanager.properties(the file name cannot be changed).To ensure your application loads the configuration file correctly, place it in the appropriate configuration directory. Common configuration directories for different languages include:Java: Place the configuration file in the
src/main/resourcesdirectory so it is automatically included in the classpath during compilation.Go: Place the configuration file in the project root directory or a dedicated
configdirectory, then load it through code.Python: Place the configuration file in the project directory or a specific
configdirectory, and use an appropriate method (such asos.pathorpkg_resources) to load it.
If you use a custom configuration file, you must specify the file path (
#customConfigFileName#) during client initialization.
Configuration file
Dedicated gateway
# Credential type credentials_type=ecs_ram_role # ECS RAM Role name credentials_role_name=#credentials_role_name# # Associated KMS region and instance endpoint cache_client_region_id=[{"regionId":"<regionId>","endpoint":"<your_kms_instance_id>.cryptoservice.kms.aliyuncs.com"}]Shared gateway
# Credential type credentials_type=ecs_ram_role # ECS RAM Role name credentials_role_name=#credentials_role_name# # Associated KMS region cache_client_region_id=[{"regionId":"#regionId#"}]Shared gateway (VPC)
# Credential type credentials_type=ecs_ram_role # ECS RAM Role name credentials_role_name=#credentials_role_name# # Associated KMS region and VPC Endpoint cache_client_region_id=[{"regionId":"#regionId#","endpoint":"kms-vpc.#regionId#.aliyuncs.com","vpc":"true"}]
Environment variables
Parameter | Value |
| Fixed value: |
| The name of the RAM role. |
|
|
AccessKey
Step 1: Create an AccessKey and configure permissions
By default, an Alibaba Cloud account has administrator permissions for all resources, which cannot be modified. To ensure resource security, we recommend that you use a RAM user to create an AccessKey pair and grant it only the necessary permissions.
Log on to the RAM console. On the Users page, click the name of the target RAM user.
On the Authentication tab, in the AccessKey section, click Create AccessKey and follow the on-screen instructions.
Grant the RAM user permissions to access KMS.
Method 1: Configure an identity-based policy
In the Actions column of the RAM user, click Grant Permission to attach a built-in system permission policy for KMS to the RAM user. For more information about the system permission policies for KMS, see System policies for KMS.
NoteYou can also create custom permission policies. For more information, see Create a custom policy.
Method 2: Configure a resource-based policy
KMS supports resource-based policies that grant access permissions for individual keys and secrets. You can use these policies to control which Alibaba Cloud accounts, RAM users, and RAM roles can manage or use KMS keys and secrets. For more information, see Key policies and Secret policies.
Step 2: Set environment variables or configuration file
The SDK supports the following two methods to obtain access credentials:
Environment variables: Configuration methods vary by operating system. For more information, see .
WarningDo not modify the parameter names. Otherwise, the SDK cannot recognize them.
Configuration file: The default configuration file is
secretsmanager.properties(the file name cannot be changed).To ensure your application loads the configuration file correctly, place it in the appropriate configuration directory. Common configuration directories for different languages include:Java: Place the configuration file in the
src/main/resourcesdirectory so it is automatically included in the classpath during compilation.Go: Place the configuration file in the project root directory or a dedicated
configdirectory, then load it through code.Python: Place the configuration file in the project directory or a specific
configdirectory, and use an appropriate method (such asos.pathorpkg_resources) to load it.
If you use a custom configuration file, you must specify the file path (
#customConfigFileName#) during client initialization.
Configuration File
Dedicated gateway
# Credential type credentials_type=ak # AccessKey ID credentials_access_key_id=#access_key_id# # AccessKey Secret credentials_access_secret=#access_key_secret# # Use the following configuration for dedicated KMS instance gateway cache_client_region_id=[{"regionId":"<regionId>","endpoint":"<your_kms_instance_id>.cryptoservice.kms.aliyuncs.com"}]# Credential type credentials_type=ak # AccessKey ID credentials_access_key_id=#access_key_id# # AccessKey Secret credentials_access_secret=#access_key_secret# # Associated KMS region cache_client_region_id=[{"regionId":"#regionId#"}]Shared gateway (VPC)
# Credential type credentials_type=ak # AccessKey ID credentials_access_key_id=#access_key_id# # AccessKey Secret credentials_access_secret=#access_key_secret# # Associated KMS region and VPC Endpoint cache_client_region_id=[{"regionId":"#regionId#","endpoint":"kms-vpc.#regionId#.aliyuncs.com","vpc":"true"}]
Environment variables
Parameter | Value |
| Fixed value: |
| The AccessKey ID. |
| The AccessKey Secret. |
|
|
OIDC Role ARN
Only SDK 2.0 supports OIDC Role ARN credentials. SDK 1.0 does not.
Step 1: Create an OIDC role ARN and configure permissions
Create an OIDC provider
Log on to the RAM console as a RAM administrator. On the SSO page, click the Role-based SSO tab.
On the OIDC tab, click Create IdP.
On the Create IdP page, configure the provider information. For more information, see Manage OIDC providers.
Obtain and save the OIDC identity information (ARN and Client ID)
Go to the SSO page, and on the IdP tab, click the name of the target OIDC provider.
On the IdP details page, you can view the ARN and Client ID.
Create and authorize a RAM role for the OIDC provider
Log on to the RAM console as a RAM administrator and go to the page.
Click Create Role. In the upper-right corner of the creation page, click Switch to Policy Editor.
In the policy editor, specify the OIDC provider. Select the visual editor and configure the parameters as described below.
NoteFor information about other modes, see Create a RAM role for an OIDC provider.
In the Select Trusted Entity section, select IdP.
In the Edit Trust Policy section, configure the following parameters.
IdP Type: Select OIDC.
IdP: Select the OIDC provider you created earlier.
Grant the OIDC RAM role permissions to access KMS
Method 1: Configure an identity-based policy
Return to the Identities > Roles list page and click Grant Permission in the Actions column of the target OIDC role to directly attach a KMS built-in system permission policy to the RAM role. For more information about KMS built-in system permission policies, see Key Management Service System Permission Policy Reference.
NoteCustom permission policies are also supported. For more information, see Create a custom permission policy.
Method 2: Configure a resource-based policy
KMS supports resource-based policies that grant access permissions for individual keys and secrets. You can use these policies to control which Alibaba Cloud accounts, RAM users, and RAM roles can manage or use KMS keys and secrets. For more information, see Key policies and Secret policies.
Obtain the target OIDC Role ARN
On the page, click the name of the target role.
On the role details page, find the OIDC Role ARN in the ARN section.
NoteThe Role ARN is the ARN of the RAM role to be assumed. The format is
acs:ram::$accountID:role/$roleName, where$accountIDis the Alibaba Cloud account ID and$roleNameis the RAM role name.
Issue and save the OIDC token file
Alibaba Cloud does not support direct OIDC login from the console, but you can complete the OIDC SSO process programmatically. Obtaining an OIDC token involves an OAuth flow, commonly through a standard OAuth 2.0 process from the OIDC identity provider (IdP).
For example:when an application runs in an ACK cluster with RRSA enabled, the cluster automatically creates and mounts the corresponding service account OIDC token file for the application pod.
Step 2: Set environment variables or configuration file
The SDK supports the following two methods to obtain access credentials:
Environment variables: Configuration methods vary by operating system. For more information, see .
WarningDo not modify the parameter names. Otherwise, the SDK cannot recognize them.
Configuration file: The default configuration file is
secretsmanager.properties(the file name cannot be changed).To ensure your application loads the configuration file correctly, place it in the appropriate configuration directory. Common configuration directories for different languages include:Java: Place the configuration file in the
src/main/resourcesdirectory so it is automatically included in the classpath during compilation.Go: Place the configuration file in the project root directory or a dedicated
configdirectory, then load it through code.Python: Place the configuration file in the project directory or a specific
configdirectory, and use an appropriate method (such asos.pathorpkg_resources) to load it.
If you use a custom configuration file, you must specify the file path (
#customConfigFileName#) during client initialization.
Configuration file
Dedicated gateway
# Credential type credentials_type=oidc_role_arn # Role ARN (optional. If not specified, the Default credential provider chain is used) credentials_role_arn=<role_arn> # OIDC provider ARN (optional. If not specified, the Default credential provider chain is used) credentials_oidc_provider_arn=<oidc_provider_arn> # OIDC token file path (optional. If not specified, the Default credential provider chain is used) credentials_oidc_token_file_path=<oidc_token_file_path> # KMS region and instance endpoint cache_client_region_id=[{"regionId":"<regionId>","endpoint":"<your_kms_instance_id>.cryptoservice.kms.aliyuncs.com"}]# Credential type credentials_type=oidc_role_arn # Role ARN (optional. If not specified, the Default credential provider chain is used) credentials_role_arn=<role_arn> # OIDC provider ARN (optional. If not specified, the Default credential provider chain is used) credentials_oidc_provider_arn=<oidc_provider_arn> # OIDC token file path (optional. If not specified, the Default credential provider chain is used) credentials_oidc_token_file_path=<oidc_token_file_path> # Associated KMS region cache_client_region_id=[{"regionId":"<regionId>"}]Shared gateway (VPC)
# Credential type credentials_type=oidc_role_arn # Role ARN (optional. If not specified, the Default credential provider chain is used) credentials_role_arn=<role_arn> # OIDC provider ARN (optional. If not specified, the Default credential provider chain is used) credentials_oidc_provider_arn=<oidc_provider_arn> # OIDC token file path (optional. If not specified, the Default credential provider chain is used) credentials_oidc_token_file_path=<oidc_token_file_path> # Associated KMS region and VPC Endpoint cache_client_region_id=[{"regionId":"#regionId#","endpoint":"kms-vpc.#regionId#.aliyuncs.com","vpc":"true"}]
Environment variables
Parameter | Value |
| Fixed value: |
| The ARN of the RAM role for the OIDC identity provider. Optional. If not specified, the Default credential provider chain is used. |
| The ARN of the OIDC identity provider. Optional. If not specified, the Default credential provider chain is used. |
| The relative or absolute path to the file that stores the OIDC token. Optional. If not specified, the Default credential provider chain is used. |
|
|
AK+RamRoleArn
Only SDK 1.0 supports reading RAM Role ARN information from default environment variables and configuration files. SDK 2.0 does not. If you need this feature with SDK 2.0, contact technical support.
Step 1: Create a RAM role ARN and configure permissions
RAM users or cloud services can assume a role to obtain temporary permissions (STS token) instead of using long-term keys, which reduces the risk of key leaks. For example, in a temporary data processing task, a RAM user or cloud service temporarily assumes a role with a specific RamRoleArn. After the task is complete, the role permissions are revoked, minimizing the risk of exposure.
Create a user AccessKey pair
Log on to the RAM console. In the left-side navigation pane, choose . On the Users page, click the name of the target RAM user.
Attach the
AliyunSTSAssumeRoleAccesssystem policy or a custom policy that includes thests:AssumeRoleaction to the RAM user.On the Authentication tab, in the AccessKey section, click Create AccessKey and follow the on-screen instructions.
Create and authorize a RAM role:
In the left-side navigation pane, choose . On the Roles page, click Create Role. For more information, see Create a RAM role.
Grant the RAM role permissions to access KMS.
Method 1: Configure an identity-based policy
In the Actions column of the RAM role, click Grant Permission to attach a built-in system permission policy for KMS to the RAM role. For more information about the system permission policies for KMS, see System policies for KMS.
NoteYou can also create custom permission policies. For more information, see Create a custom policy.
Method 2: Configure a resource-based policy
KMS supports resource-based policies that grant access permissions for individual keys and secrets. You can use these policies to control which Alibaba Cloud accounts, RAM users, and RAM roles can manage or use KMS keys and secrets. For more information, see Key policies and Secret policies.
Obtain the RamRoleArn of the target RAM role. For more information, see View the information about a RAM role.
In the left-side navigation pane, choose . On the Roles page, click the name of the target role.
On the role details page, find the RamRoleArn in the ARN section.
NoteThe RamRoleArn is the Alibaba Cloud Resource Name (ARN) of the RAM role to assume. The format is
acs:ram::$accountID:role/$roleName, where$accountIDis the Alibaba Cloud account ID and$roleNameis the RAM role name.
Step 2: Set environment variables or configuration file
The SDK supports the following two methods to obtain access credentials:
Environment variables: Configuration methods vary by operating system. For more information, see .
WarningDo not modify the parameter names. Otherwise, the SDK cannot recognize them.
Configuration file: The default configuration file is
secretsmanager.properties(the file name cannot be changed).To ensure your application loads the configuration file correctly, place it in the appropriate configuration directory. Common configuration directories for different languages include:Java: Place the configuration file in the
src/main/resourcesdirectory so it is automatically included in the classpath during compilation.Go: Place the configuration file in the project root directory or a dedicated
configdirectory, then load it through code.Python: Place the configuration file in the project directory or a specific
configdirectory, and use an appropriate method (such asos.pathorpkg_resources) to load it.
If you use a custom configuration file, you must specify the file path (
#customConfigFileName#) during client initialization.
Configuration File
Dedicated Gateway
# Credential type credentials_type=ram_role # Role session name credentials_role_session_name=#role_session_name# # Role ARN credentials_role_arn=#role_arn# # AccessKey ID credentials_access_key_id=#access_key_id# # AccessKey Secret credentials_access_secret=#access_key_secret# # Use the following configuration for dedicated KMS instance gateway cache_client_region_id=[{"regionId":"<regionId>","endpoint":"<your_kms_instance_id>.cryptoservice.kms.aliyuncs.com"}]# Credential type credentials_type=ram_role # Role session name credentials_role_session_name=#role_session_name# # Role ARN credentials_role_arn=#role_arn# # AccessKey ID credentials_access_key_id=#access_key_id# # AccessKey Secret credentials_access_secret=#access_key_secret# # Associated KMS region cache_client_region_id=[{"regionId":"#regionId#"}]Shared gateway (VPC)
# Credential type credentials_type=ram_role # Role session name credentials_role_session_name=#role_session_name# # Role ARN credentials_role_arn=#role_arn# # AccessKey ID credentials_access_key_id=#access_key_id# # AccessKey Secret credentials_access_secret=#access_key_secret# # Associated KMS region and VPC Endpoint cache_client_region_id=[{"regionId":"#regionId#","endpoint":"kms-vpc.#regionId#.aliyuncs.com","vpc":"true"}]
Environment variables
Parameter | Value |
|
|
| The name of the RAM role session. |
| The ARN of the RAM role. |
| The AccessKey ID. |
| The AccessKey Secret. |
|
|
ClientKey (Deprecated)
Only SDK 1.0 supports the ClientKey credential type. SDK 2.0 does not.
Shared gateway
Dedicated gateway
Step 1: Create a ClientKey
You can create a ClientKey by using either Quick Create or Standard Create mode. For more information about ClientKeys, see Application access points and Create an application access point.
Method 1: Quick Create
This method is convenient and efficient, making it suitable for rapid testing and development. The access credential created this way has full access to all resources in the KMS instance.
Log on to the Key Management Service console. In the top navigation bar, select a region. In the left-side navigation pane, choose .
On the Application Access tab, click Create AAP. In the Create AAP panel, configure the parameters.
Parameter
Description
Mode
Select Quick Creation.
Scope (KMS Instance)
Select the KMS instance that your application needs to access.
Application Access Point Name
Enter a name for the application access point.
Authentication Method
This is set to ClientKey and cannot be changed.
Default Permission Policy
The value is
key/*secret/*and cannot be changed. This means the application can access all keys and secrets in the specified KMS instance.Click OK. The browser automatically downloads the ClientKey. The ClientKey includes the following files:
Credential (ClientKeyContent): The default filename is
clientKey_****.json.Credential password (ClientKeyPassword): The default filename is
clientKey_****_Password.txt.
Method 2: Standard Create
If you need to configure fine-grained access permissions for resources, we recommend that you use the Standard Create method.
Follow the Standard Create instructions in Create an application access point to create a ClientKey for accessing the dedicated gateway. The key parameters are described below:
When configuring network rules, select Private for the network type.
When you configure the scope of the permission rule, select the corresponding KMS Instance ID.
After creation, your browser automatically downloads the ClientKey, which includes:
Credential (ClientKeyContent): The file is named
clientKey_****.jsonby default.Credential password (ClientKeyPassword): The file is named
clientKey_****_Password.txtby default.
Step 2: Configure Environment variables or Configuration File
Environment variables: Configuration methods vary by operating system. For more information, see .
WarningDo not modify the parameter names. Otherwise, the SDK cannot recognize them.
Configuration file: The default configuration file is
secretsmanager.properties(the file name cannot be changed).To ensure your application loads the configuration file correctly, place it in the appropriate configuration directory. Common configuration directories for different languages include:Java: Place the configuration file in the
src/main/resourcesdirectory so it is automatically included in the classpath during compilation.Go: Place the configuration file in the project root directory or a dedicated
configdirectory, then load it through code.Python: Place the configuration file in the project directory or a specific
configdirectory, and use an appropriate method (such asos.pathorpkg_resources) to load it.
If you use a custom configuration file, you must specify the file path (
#customConfigFileName#) during client initialization.
Configuration File
Approach 1: Configure the file path
cache_client_dkms_config_info=[{"regionId":"<your_dkms_region_id>","endpoint":"<your_dkms_endpoint>","passwordFromFilePath":"<your_password_file_path>","clientKeyFile":"<your_client_key_file_path>","ignoreSslCerts":false,"caFilePath":"<your_ca_certificate_file_path>"}]
Approach 2: Configure the password via environment variable
cache_client_dkms_config_info=[{"regionId":"<your_dkms_region_id>","endpoint":"<your_dkms_endpoint>","passwordFromEnvVariable":"<YOUR_PASSWORD_ENV_VARIABLE>","clientKeyFile":"<your_client_key_file_path>","ignoreSslCerts":false,"caFilePath":"<your_ca_certificate_file_path>"}]
Environment variables
The SDK supports two approaches to configure the ClientKey credential password:
Approach 1: Configure the file path of the ClientKey password file
Parameter
Value
cache_client_dkms_config_infoFormat:
[{"regionId":"<your_dkms_region_id>","endpoint":"<your_dkms_endpoint>","passwordFromFilePath":"<your_password_file_path>","clientKeyFile":"<your_client_key_file_path>","ignoreSslCerts":false,"caFilePath":"<your_ca_certificate_file_path>"}].Approach 2: Configure the ClientKey password content via environment variable
Parameter
Value
cache_client_dkms_config_infoFormat:
[{"regionId":"<your_dkms_region_id>","endpoint":"<your_dkms_endpoint>","passwordFromEnvVariable":"<YOUR_PASSWORD_ENV_VARIABLE>","clientKeyFile":"<your_client_key_file_path>","ignoreSslCerts":false,"caFilePath":"<your_ca_certificate_file_path>"}].
Parameters of cache_client_dkms_config_info
Parameter | Description |
| The region ID where the KMS instance is deployed. For region IDs, see Regions and zones. |
| The endpoint of the KMS instance, in the format |
| The absolute or relative path to the Credential-ClientKeyContent file ( |
| The absolute or relative path to the ClientKeyPassword file ( |
| The name of the environment variable that stores the ClientKeyPassword content, for example, |
| Specifies whether to skip SSL certificate validation for the KMS instance. The KMS instance has a built-in SSL certificate, used with the SSL/TLS protocol for identity verification and encrypted communication. Valid values:
|
| The absolute or relative path to the KMS instance CA certificate file. Note The CA certificate is used to validate the KMS instance SSL certificate. For more information on how to obtain the CA certificate, see Obtain the KMS instance CA certificate. |
Retrieve secrets
All examples below use SDK 2.0. For SDK 1.0 examples, visit the SDK 1.0 source code repository.
Java
Use default configuration
The SDK automatically reads credential information from the secretsmanager.properties file or environment variables.
import com.aliyuncs.kms.secretsmanager.client.V2.0.SecretCacheClient;
import com.aliyuncs.kms.secretsmanager.client.V2.0.SecretCacheClientBuilder;
import com.aliyuncs.kms.secretsmanager.client.V2.0.exception.CacheSecretException;
import com.aliyuncs.kms.secretsmanager.client.V2.0.model.SecretInfo;
public class CacheClientEnvironmentSample {
public static void main(String[] args) {
try {
SecretCacheClient client = SecretCacheClientBuilder.newClient();
SecretInfo secretInfo = client.getSecretInfo("#secretName#");
System.out.println(secretInfo);
} catch (CacheSecretException e) {
e.printStackTrace();
}
}
}
Use custom configuration file
Use this approach when the configuration file does not use the default file name or path. Specify the configuration file path (#customConfigFileName#).
import com.aliyuncs.kms.secretsmanager.client.V2.0.SecretCacheClient;
import com.aliyuncs.kms.secretsmanager.client.V2.0.SecretCacheClientBuilder;
import com.aliyuncs.kms.secretsmanager.client.V2.0.exception.CacheSecretException;
import com.aliyuncs.kms.secretsmanager.client.V2.0.model.SecretInfo;
import com.aliyuncs.kms.secretsmanager.client.V2.0.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());
}
}
}
Use hard-coded credentials
This approach allows you to pass the AccessKey and region information directly during client initialization, without writing the AccessKey to the configuration file or environment variables.
import com.aliyuncs.kms.secretsmanager.client.V2.0.SecretCacheClient;
import com.aliyuncs.kms.secretsmanager.client.V2.0.SecretCacheClientBuilder;
import com.aliyuncs.kms.secretsmanager.client.V2.0.exception.CacheSecretException;
import com.aliyuncs.kms.secretsmanager.client.V2.0.model.RegionInfo;
import com.aliyuncs.kms.secretsmanager.client.V2.0.service.BaseSecretManagerClientBuilder;
import com.aliyuncs.kms.secretsmanager.client.V2.0.utils.CredentialsProviderUtils;
public class CacheClientWithCaCertificateSample {
public static void main(String[] args) {
try {
// Create a RegionInfo with the CA certificate path
RegionInfo regionInfo = new RegionInfo();
regionInfo.setRegionId("#regionId#");
// Dedicated gateway endpoint. Omit if using shared gateway.
regionInfo.setEndpoint("<your_kms_instance_id>.cryptoservice.kms.aliyuncs.com");
SecretCacheClient client = SecretCacheClientBuilder.newCacheClientBuilder(
BaseSecretManagerClientBuilder.standard()
.withCredentialsProvider(CredentialsProviderUtils.withAccessKey(
System.getenv("#accessKeyId#"),
System.getenv("#accessKeySecret#")))
.addRegion(regionInfo)
.build())
.build();
SecretInfo secretInfo = client.getSecretInfo("#secretName#");
} catch (CacheSecretException e) {
e.printStackTrace();
}
}
}
Use Alibaba Cloud Default credential provider chain
The Default credential provider chain is a fallback strategy. It searches for credentials in a predefined order until credentials are found. If all methods fail, authentication fails and credentials cannot be obtained.
import com.aliyuncs.kms.secretsmanager.client.V2.0.SecretCacheClient;
import com.aliyuncs.kms.secretsmanager.client.V2.0.SecretCacheClientBuilder;
import com.aliyuncs.kms.secretsmanager.client.V2.0.exception.CacheSecretException;
import com.aliyuncs.kms.secretsmanager.client.V2.0.model.SecretInfo;
import com.aliyuncs.kms.secretsmanager.client.V2.0.service.BaseSecretManagerClientBuilder;
public class CacheClientDefaultCredentialChainSample {
public static void main(String[] args) {
try {
SecretCacheClient client = SecretCacheClientBuilder.newCacheClientBuilder(
BaseSecretManagerClientBuilder.standard()
.withRegion("#regionId#")
.build())
.build();
SecretInfo secretInfo = client.getSecretInfo("#secretName#");
System.out.println(secretInfo);
} catch (CacheSecretException e) {
e.printStackTrace();
}
}
}
For more examples, see Secrets Manager Client SDK Examples.
Python
Use default configuration
The SDK automatically reads credential information from the secretsmanager.properties file or environment variables.
from alibabacloud_secretsmanager_client_V2.0.secret_manager_cache_client_builder import SecretManagerCacheClientBuilder
if __name__ == '__main__':
secret_cache_client = SecretManagerCacheClientBuilder.new_client()
secret_info = secret_cache_client.get_secret_info("#secretName#")
print(secret_info.__dict__)
Use custom configuration file
Use this approach when the configuration file does not use the default file name or path.
from alibabacloud_secretsmanager_client_V2.0.secret_manager_cache_client_builder import SecretManagerCacheClientBuilder
from alibabacloud_secretsmanager_client_V2.0.service.default_secret_manager_client_builder import DefaultSecretManagerClientBuilder
if __name__ == '__main__':
secret_cache_client = SecretManagerCacheClientBuilder.new_cache_client_builder(
DefaultSecretManagerClientBuilder.standard()
.with_custom_config_file("#customConfigFileName#")
.build()
).build()
secret_info = secret_cache_client.get_secret_info("#secretName#")
print(secret_info.__dict__)
Use hard-coded credentials
This approach passes the AccessKey and region information directly during client initialization.
import os
from alibabacloud_secretsmanager_client_V2.0.secret_manager_cache_client_builder import SecretManagerCacheClientBuilder
from alibabacloud_secretsmanager_client_V2.0.service.default_secret_manager_client_builder import \
DefaultSecretManagerClientBuilder
from alibabacloud_secretsmanager_client_V2.0.model.region_info import RegionInfo
if __name__ == '__main__':
# Create a RegionInfo with the CA certificate path
region_info = RegionInfo(
region_id="#regionId#",
endpoint="#kmsInstanceEndpoint#", # Dedicated gateway endpoint. Omit if using shared gateway.
)
secret_cache_client = SecretManagerCacheClientBuilder.new_cache_client_builder(
DefaultSecretManagerClientBuilder.standard()
.with_access_key(
os.getenv("#accessKeyId#"),
os.getenv("#accessKeySecret#")
)
.add_region_info(region_info)
.build()
).build()
# ... use the client
Use Alibaba Cloud Default credential provider chain
from alibabacloud_secretsmanager_client_V2.0.secret_manager_cache_client_builder import SecretManagerCacheClientBuilder
from alibabacloud_secretsmanager_client_V2.0.service.default_secret_manager_client_builder import DefaultSecretManagerClientBuilder
if __name__ == '__main__':
secret_cache_client = SecretManagerCacheClientBuilder.new_cache_client_builder(
DefaultSecretManagerClientBuilder.standard()
.with_region("#regionId#")
.build()
).build()
secret_info = secret_cache_client.get_secret_info("#secretName#")
print(secret_info.__dict__)
For more examples, see Secrets Manager Client SDK Examples.
Go
Use default configuration
package main
import "github.com/aliyun/alibabacloud-secretsmanager-client-go-V2.0/sdk"
func main() {
client, err := sdk.NewClient()
if err != nil {
// Handle exceptions
panic(err)
}
secretInfo, err := client.GetSecretInfo("#secretName#")
if err != nil {
// Handle exceptions
panic(err)
}
}
Use custom configuration file
package main
import (
"github.com/aliyun/alibabacloud-secretsmanager-client-go-V2.0/sdk"
"github.com/aliyun/alibabacloud-secretsmanager-client-go-V2.0/sdk/service"
)
func main() {
client, err := sdk.NewSecretCacheClientBuilder(
service.NewDefaultSecretManagerClientBuilder().Standard().
WithCustomConfigFile("#customConfigFileName#").Build()).Build()
if err != nil {
// Handle exceptions
panic(err)
}
secretInfo, err := client.GetSecretInfo("#secretName#")
if err != nil {
// Handle exceptions
panic(err)
}
}
Use hard-coded credentials
package main
import (
"github.com/aliyun/alibabacloud-secretsmanager-client-go-V2.0/sdk"
"github.com/aliyun/alibabacloud-secretsmanager-client-go-V2.0/sdk/models"
"github.com/aliyun/alibabacloud-secretsmanager-client-go-V2.0/sdk/service"
"os"
)
func main() {
regionInfo := &models.RegionInfo{
RegionId: "#regionId#",
// Dedicated gateway endpoint. Omit if using shared gateway.
Endpoint: "<kmsInstanceId>.cryptoservice.kms.aliyuncs.com",
}
client, err := sdk.NewSecretCacheClientBuilder(
service.NewDefaultSecretManagerClientBuilder().
Standard().
WithAccessKey(os.Getenv("#accessKeyId#"), os.Getenv("#accessKeySecret#")).
AddRegionInfo(regionInfo).
Build()).Build()
if err != nil {
// Handle exceptions
panic(err)
}
secretInfo, err := client.GetSecretInfo("#secretName#")
if err != nil {
// Handle exceptions
panic(err)
}
}
Use Alibaba Cloud Default credential provider chain
package main
import (
"github.com/aliyun/alibabacloud-secretsmanager-client-go-V2.0/sdk"
"github.com/aliyun/alibabacloud-secretsmanager-client-go-V2.0/sdk/service"
)
func main() {
client, err := sdk.NewSecretCacheClientBuilder(
service.NewDefaultSecretManagerClientBuilder().Standard().
WithRegion("#regionId#").Build()).Build()
if err != nil {
// Handle exceptions
panic(err)
}
secretInfo, err := client.GetSecretInfo("#secretName#")
if err != nil {
// Handle exceptions
panic(err)
}
}
For more examples, see Secrets Manager Client SDK Examples.
Node.js
Use default configuration
The SDK automatically reads credential information from the secretsmanager.properties file or environment variables.
import { SecretCacheClientBuilder } from 'alibabacloud-secretsmanager-client-v2';
async function example() {
try {
// Build client via environment variables or default configuration
const client = await SecretCacheClientBuilder.newClient();
const secretInfo = await client.getSecretInfo('#secretName#');
console.log(secretInfo);
} catch (error) {
console.error('Error:', error);
}
}
example();Use custom configuration file
Use this approach when the configuration file does not use the default file name or path. Specify the configuration file path.
import {
SecretCacheClientBuilder,
BaseSecretManagerClientBuilder,
CredentialsProviderUtils
} from 'alibabacloud-secretsmanager-client-v2';
async function example() {
try {
const client = await SecretCacheClientBuilder.newCacheClientBuilder(
BaseSecretManagerClientBuilder.standard().withCustomConfigFile('#customConfigFileName#').build()
).build();
const secretInfo = await client.getSecretInfo('#secretName#');
console.log(secretInfo);
} catch (error) {
console.error('Error:', error);
}
}
example();Use hard-coded credentials
This approach passes the AccessKey and region information directly during client initialization.
import {
SecretCacheClientBuilder,
BaseSecretManagerClientBuilder,
CredentialsProviderUtils,
RegionInfo
} from 'alibabacloud-secretsmanager-client-v2';
async function example() {
try {
// Create RegionInfo with CA certificate path
const regionInfo = new RegionInfo();
regionInfo.setRegionId('#regionId#');
regionInfo.setEndpoint('#kmsInstanceEndpoint#'); // Specify KMS instance address
const client = await SecretCacheClientBuilder.newCacheClientBuilder(
BaseSecretManagerClientBuilder.standard()
.withCredentialsProvider(
CredentialsProviderUtils.withAccessKey(
process.env['#accessKeyId#'],
process.env['#accessKeySecret#']
)
)
.addRegionInfo(regionInfo) // Use RegionInfo with CA certificate path
.build()
).build();
const secretInfo = await client.getSecretInfo('#secretName#');
console.log(secretInfo);
} catch (error) {
console.error('Error:', error);
}
}
example();Use Alibaba Cloud Default credential provider chain
import {
SecretCacheClientBuilder,
BaseSecretManagerClientBuilder,
CredentialsProviderUtils
} from 'alibabacloud-secretsmanager-client-v2';
async function example() {
try {
const client = await SecretCacheClientBuilder.newCacheClientBuilder(
BaseSecretManagerClientBuilder.standard()
.withCredentialsProvider(CredentialsProviderUtils.withDefaultCredential())
.withRegion('#regionId#')
.build()
).build();
const secretInfo = await client.getSecretInfo('#secretName#');
console.log(secretInfo);
} catch (error) {
console.error('Error:', error);
}
}
example();For more examples, see Secrets Manager Client SDK Examples.
FAQ
What do I do if the error "cannot find the built-in CA certificate for region[$regionId], please provide the caFilePath parameter." appears?
Cause: The built-in CA certificate for the specified region does not exist in the SDK.
Solution:
Update the SDK to the latest V2.0 version.
If the error persists after updating to the latest version, download the latest CA certificate (available on the KMS console under Instance Management > Instance Details), and pass the CA certificate path. You can use any of the following methods:
Pass via environment variable
Add the
caFilePathparameter to thecache_client_region_idconfiguration:# Associated KMS region, including the CA certificate path and instance endpoint cache_client_region_id=[{"regionId":"<regionId>","endpoint":"<kmsInstanceId>.cryptoservice.kms.aliyuncs.com","caFilePath":"<ca_certificate_file_path>"}]Pass via configuration file
Add the
caFilePathparameter tosecretsmanager.propertiesor a custom configuration file:# Associated KMS region, including the CA certificate path and instance endpoint cache_client_region_id=[{"regionId":"<regionId>","endpoint":"<kmsInstanceId>.cryptoservice.kms.aliyuncs.com","caFilePath":"<ca_certificate_file_path>"}]Pass via Hard-coded Credentials
import com.aliyuncs.kms.secretsmanager.client.V2.0.SecretCacheClient; import com.aliyuncs.kms.secretsmanager.client.V2.0.SecretCacheClientBuilder; import com.aliyuncs.kms.secretsmanager.client.V2.0.exception.CacheSecretException; import com.aliyuncs.kms.secretsmanager.client.V2.0.model.RegionInfo; import com.aliyuncs.kms.secretsmanager.client.V2.0.service.BaseSecretManagerClientBuilder; import com.aliyuncs.kms.secretsmanager.client.V2.0.utils.CredentialsProviderUtils; public class CacheClientWithCaCertificateSample { public static void main(String[] args) { try { // Create a RegionInfo with the CA certificate path RegionInfo regionInfo = new RegionInfo(); regionInfo.setRegionId("#regionId#"); regionInfo.setEndpoint("#kmsInstanceEndpoint#"); // Specify KMS instance endpoint regionInfo.setCaFilePath("#caFilePath#"); // Specify CA certificate file path SecretCacheClient client = SecretCacheClientBuilder.newCacheClientBuilder( BaseSecretManagerClientBuilder.standard() .withCredentialsProvider(CredentialsProviderUtils.withAccessKey( System.getenv("#accessKeyId#"), System.getenv("#accessKeySecret#"))) .addRegion(regionInfo) // Use RegionInfo with CA certificate path .build()) .build(); // ... use the client } catch (CacheSecretException e) { e.printStackTrace(); } } }import os from alibabacloud_secretsmanager_client_V2.0.secret_manager_cache_client_builder import SecretManagerCacheClientBuilder from alibabacloud_secretsmanager_client_V2.0.service.default_secret_manager_client_builder import \ DefaultSecretManagerClientBuilder from alibabacloud_secretsmanager_client_V2.0.model.region_info import RegionInfo if __name__ == '__main__': # Create a RegionInfo with the CA certificate path region_info = RegionInfo( region_id="#regionId#", endpoint="#kmsInstanceEndpoint#", # Specify KMS instance endpoint ca_file_path="#caFilePath#" # Specify CA certificate file path ) secret_cache_client = SecretManagerCacheClientBuilder.new_cache_client_builder( DefaultSecretManagerClientBuilder.standard() .with_access_key( os.getenv("#accessKeyId#"), os.getenv("#accessKeySecret#") ) .add_region_info(region_info) # Use RegionInfo with CA certificate path .build() ).build() # ... use the clientpackage main import ( "github.com/aliyun/alibabacloud-secretsmanager-client-go-V2.0/sdk" "github.com/aliyun/alibabacloud-secretsmanager-client-go-V2.0/sdk/models" "github.com/aliyun/alibabacloud-secretsmanager-client-go-V2.0/sdk/service" "os" ) func main() { // Create a RegionInfo with the CA certificate path regionInfo := &models.RegionInfo{ RegionId: "#regionId#", Endpoint: "#kmsInstanceEndpoint#", // Specify KMS instance endpoint CaFilePath: "#caFilePath#", // Specify CA certificate file path } client, err := sdk.NewSecretCacheClientBuilder( service.NewDefaultSecretManagerClientBuilder(). Standard(). WithAccessKey(os.Getenv("#accessKeyId#"), os.Getenv("#accessKeySecret#")). AddRegionInfo(regionInfo). // Use RegionInfo with CA certificate path Build()).Build() if err != nil { // Handle exceptions panic(err) } secretInfo, err := client.GetSecretInfo("#secretName#") if err != nil { // Handle exceptions panic(err) } }import { SecretCacheClientBuilder, BaseSecretManagerClientBuilder, CredentialsProviderUtils, RegionInfo } from 'alibabacloud-secretsmanager-client-v2'; async function example() { try { // Create RegionInfo with CA certificate path const regionInfo = new RegionInfo(); regionInfo.setRegionId('#regionId#'); regionInfo.setEndpoint('#kmsInstanceEndpoint#'); // Specify KMS instance address regionInfo.setCaFilePath('#caFilePath#'); // Specify CA certificate file path const client = await SecretCacheClientBuilder.newCacheClientBuilder( BaseSecretManagerClientBuilder.standard() .withCredentialsProvider( CredentialsProviderUtils.withAccessKey( process.env['#accessKeyId#'], process.env['#accessKeySecret#'] ) ) .addRegionInfo(regionInfo) // Use RegionInfo with CA certificate path .build() ).build(); const secretInfo = await client.getSecretInfo('#secretName#'); console.log(secretInfo); } catch (error) { console.error('Error:', error); } } example();
What do I do if the error "env/config credentials type[client_key] is illegal" appears?
Cause: The Alibaba Cloud Secrets Manager Client SDK 2.0 does not support the ClientKey credential type.
Solution:
Switch to a supported credential type such as AccessKey, ECS RAM Role, or OIDC Role ARN. For more information, see Configure access credentials.
Downgrade to the SDK 1.0 (not recommended).