All Products
Search
Document Center

Key Management Service:Secrets Manager Client

Last Updated:May 08, 2026

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.

Note
  • 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

    Supported

    Supported

    OIDC Role Arn

    Unsupported

    Supported

    ECS RAM Role

    Supported

    Supported

    RAM Role Arn

    Supported

    Supported

    Note

    The 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

    Supported

    Unsupported

    Default credential provider chain

    Unsupported

    Supported

  • Security Features

    Feature

    SDK 1.0

    SDK 2.0

    Built-in CA Certificate

    Unsupported

    Supported

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:

  1. Set environment variables or prepare the configuration file, ensuring that all necessary credential information is included. Parameters differ between dedicated gateways and shared gateways.

  2. Initialize the client. The SDK automatically reads the configuration and identifies the gateway type.

  3. 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>
          
Important

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
          
Important
  • Installing the Secrets Manager Client Python SDK V2 requires Python 3.7 or later. Run python3 --version to 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          
Important

Node.js

Install the Secrets Manager Client using npm or yarn.

  • npm

    npm install alibabacloud-secretsmanager-client-v2
  • yarn

    yarn add alibabacloud-secretsmanager-client-v2
Important
  • 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.

  1. 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).

  2. 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.

      Note

      You 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.

  3. Log on to the ECS console and attach the RAM role to an ECS instance.image

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 .

    Warning

    Do 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/resources directory so it is automatically included in the classpath during compilation.

    • Go: Place the configuration file in the project root directory or a dedicated config directory, then load it through code.

    • Python: Place the configuration file in the project directory or a specific config directory, and use an appropriate method (such as os.path or pkg_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

credentials_type

Fixed value: ecs_ram_role.

credentials_role_name

The name of the RAM role.

cache_client_region_id

  • Dedicated gateway: [{"regionId":"<regionId>","endpoint":"<your_kms_instance_id>.cryptoservice.kms.aliyuncs.com"}].

  • Shared gateway: [{"regionId":"<your_region_id>"}].

  • Shared gateway (VPC): [{"regionId":"<your_region_id>","endpoint":"kms-vpc.<your_region_id>.aliyuncs.com","vpc":"true"}].

    Important
    • Replace <regionId> with the actual region ID and <your_kms_instance_id> with the actual instance ID.

    • On Linux, when setting environment variables with the export command, use escape characters, for example: [{\"regionId\":\"<your_region_id>"}].

AccessKey

Step 1: Create an AccessKey and configure permissions

Warning

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.

  1. Log on to the RAM console. On the Users page, click the name of the target RAM user.

  2. On the Authentication tab, in the AccessKey section, click Create AccessKey and follow the on-screen instructions.

  3. 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.

      Note

      You 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 .

    Warning

    Do 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/resources directory so it is automatically included in the classpath during compilation.

    • Go: Place the configuration file in the project root directory or a dedicated config directory, then load it through code.

    • Python: Place the configuration file in the project directory or a specific config directory, and use an appropriate method (such as os.path or pkg_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"}]
                
  • Shared gateway

    # 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

credentials_type

Fixed value: ak.

credentials_access_key_id

The AccessKey ID.

credentials_access_secret

The AccessKey Secret.

cache_client_region_id

  • Dedicated gateway: [{"regionId":"<regionId>","endpoint":"<your_kms_instance_id>.cryptoservice.kms.aliyuncs.com"}].

  • Shared gateway: [{"regionId":"<your_region_id>"}].

  • Shared gateway (VPC): [{"regionId":"<your_region_id>","endpoint":"kms-vpc.<your_region_id>.aliyuncs.com","vpc":"true"}].

    Important
    • Replace <regionId> with the actual region ID and <your_kms_instance_id> with the actual instance ID.

    • On Linux, when setting environment variables with the export command, use escape characters, for example: [{\"regionId\":\"<your_region_id>"}].

OIDC Role ARN

Note

Only SDK 2.0 supports OIDC Role ARN credentials. SDK 1.0 does not.

Step 1: Create an OIDC role ARN and configure permissions

  1. Create an OIDC provider

    1. Log on to the RAM console as a RAM administrator. On the SSO page, click the Role-based SSO tab.

    2. On the OIDC tab, click Create IdP.

    3. On the Create IdP page, configure the provider information. For more information, see Manage OIDC providers.

  2. Obtain and save the OIDC identity information (ARN and Client ID)

    1. Go to the SSO page, and on the IdP tab, click the name of the target OIDC provider.

    2. On the IdP details page, you can view the ARN and Client ID.

  3. Create and authorize a RAM role for the OIDC provider

    1. Log on to the RAM console as a RAM administrator and go to the Identities > Roles page.

    2. Click Create Role. In the upper-right corner of the creation page, click Switch to Policy Editor.

    3. In the policy editor, specify the OIDC provider. Select the visual editor and configure the parameters as described below.

      Note

      For information about other modes, see Create a RAM role for an OIDC provider.

      1. In the Select Trusted Entity section, select IdP.

      2. In the Edit Trust Policy section, configure the following parameters.

        • IdP Type: Select OIDC.

        • IdP: Select the OIDC provider you created earlier.

  4. 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.

      Note

      Custom 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.

  5. Obtain the target OIDC Role ARN

    1. On the Identities > Roles page, click the name of the target role.

    2. On the role details page, find the OIDC Role ARN in the ARN section.

      Note

      The Role ARN is the ARN of the RAM role to be assumed. The format is acs:ram::$accountID:role/$roleName, where $accountID is the Alibaba Cloud account ID and $roleName is the RAM role name.

  6. 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 .

    Warning

    Do 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/resources directory so it is automatically included in the classpath during compilation.

    • Go: Place the configuration file in the project root directory or a dedicated config directory, then load it through code.

    • Python: Place the configuration file in the project directory or a specific config directory, and use an appropriate method (such as os.path or pkg_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"}]            
  • Shared 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>
    # 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

credentials_type

Fixed value: oidc_role_arn.

credentials_role_arn

The ARN of the RAM role for the OIDC identity provider. Optional. If not specified, the Default credential provider chain is used.

credentials_oidc_provider_arn

The ARN of the OIDC identity provider. Optional. If not specified, the Default credential provider chain is used.

credentials_oidc_token_file_path

The relative or absolute path to the file that stores the OIDC token. Optional. If not specified, the Default credential provider chain is used.

cache_client_region_id

  • Dedicated gateway: [{"regionId":"<regionId>","endpoint":"<your_kms_instance_id>.cryptoservice.kms.aliyuncs.com"}].

  • Shared gateway: [{"regionId":"<your_region_id>"}].

  • Shared gateway (VPC): [{"regionId":"<your_region_id>","endpoint":"kms-vpc.<your_region_id>.aliyuncs.com","vpc":"true"}].

    Important
    • Replace <regionId> with the actual region ID and <your_kms_instance_id> with the actual instance ID.

    • On Linux, when setting environment variables with the export command, use escape characters, for example: [{\"regionId\":\"<your_region_id>"}].

AK+RamRoleArn

Note

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.

  1. Create a user AccessKey pair

    1. Log on to the RAM console. In the left-side navigation pane, choose Identities > Users. On the Users page, click the name of the target RAM user.

    2. Attach the AliyunSTSAssumeRoleAccess system policy or a custom policy that includes the sts:AssumeRole action to the RAM user.

    3. On the Authentication tab, in the AccessKey section, click Create AccessKey and follow the on-screen instructions.

  2. Create and authorize a RAM role:

    1. In the left-side navigation pane, choose Identities > Roles. On the Roles page, click Create Role. For more information, see Create a RAM role.

    2. 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.

        Note

        You 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.

  3. Obtain the RamRoleArn of the target RAM role. For more information, see View the information about a RAM role.

    1. In the left-side navigation pane, choose Identities > Roles. On the Roles page, click the name of the target role.

    2. On the role details page, find the RamRoleArn in the ARN section.

      Note

      The RamRoleArn is the Alibaba Cloud Resource Name (ARN) of the RAM role to assume. The format is acs:ram::$accountID:role/$roleName, where $accountID is the Alibaba Cloud account ID and $roleName is 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 .

    Warning

    Do 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/resources directory so it is automatically included in the classpath during compilation.

    • Go: Place the configuration file in the project root directory or a dedicated config directory, then load it through code.

    • Python: Place the configuration file in the project directory or a specific config directory, and use an appropriate method (such as os.path or pkg_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"}]          
  • Shared 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#
    # 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

credentials_type

ram_role or sts

credentials_role_session_name

The name of the RAM role session.

credentials_role_arn

The ARN of the RAM role.

credentials_access_key_id

The AccessKey ID.

credentials_access_secret

The AccessKey Secret.

cache_client_region_id

  • Dedicated gateway: [{"regionId":"<regionId>","endpoint":"<your_kms_instance_id>.cryptoservice.kms.aliyuncs.com"}].

  • Shared gateway: [{"regionId":"<your_region_id>"}].

  • Shared gateway (VPC): [{"regionId":"<your_region_id>","endpoint":"kms-vpc.<your_region_id>.aliyuncs.com","vpc":"true"}].

    Important
    • Replace <regionId> with the actual region ID and <your_kms_instance_id> with the actual instance ID.

    • On Linux, when setting environment variables with the export command, use escape characters, for example: [{\"regionId\":\"<your_region_id>"}].

ClientKey (Deprecated)

Note

Only SDK 1.0 supports the ClientKey credential type. SDK 2.0 does not.

Shared gateway

Step 1: Create a ClientKey
  1. Log on to the Key Management Service console. In the top navigation bar, select a region. In the left-side navigation pane, choose Application Access > Multi-Cloud Access (formerly AAP).

  2. (Optional) Create a network rule.

    Note

    Configuring a network rule to restrict access by source IP address is optional. However, we recommend configuring one for better security.

    1. Click the Network Access Rules tab and then click Create Network Access Rule.

    2. In the Create Network Access Rule panel, set Network Type to Public, enter the Allowed Source IP Addresses, and click OK.

  3. Create a permission policy.

    1. Click the Policies tab and then click Create Policy.

    2. In the Create Policy panel, configure the parameters for the shared gateway as described below, and then click OK.

      1. Scope: Shared KMS Gateway

      2. Accessible Resources: Select the secrets you want to access.

      3. (Optional) Network Access Rules: Select the network rule created in the previous step.

  4. Create an application access point (AAP).

    1. Click the Application Access tab and then click Create AAP.

    2. In the Create AAP panel, set Mode to Standard Creation, and then configure the parameters as described below.

      Parameter

      Description

      Authentication Method

      Select ClientKey.

      Encryption Password

      Enter an 8- to 64-character string that contains digits, letters, and special characters: ~!@#$%^&*?_-.

      Validity Period

      Important

      We recommend setting the validity period to one year to reduce the risk of ClientKey leaks. Be sure to rotate the ClientKey before it expires to avoid service interruptions. For more information, see Rotate a ClientKey.

      Policies

      Select the permission policy that you created in the previous step.

    3. 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.

Step 2: Configure Environment variables or Configuration File
  • Environment variables: Configuration methods vary by operating system. For more information, see .

    Warning

    Do 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/resources directory so it is automatically included in the classpath during compilation.

    • Go: Place the configuration file in the project root directory or a dedicated config directory, then load it through code.

    • Python: Place the configuration file in the project directory or a specific config directory, and use an appropriate method (such as os.path or pkg_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

    # Credential type
    credentials_type=client_key
    
    # File path to the ClientKeyPassword file (clientKey_****_Password.txt)
    client_key_password_from_file_path=#client_key_password_file_path#
    
    # File path to the ClientKeyContent file (clientKey_****.json)
    client_key_private_key_path=#client_key_private_key_file_path#
    
    # Associated KMS region
    cache_client_region_id=[{"regionId":"#regionId#"}]
                  
  • Approach 2: Configure the password via environment variable

    Warning

    First, store the ClientKeyPassword from the clientKey_****_Password.txt file in a custom environment variable, such as clientKeyPassword_content.

    # Credential type
    credentials_type=client_key
    
    # Environment variable name that stores the ClientKeyPassword content
    client_key_password_from_env_variable=#client_key_password_env_var_name#
    
    # ClientKey private key file path
    client_key_private_key_path=#client_key_private_key_file_path#
    
    # Associated KMS region
    cache_client_region_id=[{"regionId":"#regionId#"}]
                  

Environment variables

The SDK supports two approaches to configure the ClientKey credential password:

  • Approach 1: Configure the file path of the ClientKey password (clientKey_****_Password.txt)

    Parameter

    Value

    credentials_type

    Fixed value: client_key.

    client_key_password_from_file_path

    The absolute or relative path to the ClientKeyPassword file (clientKey_****_Password.txt).

    client_key_private_key_path

    The absolute or relative path to the Credential-ClientKeyContent  file (clientKey_****.json).

    cache_client_region_id

    Format: [{"regionId":"<your_region_id>"}]. On Linux, use escape characters: [{\"regionId\":\"<your_region_id>"}].

  • Approach 2: Directly configure the ClientKey password content

    Warning

    First, store the content of clientKey_****_Password.txt in a custom environment variable (for example, clientKeyPassword_content).

    Parameter

    Value

    credentials_type

    Fixed value: client_key.

    client_key_password_from_env_variable

    The name of the environment variable that stores the ClientKeyPassword content, for example, clientKeyPassword_content.

    client_key_private_key_path

    The absolute or relative path to the clientKey_****.json file.

    cache_client_region_id

    Format: [{"regionId":"<your_region_id>"}]. On Linux, use escape characters.

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.

    1. Log on to the Key Management Service console. In the top navigation bar, select a region. In the left-side navigation pane, choose Application Access > Multi-Cloud Access (formerly AAP).

    2. 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.

    3. 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.

    1. 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:

      1. When configuring network rules, select Private for the network type.

      2. When you configure the scope of the permission rule, select the corresponding KMS Instance ID.

    2. After creation, your browser automatically downloads the ClientKey, which includes:

      • Credential (ClientKeyContent): The file is named clientKey_****.json by default.

      • Credential password (ClientKeyPassword): The file is named clientKey_****_Password.txt by default.

Step 2: Configure Environment variables or Configuration File
  • Environment variables: Configuration methods vary by operating system. For more information, see .

    Warning

    Do 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/resources directory so it is automatically included in the classpath during compilation.

    • Go: Place the configuration file in the project root directory or a dedicated config directory, then load it through code.

    • Python: Place the configuration file in the project directory or a specific config directory, and use an appropriate method (such as os.path or pkg_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_info

    Format: [{"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_info

    Format: [{"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

regionId

The region ID where the KMS instance is deployed. For region IDs, see Regions and zones.

endpoint

The endpoint of the KMS instance, in the format {instance_id}.kms.aliyuncs.com.

clientKeyFile

The absolute or relative path to the Credential-ClientKeyContent file (clientKey_****.json).

passwordFromFilePath

The absolute or relative path to the ClientKeyPassword file (clientKey_****_Password.txt).

passwordFromEnvVariable

The name of the environment variable that stores the ClientKeyPassword content, for example, clientKeyPassword_content.

ignoreSslCerts

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:

  • true: Skips validation. No need to configure caFilePath.

  • false: Validates the SSL certificate.

caFilePath

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();
        }
    }
}
          
Note

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__)
          
Note

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)
    }
}
          
Note

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();
Note

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 caFilePath parameter to the cache_client_region_id configuration:

        # 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 caFilePath parameter to secretsmanager.properties or 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 client
                  
        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() {
            // 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).