All Products
Search
Document Center

Key Management Service:Secret client

Last Updated:Apr 27, 2025

The secret client is a custom encapsulation based on Key Management Service (KMS) API and KMS instance API that incorporates capabilities to cache and refresh secrets in applications. This improves service stability and simplifies the integration process for developers. The secret client supports retrieving secret values for all types of secrets. This topic describes how to install and use the secret client.

Features

The secret client provides the following features:

  • Allows developers to integrate secret client capabilities into applications. You can retrieve secret information with a single line of code.

  • Encapsulates capabilities to cache and refresh secrets in applications.

  • Encapsulates an API error-based retry mechanism to intelligently handle reported errors.

  • Provides a plugin design mode that allows you to customize features such as extended cache and error retry.

Supported secret types and programming languages

  • Supported secret types:

    • Generic secret.

    • Resource Access Management (RAM) secret.

    • ECS secret.

    • Database secret.

  • Supported programming languages:

    • Java 8 and later.

    • Go.

    • Python.

Retrieve secret values through a shared gateway

The network type is the Internet or VPC network.

Step 1: Create an access credential

The following RAM identity authentication methods are supported: Elastic Compute Service (ECS) instance RAM role, RamRoleArn, Security Token Service (STS) token, AccessKey pair, and ClientKey (not recommended).

ECS instance RAM role

An ECS instance RAM role is a regular service role that is attached to ECS instances, and the principal is ECS. This allows the ECS instance to obtain STS tokens for temporary access, eliminating the need for AccessKey pairs when calling KMS OpenAPI operations.

  1. Log on to the RAM console, and create an instance RAM role whose Principal Type is an Alibaba Cloud service.

    • Principal Type: Select Cloud Service.

    • Principal Name: Select Elastic Compute Service / ECS.

  2. Grant the RAM role access to retrieve KMS secrets.

    • Method 1: Through identity-based policies

      KMS provides system-defined permission policies that can be attached to RAM roles. For more information, see System policies for KMS. You can also create custom policies.

      image

    • Method 2: Through resource-based policies

      KMS supports resource-based policies, which allow you to set access permissions for keys and secrets. This lets you control which Alibaba Cloud accounts, RAM users, and RAM roles have permission to 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 instance RAM role to an ECS instance. image

RamRoleArn

RAM users or cloud services can obtain temporary permissions by assuming roles instead of directly using long-term access keys, thereby reducing the risk of key leakage. For instance, in temporary data processing tasks, RAM users or cloud services can temporarily assume a role with a specific RamRoleArn. RamRoleArn is the ARN information of the RAM role. Once the task is completed, the role's permissions are revoked, further mitigating the risk of exposure.

  1. Log on to the RAM console by using an Alibaba Cloud account or a RAM user who has administrative rights.

  2. Create a RAM role.

  3. Grant the RAM role access to KMS. You have two methods to complete the grant.

    • Method 1: Through identity-based policies

      KMS provides system-defined permission policies that can be attached to RAM roles. For more information, see System policies for KMS. You can also create custom policies.

    • Method 2: Through resource-based policies

      KMS supports resource-based policies, which allow you to set access permissions for keys and secrets. This lets you control which Alibaba Cloud accounts, RAM users, and RAM roles have permission to manage or use KMS keys and secrets. For more information, see Key policies and Secret policies.

  4. View the RamRoleArn about a RAM role.

    The RamRoleArn follows the format acs:ram::$accountID:role/$roleName, where $accountID is the Alibaba Cloud account and $roleName is the RAM role name.

    image

STS token

By using STS services, a temporary access credential can be issued to RAM users or RAM roles, allowing them to access KMS with permissions specified by the policy for a limited validity period. After the expiration period, the credential will automatically become invalid.

  1. Log on to the RAM console by using an Alibaba Cloud account or a RAM user who has administrative rights.

  2. Create a RAM user or create a RAM role.

  3. Grant AliyunSTSAssumeRoleAccess permission to a RAM user or Grant AliyunSTSAssumeRoleAccess permission to a RAM role.

    image

  4. Grant the RAM user access to KMS. You have two methods to complete the grant.

    • Method 1: Through identity-based policies

      KMS provides system-defined permission policies that can be attached to RAM users. For more information, see System policies for KMS. You can also create custom policies.

    • Method 2: Through resource-based policies

      KMS supports resource-based policies, which allow you to set access permissions for keys and secrets. This lets you control which Alibaba Cloud accounts, RAM users, and RAM roles have permission to manage or use KMS keys and secrets. For more information, see Key policies and Secret policies.

  1. Use the RAM user or RAM role to call the AssumeRole interface of the STS service to obtain temporary access credentials.

AccessKey

Use a RAM user's AccessKey pair as an example. Alibaba Cloud accounts have default administrator privileges for all resources, which cannot be modified. Because compromised AccessKeys risk significant security vulnerabilities, we strongly recommend against creating them for Alibaba Cloud accounts. Instead, create a RAM user solely for API access, generate its AccessKey, and implement the principle of least privilege.

  1. Log on to the RAM console. In the left-side navigation pane, choose Identities > Users, and click on the desired RAM user.

  2. In the Authentication tab, click Create AccessKey and follow the instructions.

    image

  3. Grant the RAM user access to retrieve KMS secrets.

    • Method 1: Through identity-based policies

      KMS provides system-defined permission policies that can be attached to RAM users. For more information, see System policies for KMS. You can also create custom policies.

      image

    • Method 2: Through resource-based policies

      KMS supports resource-based policies, which allow you to set access permissions for keys and secrets. This lets you control which Alibaba Cloud accounts, RAM users, and RAM roles have permission to manage or use KMS keys and secrets. For more information, see Key policies and Secret policies.

ClientKey (not recommended)

For instructions, see the standard creation method in Create an application access point. When configurating parameters, ensure the following settings are correct:

  • When create network rules, select Public or VPC for Network Type.

  • When configure the scope of permission rules, select Shared KMS Gateway.

Step 2: Install the secret client

Java

Install the secret client in your project by using Maven. We recommend that you use the latest version. Visit alibabacloud-secretsmanager-client-java to learn more about versions and source code.

<dependency>
    <groupId>com.aliyun</groupId>
    <artifactId>alibabacloud-secretsmanager-client</artifactId>
    <version>1.4.x</version>
</dependency>
<dependency>
  <groupId>com.aliyun</groupId>
  <artifactId>aliyun-java-sdk-core</artifactId>
  <version>4.5.x</version>
</dependency>

Python

Run the pip command to install the secret client. Visit aliyun-secretsmanager-client-python to learn more about installation and source code.

pip install aliyun-secret-manager-client

Go

Use the go get command to install the secret client. Visit aliyun-secretsmanager-client-go to learn more about installation and source code.

go get -u github.com/aliyun/aliyun-secretsmanager-client-go

Step 3: Initialize the client and retrieve secret values

The sample code for retrieving secret values varies based on the client initialization method. Choose one method for each programming language.

Java

  • Method 1: Using environment variables or the secretsmanager.properties configuration file

    Environment variables

    Environment variables and their configuration methods vary depending on the access credential type and operating system. The following tables list the required variables for each access credential type. For instructions on configuring these variables for different operating systems, see Configure environment variables in Linux, macOS, and Windows.

    ECS instance RAM role

    Variable

    Value

    credentials_type

    The value is fixed as ecs_ram_role.

    credentials_role_name

    The name of the RAM role.

    cache_client_region_id

    The format is [{"regionId":"<REGION_ID>"}]. Replace <REGION_ID> with the actual region ID.

    Important

    On Linux and macOS systems, when setting environment variables with the export command, escape special characters. Use [{\"regionId\":\"<REGION_ID>\"}] as the value format for this variable.

    RamRoleArn

    Variable

    Value

    credentials_type

    The value is fixed as ram_role.

    credentials_role_session_name

    The name of the RAM role.

    credentials_role_arn

    The Alibaba Cloud Resource Name (ARN) of the RAM role.

    credentials_access_key_id

    The AccessKey ID.

    credentials_access_secret

    The AccessKey secret.

    cache_client_region_id

    The format is [{"regionId":"<REGION_ID>"}]. Replace <REGION_ID> with the actual region ID.

    Important

    On Linux and macOS systems, when setting environment variables with the export command, escape special characters. Use [{\"regionId\":\"<REGION_ID>\"}] as the value format for this variable.

    STS token

    Variable

    Value

    credentials_type

    The value is fixed as sts.

    credentials_role_session_name

    The name of the RAM role.

    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

    The format is [{"regionId":"<REGION_ID>"}]. Replace <REGION_ID> with the actual region ID.

    Important

    On Linux and macOS systems, when setting environment variables with the export command, escape special characters. Use [{\"regionId\":\"<REGION_ID>\"}] as the value format for this variable.

    AccessKey

    Variable

    Value

    credentials_type

    The value is fixed as ak.

    credentials_access_key_id

    The AccessKey ID.

    credentials_access_secret

    The AccessKey secret.

    cache_client_region_id

    The format is [{"regionId":"<REGION_ID>"}]. Replace <REGION_ID> with the actual region ID.

    Important

    On Linux and macOS systems, when setting environment variables with the export command, escape special characters. Use [{\"regionId\":\"<REGION_ID>\"}] as the value format for this variable.

    ClientKey

    Variable

    Value

    credentials_type

    The value is fixed as client_key.

    client_key_password_from_env_variable

    The name of the environment variable containing the client key password. Before configuring it, define an environment variable with a custom name and set the client key password as its value.

    Note

    You can only specify one method for providing the client key password: either from an environment variable (client_key_password_from_env_variable) or from a file (client_key_password_from_file_path).

    client_key_password_from_file_path

    The absolute or relative path to the client key password file. Before configuring it, save the password to a file and name it.

    client_key_private_key_path

    The absolute or relative path to the client key file. Before configuring it, save the file in a secure location. You can specify a custom name for the file.

    cache_client_region_id

    The format is [{"regionId":"<REGION_ID>"}]. Replace <REGION_ID> with the actual region ID.

    Important

    On Linux and macOS systems, when setting environment variables with the export command, escape special characters. Use [{\"regionId\":\"<REGION_ID>\"}] as the value format for this variable.

    Configuration file: secretsmanager.properties

    The configuration file is named secretsmanager.properties. Note that its contents vary depending on your authentication method.

    ECS instance RAM role

    # Access credential type.
    credentials_type=ecs_ram_role
    # The name of the instance RAM role of an ECS instance.
    credentials_role_name=#credentials_role_name#
    # The ID of the region in which you want to use KMS.
    cache_client_region_id=[{"regionId":"#regionId#"}]

    RAMRoleArn

    # Access credential type.
    credentials_type=ram_role
    # The name of the role.
    credentials_role_session_name=#role name#
    # The ARN of the RAM role.
    credentials_role_arn=#role arn#
    # AK.
    credentials_access_key_id=#access key id#
    # SK.
    credentials_access_secret=#access key secret#
    # The ID of the region in which you want to use KMS.
    cache_client_region_id=[{"regionId":"#regionId#"}]

    STS token

    # Access credential type.
    credentials_type=sts
    # The name of the role.
    credentials_role_session_name=#role name#
    # The ARN of the RAM role.
    credentials_role_arn=#role arn#
    # AK.
    credentials_access_key_id=#access key id#
    # SK.
    credentials_access_secret=#access key secret#
    # The ID of the region in which you want to use KMS.
    cache_client_region_id=[{"regionId":"#regionId#"}]

    AccessKey

    # Access credential type.
    credentials_type=ak
    # AK.
    credentials_access_key_id=#access key id#
    # SK.
    credentials_access_secret=#access key secret#
    # The ID of the region in which you want to use KMS.
    cache_client_region_id=[{"regionId":"#regionId#"}]

    ClientKey

    # Access credential type.
    credentials_type=client_key
    
    # The password of the client key. You can obtain the password from environment variables or files.
    client_key_password_from_env_variable=#your client key private key password environment variable name#
    client_key_password_from_file_path=#your client key private key password file path#
    
    # Specify the path of the private key file of the client key.
    client_key_private_key_path=#your client key private key file path#
    
    # The ID of the region in which you want to use KMS.
    cache_client_region_id=[{"regionId":"#regionId#"}]

    Sample code (using environment variables)

    Replace #secretName# with your secret name.

    import com.aliyuncs.kms.secretsmanager.client.SecretCacheClient;
    import com.aliyuncs.kms.secretsmanager.client.SecretCacheClientBuilder;
    import com.aliyuncs.kms.secretsmanager.client.exception.CacheSecretException;
    import com.aliyuncs.kms.secretsmanager.client.model.SecretInfo;
    
    public class CacheClientEnvironmentSample {
    
        public static void main(String[] args) {
            try {
                // Build the secret client
                SecretCacheClient client = SecretCacheClientBuilder.newClient();
                // Use the secret client to retrieve secret information.
                SecretInfo secretInfo = client.getSecretInfo("#secretName#");
                System.out.println(secretInfo);
            } catch (CacheSecretException e) {
                e.printStackTrace();
            }
        }
    }
  • Method 2: Using a custom configuration file

    Specify the configuration file name and path. Note that its contents vary depending on your authentication method.

    Custom configuration file

    ECS instance RAM role
    # Access credential type.
    credentials_type=ecs_ram_role
    # The name of the instance RAM role of an ECS instance.
    credentials_role_name=#credentials_role_name#
    # The ID of the region in which you want to use KMS.
    cache_client_region_id=[{"regionId":"#regionId#"}]
    RAMRoleArn
    # Access credential type.
    credentials_type=ram_role
    # The name of the role.
    credentials_role_session_name=#role name#
    # The ARN of the RAM role.
    credentials_role_arn=#role arn#
    # AK.
    credentials_access_key_id=#access key id#
    # SK.
    credentials_access_secret=#access key secret#
    # The ID of the region in which you want to use KMS.
    cache_client_region_id=[{"regionId":"#regionId#"}]
    STS token
    # Access credential type.
    credentials_type=sts
    # The name of the role.
    credentials_role_session_name=#role name#
    # The ARN of the RAM role.
    credentials_role_arn=#role arn#
    # AK.
    credentials_access_key_id=#access key id#
    # SK.
    credentials_access_secret=#access key secret#
    # The ID of the region in which you want to use KMS.
    cache_client_region_id=[{"regionId":"#regionId#"}]
    AccessKey
    # Access credential type.
    credentials_type=ak
    # AK.
    credentials_access_key_id=#access key id#
    # SK.
    credentials_access_secret=#access key secret#
    # The ID of the region in which you want to use KMS.
    cache_client_region_id=[{"regionId":"#regionId#"}]
    ClientKey
    # Access credential type.
    credentials_type=client_key
    
    # The password of the client key. You can obtain the password from environment variables or files.
    client_key_password_from_env_variable=#your client key private key password environment variable name#
    client_key_password_from_file_path=#your client key private key password file path#
    
    # Specify the path of the private key file of the client key.
    client_key_private_key_path=#your client key private key file path#
    
    # The ID of the region in which you want to use KMS.
    cache_client_region_id=[{"regionId":"#regionId#"}]

    Sample code

    Replace #customConfigFileName# with your configuration file name and #secretName# with your secret name.

    import com.aliyuncs.kms.secretsmanager.client.SecretCacheClient;
    import com.aliyuncs.kms.secretsmanager.client.SecretCacheClientBuilder;
    import com.aliyuncs.kms.secretsmanager.client.exception.CacheSecretException;
    import com.aliyuncs.kms.secretsmanager.client.model.SecretInfo;
    import com.aliyuncs.kms.secretsmanager.client.service.BaseSecretManagerClientBuilder;
    
    public class CacheClientCustomConfigFileSample {
    
        public static void main(String[] args) {
            try {
                SecretCacheClient client = SecretCacheClientBuilder.newCacheClientBuilder(
                        BaseSecretManagerClientBuilder.standard().withCustomConfigFile("#customConfigFileName#").build()).build();
                SecretInfo secretInfo = client.getSecretInfo("#secretName#");
                System.out.println(secretInfo);
            } catch (CacheSecretException e) {
                System.out.println("CacheSecretException:" + e.getMessage());
            }
        }
    }
  • Method 3: Specifying parameters (accessKey, accessSecret, and regionId)

    Applies only to the AccessKey authentication method.

    Note

    The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using the AccessKey pair to perform operations is a high-risk operation. In addition, use a RAM user to call API operations or perform routine O&M. We recommend that you do not save the AccessKey ID and AccessKey Secret in your project code. If you do, the AccessKey pair may be leaked and the security of all the resources that belong to your account may be compromised.

    In this example, the AccessKey pair is saved in ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables to implement identity authentication.

    Sample code

    Replace #regionId# with the actual region ID and #secretName# with your secret name.

    import com.aliyuncs.kms.secretsmanager.client.SecretCacheClient;
    import com.aliyuncs.kms.secretsmanager.client.SecretCacheClientBuilder;
    import com.aliyuncs.kms.secretsmanager.client.exception.CacheSecretException;
    import com.aliyuncs.kms.secretsmanager.client.model.SecretInfo;
    import com.aliyuncs.kms.secretsmanager.client.service.BaseSecretManagerClientBuilder;
    import com.aliyuncs.kms.secretsmanager.client.utils.CredentialsProviderUtils;
    
    public class CacheClientSimpleParametersSample {
    
        public static void main(String[] args) {
            try {
                SecretCacheClient client = SecretCacheClientBuilder.newCacheClientBuilder(
                        BaseSecretManagerClientBuilder.standard().withCredentialsProvider(CredentialsProviderUtils
                                .withAccessKey(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"), System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"))).withRegion("#regionId#").build()).build();
                SecretInfo secretInfo = client.getSecretInfo("#secretName#");
                System.out.println(secretInfo);
            } catch (CacheSecretException e) {
                e.printStackTrace();
            }
        }
    }

Python

  • Method 1: Using environment variables or the secretsmanager.properties configuration file

    Environment variables

    Environment variables and their configuration methods vary depending on the access credential type and operating system. The following tables list the required variables for each access credential type. For instructions on configuring these variables for different operating systems, see Configure environment variables in Linux, macOS, and Windows.

    ECS instance RAM role

    Variable

    Value

    credentials_type

    The value is fixed as ecs_ram_role.

    credentials_role_name

    The name of the RAM role.

    cache_client_region_id

    The format is [{"regionId":"<REGION_ID>"}]. Replace <REGION_ID> with the actual region ID.

    Important

    On Linux and macOS systems, when setting environment variables with the export command, escape special characters. Use [{\"regionId\":\"<REGION_ID>\"}] as the value format for this variable.

    RamRoleArn

    Variable

    Value

    credentials_type

    The value is fixed as ram_role.

    credentials_role_session_name

    The name of the RAM role.

    credentials_role_arn

    The Alibaba Cloud Resource Name (ARN) of the RAM role.

    credentials_access_key_id

    The AccessKey ID.

    credentials_access_secret

    The AccessKey secret.

    cache_client_region_id

    The format is [{"regionId":"<REGION_ID>"}]. Replace <REGION_ID> with the actual region ID.

    Important

    On Linux and macOS systems, when setting environment variables with the export command, escape special characters. Use [{\"regionId\":\"<REGION_ID>\"}] as the value format for this variable.

    STS token

    Variable

    Value

    credentials_type

    The value is fixed as sts.

    credentials_role_session_name

    The name of the RAM role.

    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

    The format is [{"regionId":"<REGION_ID>"}]. Replace <REGION_ID> with the actual region ID.

    Important

    On Linux and macOS systems, when setting environment variables with the export command, escape special characters. Use [{\"regionId\":\"<REGION_ID>\"}] as the value format for this variable.

    AccessKey

    Variable

    Value

    credentials_type

    The value is fixed as ak.

    credentials_access_key_id

    The AccessKey ID.

    credentials_access_secret

    The AccessKey secret.

    cache_client_region_id

    The format is [{"regionId":"<REGION_ID>"}]. Replace <REGION_ID> with the actual region ID.

    Important

    On Linux and macOS systems, when setting environment variables with the export command, escape special characters. Use [{\"regionId\":\"<REGION_ID>\"}] as the value format for this variable.

    ClientKey

    Variable

    Value

    credentials_type

    The value is fixed as client_key.

    client_key_password_from_env_variable

    The name of the environment variable containing the client key password. Before configuring it, define an environment variable with a custom name and set the client key password as its value.

    Note

    You can only specify one method for providing the client key password: either from an environment variable (client_key_password_from_env_variable) or from a file (client_key_password_from_file_path).

    client_key_password_from_file_path

    The absolute or relative path to the client key password file. Before configuring it, save the password to a file and name it.

    client_key_private_key_path

    The absolute or relative path to the client key file. Before configuring it, save the file in a secure location. You can specify a custom name for the file.

    cache_client_region_id

    The format is [{"regionId":"<REGION_ID>"}]. Replace <REGION_ID> with the actual region ID.

    Important

    On Linux and macOS systems, when setting environment variables with the export command, escape special characters. Use [{\"regionId\":\"<REGION_ID>\"}] as the value format for this variable.

    Configuration file: secretsmanager.properties

    The configuration file is named secretsmanager.properties. Note that its contents vary depending on your authentication method.

    ECS instance RAM role
    # Access credential type.
    credentials_type=ecs_ram_role
    # The name of the instance RAM role of an ECS instance.
    credentials_role_name=#credentials_role_name#
    # The ID of the region in which you want to use KMS.
    cache_client_region_id=[{"regionId":"#regionId#"}]
    RAMRoleArn
    # Access credential type.
    credentials_type=ram_role
    # The name of the role.
    credentials_role_session_name=#role name#
    # The ARN of the RAM role.
    credentials_role_arn=#role arn#
    # AK.
    credentials_access_key_id=#access key id#
    # SK.
    credentials_access_secret=#access key secret#
    # The ID of the region in which you want to use KMS.
    cache_client_region_id=[{"regionId":"#regionId#"}]
    STS token
    # Access credential type.
    credentials_type=sts
    # The name of the role.
    credentials_role_session_name=#role name#
    # The ARN of the RAM role.
    credentials_role_arn=#role arn#
    # AK.
    credentials_access_key_id=#access key id#
    # SK.
    credentials_access_secret=#access key secret#
    # The ID of the region in which you want to use KMS.
    cache_client_region_id=[{"regionId":"#regionId#"}]
    AccessKey
    # Access credential type.
    credentials_type=ak
    # AK.
    credentials_access_key_id=#access key id#
    # SK.
    credentials_access_secret=#access key secret#
    # The ID of the region in which you want to use KMS.
    cache_client_region_id=[{"regionId":"#regionId#"}]
    ClientKey
    # Access credential type.
    credentials_type=client_key
    
    # The password of the client key. You can obtain the password from environment variables or files.
    client_key_password_from_env_variable=#your client key private key password environment variable name#
    client_key_password_from_file_path=#your client key private key password file path#
    
    # Specify the path of the private key file of the client key.
    client_key_private_key_path=#your client key private key file path#
    
    # The ID of the region in which you want to use KMS.
    cache_client_region_id=[{"regionId":"#regionId#"}]

    Sample code (using environment variables)

    Replace #secretName# with your secret name.

    from alibaba_cloud_secretsmanager_client.secret_manager_cache_client_builder import SecretManagerCacheClientBuilder
    
    if __name__ == '__main__':
        # Build the secret client
        secret_cache_client = SecretManagerCacheClientBuilder.new_client()
        # Use the secret client to retrieve secret information
        secret_info = secret_cache_client.get_secret_info("#secretName#")
        print(secret_info.__dict__)
  • Method 2: Specifying parameters (accessKey, accessSecret, and regionId)

    Applies only to the AccessKey authentication method.

    Note

    The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using the AccessKey pair to perform operations is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. We recommend that you do not save the AccessKey ID and AccessKey Secret in your project code. Otherwise, the AccessKey pair may be leaked and the security of all the resources that belong to your account may be compromised.

    In this example, the AccessKey pair is saved in ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables to implement identity authentication.

    Sample code

    Replace #regionId# with the actual region ID and #secretName# with your secret name.

    import os
    
    from alibaba_cloud_secretsmanager_client.secret_manager_cache_client_builder import SecretManagerCacheClientBuilder
    from alibaba_cloud_secretsmanager_client.service.default_secret_manager_client_builder import DefaultSecretManagerClientBuilder
    
    if __name__ == '__main__':
        secret_cache_client = SecretManagerCacheClientBuilder.new_cache_client_builder(DefaultSecretManagerClientBuilder.standard() \
            .with_access_key(os.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"), os.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")) \
            .with_region("#regionId#").build()) \
        .build();
        secret_info = secret_cache_client.get_secret_info("#secretName#")
        print(secret_info.__dict__)

Go

  • Method 1: Using environment variables or the secretsmanager.properties configuration file

    Environment variables

    Environment variables and their configuration methods vary depending on the access credential type and operating system. The following tables list the required variables for each access credential type. For instructions on configuring these variables for different operating systems, see Configure environment variables in Linux, macOS, and Windows.

    ECS instance RAM role

    Variable

    Value

    credentials_type

    The value is fixed as ecs_ram_role.

    credentials_role_name

    The name of the RAM role.

    cache_client_region_id

    The format is [{"regionId":"<REGION_ID>"}]. Replace <REGION_ID> with the actual region ID.

    Important

    On Linux and macOS systems, when setting environment variables with the export command, escape special characters. Use [{\"regionId\":\"<REGION_ID>\"}] as the value format for this variable.

    RamRoleArn

    Variable

    Value

    credentials_type

    The value is fixed as ram_role.

    credentials_role_session_name

    The name of the RAM role.

    credentials_role_arn

    The Alibaba Cloud Resource Name (ARN) of the RAM role.

    credentials_access_key_id

    The AccessKey ID.

    credentials_access_secret

    The AccessKey secret.

    cache_client_region_id

    The format is [{"regionId":"<REGION_ID>"}]. Replace <REGION_ID> with the actual region ID.

    Important

    On Linux and macOS systems, when setting environment variables with the export command, escape special characters. Use [{\"regionId\":\"<REGION_ID>\"}] as the value format for this variable.

    STS token

    Variable

    Value

    credentials_type

    The value is fixed as sts.

    credentials_role_session_name

    The name of the RAM role.

    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

    The format is [{"regionId":"<REGION_ID>"}]. Replace <REGION_ID> with the actual region ID.

    Important

    On Linux and macOS systems, when setting environment variables with the export command, escape special characters. Use [{\"regionId\":\"<REGION_ID>\"}] as the value format for this variable.

    AccessKey

    Variable

    Value

    credentials_type

    The value is fixed as ak.

    credentials_access_key_id

    The AccessKey ID.

    credentials_access_secret

    The AccessKey secret.

    cache_client_region_id

    The format is [{"regionId":"<REGION_ID>"}]. Replace <REGION_ID> with the actual region ID.

    Important

    On Linux and macOS systems, when setting environment variables with the export command, escape special characters. Use [{\"regionId\":\"<REGION_ID>\"}] as the value format for this variable.

    ClientKey

    Variable

    Value

    credentials_type

    The value is fixed as client_key.

    client_key_password_from_env_variable

    The name of the environment variable containing the client key password. Before configuring it, define an environment variable with a custom name and set the client key password as its value.

    Note

    You can only specify one method for providing the client key password: either from an environment variable (client_key_password_from_env_variable) or from a file (client_key_password_from_file_path).

    client_key_password_from_file_path

    The absolute or relative path to the client key password file. Before configuring it, save the password to a file and name it.

    client_key_private_key_path

    The absolute or relative path to the client key file. Before configuring it, save the file in a secure location. You can specify a custom name for the file.

    cache_client_region_id

    The format is [{"regionId":"<REGION_ID>"}]. Replace <REGION_ID> with the actual region ID.

    Important

    On Linux and macOS systems, when setting environment variables with the export command, escape special characters. Use [{\"regionId\":\"<REGION_ID>\"}] as the value format for this variable.

    Configuration file: secretsmanager.properties

    The configuration file is named secretsmanager.properties. Note that its contents vary depending on your authentication method.

    ECS instance RAM role
    # Access credential type.
    credentials_type=ecs_ram_role
    # The name of the instance RAM role of an ECS instance.
    credentials_role_name=#credentials_role_name#
    # The ID of the region in which you want to use KMS.
    cache_client_region_id=[{"regionId":"#regionId#"}]
    RAMRoleArn
    # Access credential type.
    credentials_type=ram_role
    # The name of the role.
    credentials_role_session_name=#role name#
    # The ARN of the RAM role.
    credentials_role_arn=#role arn#
    # AK.
    credentials_access_key_id=#access key id#
    # SK.
    credentials_access_secret=#access key secret#
    # The ID of the region in which you want to use KMS.
    cache_client_region_id=[{"regionId":"#regionId#"}]
    STS token
    # Access credential type.
    credentials_type=sts
    # The name of the role.
    credentials_role_session_name=#role name#
    # The ARN of the RAM role.
    credentials_role_arn=#role arn#
    # AK.
    credentials_access_key_id=#access key id#
    # SK.
    credentials_access_secret=#access key secret#
    # The ID of the region in which you want to use KMS.
    cache_client_region_id=[{"regionId":"#regionId#"}]
    AccessKey
    # Access credential type.
    credentials_type=ak
    # AK.
    credentials_access_key_id=#access key id#
    # SK.
    credentials_access_secret=#access key secret#
    # The ID of the region in which you want to use KMS.
    cache_client_region_id=[{"regionId":"#regionId#"}]
    ClientKey
    # Access credential type.
    credentials_type=client_key
    
    # The password of the client key. You can obtain the password from environment variables or files.
    client_key_password_from_env_variable=#your client key private key password environment variable name#
    client_key_password_from_file_path=#your client key private key password file path#
    
    # Specify the path of the private key file of the client key.
    client_key_private_key_path=#your client key private key file path#
    
    # The ID of the region in which you want to use KMS.
    cache_client_region_id=[{"regionId":"#regionId#"}]

    Sample code (using environment variables)

    Replace #secretName# with your secret name.

    package main
    
    import (
        "fmt"
        "github.com/aliyun/aliyun-secretsmanager-client-go/sdk"
    )
    func main() { 
       // Build the secret client
        client, err := sdk.NewClient()
        if err != nil {
            // Handle exceptions
            panic(err)
        }
       // Use the secret client to retrieve secret information
        secretInfo, err := client.GetSecretInfo("#secretName#")
        if err != nil {
            // Handle exceptions
            panic(err)
        }
        fmt.Printf("SecretValue:%s\n",secretInfo.SecretValue)
    }
  • Method 2: Specifying parameters (accessKey, accessSecret, and regionId)

    Applies only to the AccessKey authentication method.

    Note

    The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using the AccessKey pair to perform operations is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. We recommend that you do not save the AccessKey ID and AccessKey Secret in your project code. Otherwise, the AccessKey pair may be leaked and the security of all the resources that belong to your account may be compromised.

    In this example, the AccessKey pair is saved in ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables to implement identity authentication.

    Sample code

    Replace #regionId# with the actual region ID and #secretName# with your secret name.

    package main
    
    import (
    	"github.com/aliyun/aliyun-secretsmanager-client-go/sdk/service"
    	"github.com/aliyun/aliyun-secretsmanager-client-go/sdk"
    	"os"
    )
    
    func main() {
    	client, err := sdk.NewSecretCacheClientBuilder(service.NewDefaultSecretManagerClientBuilder().Standard().WithAccessKey(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"), os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")).WithRegion("#regionId#").Build()).Build()
    	if err != nil {
    		// Handle exceptions
    		panic(err)
    	}
    	secretInfo, err := client.GetSecretInfo("#secretName#")
    	if err != nil {
    		// Handle exceptions
    		panic(err)
    	}
    }

Retrieve secret values through a dedicated gateway (not recommended)

KMS uses a private network.

Step 1: Create an access credential

Access requires a client key, which can be created using one of the following methods:

  • Method 1: Quick creation

    Suitable for quick testing and development scenarios. This method uses a default permission policy that cannot be modified. Your application will have access to all keys and secrets in the specified KMS instance.

  • Method 2: Standard creation

    Use this method to configure fine-grained access permissions for resources.

Method 1: Quick creation

  1. Log on to the KMS console. In the top navigation bar, select a region. In the left-side navigation pane, click Application Access > AAPs.

  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 you want to access.

    Application Access Point Name

    Enter the name of the AAP.

    Authentication Method

    The default value is ClientKey, which cannot be changed.

    Default Permission Policy

    The default value is key/*secret/*, which cannot be changed. Your application can access all keys and secrets in the specified KMS instance.

  3. Click OK. The browser automatically downloads the client key that is created.

    The client key contains Application Access Secret(ClientKeyContent) and Password. By default, Application Access Secret(ClientKeyContent) is saved in a file whose name is in the clientKey_****.json format. By default, Password is saved in a file whose name is in the clientKey_****_Password.txt format.

Method 2: Standard creation

For detailed instructions, see Method 2: Standard creation. When configurating parameters, ensure the following settings are correct:

  • When create a network access rule, select Private for Network Type.

  • When configure the scope of permission policy, select the specified KMS Instance ID.

Step 2: Install the secret client

Java

Install the secret client in your project by using Maven. We recommend that you use the latest version. Visit alibabacloud-secretsmanager-client-java to learn more about versions and source code.

<dependency>
    <groupId>com.aliyun</groupId>
    <artifactId>alibabacloud-secretsmanager-client</artifactId>
    <version>1.4.x</version>
</dependency>
<dependency>
  <groupId>com.aliyun</groupId>
  <artifactId>aliyun-java-sdk-core</artifactId>
  <version>4.5.x</version>
</dependency>

Python

Run the pip command to install the secret client. Visit aliyun-secretsmanager-client-python to learn more about installation and source code.

pip install aliyun-secret-manager-client

Go

Use the go get command to install the secret client. Visit aliyun-secretsmanager-client-go to learn more about installation and source code.

go get -u github.com/aliyun/aliyun-secretsmanager-client-go

Step 3: Initialize the secret client and retrieve secret values

The sample code for retrieving secret values varies based on the client initialization method. Choose one method for each programming language.

Java

  • Method 1: Using environment variables or the secretsmanager.properties configuration file

    Environment variables

    • Method 1: Obtain ClientKey credentials through environment variables

      Variable

      Value

      cache_client_dkms_config_info

      The format is [{"regionId":"<DKMS_REGION_ID >","endpoint":"<DKMS_ENDPOINT>","passwordFromEnvVariable":"<PASSWORD_ENV_VARIABLE>","clientKeyFile":"<CLIENT_KEY_FILE_PATH>","ignoreSslCerts":false,"caFilePath":"<CA_CERTIFICATE_FILE_PATH>"}].

      Before configuring it, define an environment variable with a custom name and set the client key password as its value. Then, replace <PASSWORD_ENV_VARIABLE> with your variable name.

      For Linux systems, the example is as follows:

      export cache_client_dkms_config_info=[{"regionId":"ap-southeast-1","endpoint":"kst-hzz634e67d126u9p9****.cryptoservice.kms.aliyuncs.com","passwordFromEnvVariable":"passwordFromEnvVariable","clientKeyFile":"C:\RamSecretPlugin\src\main\resources\clientKey_KAAP.json","ignoreSslCerts":false,"caFilePath":"C:\RamSecretPlugin\src\main\resources\PrivateKmsCA_kst-hzz634e67d126u9p9****.pem"}]
    • Method 2: Obtain the client key password from a file

      The default filename for the client key password after download is clientKey_****_Password.txt. You can rename the file, but you'll need to replace <your Client Key file path> in the cache_client_dkms_config_info value with the new file path.

      Variable

      Value

      cache_client_dkms_config_info

      The format is: [{"regionId":"<DKMS_REGION_ID>","endpoint":"<DKMS_ENDPOINT>","passwordFromFilePath":"<PASSWORD_FILE_PATH>","clientKeyFile":"<CLIENT_KEY_FILE_PATH>","ignoreSslCerts":false,"caFilePath":"<CA_CERTIFICATE_FILE_PATH>"}].

      For Linux systems, the example is as follows:

      export cache_client_dkms_config_info=[{"regionId":"ap-southeast-1","endpoint":"kst-hzz634e67d126u9p9****.cryptoservice.kms.aliyuncs.com","passwordFromFilePath":"C:\RamSecretPlugin\src\main\resources\clientKeyPassword.txt","clientKeyFile":"C:\RamSecretPlugin\src\main\resources\clientKey_KAAP.json","ignoreSslCerts":false,"caFilePath":"C:\RamSecretPlugin\src\main\resources\PrivateKmsCA_kst-hzz634e67d126u9p9****.pem"}]

    Parameter description

    Parameter

    Description

    Note

    regionId

    The region ID of the KMS instance.

    For specific region IDs, see Regions and endpoints.

    endpoint

    The domain name of the KMS instance, in the format {instance ID}.kms.aliyuncs.com.

    Visit the Instances page and check the Instance VPC Endpoint on the instance details page, which is the endpoint.

    clientKeyFile

    The absolute or relative path to the client key file in the JSON format.

    • Client key file: The Application Access Secret downloaded when you create a client key in the application access point (AAP). The default filename after download is ClientKey_******.json.

    • Password: The client key password downloaded when you create a client key in the AAP. The default filename after download is ClientKey_******_password.txt.

    Important

    Each client key has a unique password, both generated only upon creation. If you lose either, you must create a new client key in the AAP. For instructions, see Create an application access point.

    passwordFromFilePath or passwordFromEnvVariable

    • passwordFromFilePath: Obtains the password from a file. The value is the absolute or relative path to the file containing the client key password.

    • passwordFromEnvVariable: Obtains the password from an environment variable. The value is the name of the environment variable that the value is the client key password.

    ignoreSslCerts

    Specifies whether to ignore the validity check on the SSL certificate of the KMS instance. The KMS instance has a built-in SSL certificate that is used for identity verification and SSL- or TLS-encrypted communication. Valid values:

    • true: The validity check is ignored.

      If the value is true, the caFilePath parameter is not required.

    • false: The validity check is performed.

    In the production environment, set this parameter to false.

    caFilePath

    The absolute or relative path to the certificate authority (CA) certificate file of the KMS instance.

    The CA certificate validates the KMS instance's SSL certificate, including checks on the certificate's issuer, its validity period, and whether the domain name matches the KMS endpoint.

    Visit the Instances page. On the instance details page, click Download in the Instance CA Certificate section.

    Configuration file: secretsmanager.properties

    The configuration file is named secretsmanager.properties. It uses a JSON array for the cache_client_dkms_config_info parameter. The value varies depending on the client key password retrieval method.

    • Method 1: Obtain the client key password from an environment variable

      cache_client_dkms_config_info=[{"regionId":"<DKMS_REGION_ID>","endpoint":"<DKMS_ENDPOINT>","passwordFromEnvVariable":"<PASSWORD_ENV_VARIABLE>","clientKeyFile":"<CLIENT_KEY_FILE_PATH>","ignoreSslCerts":false,"caFilePath":"<CA_CERTIFICATE_FILE_PATH>"}]

      Before configurating the file, define an environment variable with a custom name and set the client key password as its value. Then, replace <PASSWORD_ENV_VARIABLE> with your variable name.

      Example:

      cache_client_dkms_config_info=[{"regionId":"ap-southeast-1","endpoint":"kst-hzz634e67d126u9p9****.cryptoservice.kms.aliyuncs.com","passwordFromEnvVariable":"passwordFromEnvVariable","clientKeyFile":"C:\RamSecretPlugin\src\main\resources\clientKey_KAAP.json","ignoreSslCerts":false,"caFilePath":"C:\RamSecretPlugin\src\main\resources\PrivateKmsCA_kst-hzz634e67d126u9p9****.pem"}]
    • Method 2: Obtain the client key password from a file

      The default filename for the Client Key Password (ClientKeyPassword) after download is clientKey_****_Password.txt. You can rename the file, but you'll need to replace <your Client Key file path> in the cache_client_dkms_config_info value with the new file path.

      cache_client_dkms_config_info=[{"regionId":"<your dkms regionId >","endpoint":"<your dkms endpoint>","passwordFromFilePath":"< your password file path >","clientKeyFile":"<your Client Key file path>","ignoreSslCerts":false,"caFilePath":"<your CA certificate file path>"}]

      Example:

      cache_client_dkms_config_info=[{"regionId":"cn-hangzhou","endpoint":"kst-hzz634e67d126u9p9****.cryptoservice.kms.aliyuncs.com","passwordFromFilePath":"C:\RamSecretPlugin\src\main\resources\clientKeyPassword.txt","clientKeyFile":"C:\RamSecretPlugin\src\main\resources\clientKey_KAAP.json","ignoreSslCerts":false,"caFilePath":"C:\RamSecretPlugin\src\main\resources\PrivateKmsCA_kst-hzz634e67d126u9p9****.pem"}]

    Parameter description

    Parameter

    Description

    Note

    regionId

    The region ID of the KMS instance.

    For specific region IDs, see Regions and endpoints.

    endpoint

    The domain name of the KMS instance, in the format {instance ID}.kms.aliyuncs.com.

    Visit the Instances page and check the Instance VPC Endpoint on the instance details page, which is the endpoint.

    clientKeyFile

    The absolute or relative path to the client key file in the JSON format.

    • Client key file: The Application Access Secret downloaded when you create a client key in the application access point (AAP). The default filename after download is ClientKey_******.json.

    • Password: The client key password downloaded when you create a client key in the AAP. The default filename after download is ClientKey_******_password.txt.

    Important

    Each client key has a unique password, both generated only upon creation. If you lose either, you must create a new client key in the AAP. For instructions, see Create an application access point.

    passwordFromFilePath or passwordFromEnvVariable

    • passwordFromFilePath: Obtains the password from a file. The value is the absolute or relative path to the file containing the client key password.

    • passwordFromEnvVariable: Obtains the password from an environment variable. The value is the name of the environment variable that the value is the client key password.

    ignoreSslCerts

    Specifies whether to ignore the validity check on the SSL certificate of the KMS instance. The KMS instance has a built-in SSL certificate that is used for identity verification and SSL- or TLS-encrypted communication. Valid values:

    • true: The validity check is ignored.

      If the value is true, the caFilePath parameter is not required.

    • false: The validity check is performed.

    In the production environment, set this parameter to false.

    caFilePath

    The absolute or relative path to the certificate authority (CA) certificate file of the KMS instance.

    The CA certificate validates the KMS instance's SSL certificate, including checks on the certificate's issuer, its validity period, and whether the domain name matches the KMS endpoint.

    Visit the Instances page. On the instance details page, click Download in the Instance CA Certificate section.

    Sample code (using environment variables)

    Replace #secretName# with your secret name.

    import com.aliyuncs.kms.secretsmanager.client.SecretCacheClient;
    import com.aliyuncs.kms.secretsmanager.client.SecretCacheClientBuilder;
    import com.aliyuncs.kms.secretsmanager.client.exception.CacheSecretException;
    import com.aliyuncs.kms.secretsmanager.client.model.SecretInfo;
    
    public class CacheClientEnvironmentSample {
    
        public static void main(String[] args) {
            try {
                // Build the secret client
                SecretCacheClient client = SecretCacheClientBuilder.newClient();
                // Use the secret client to retrieve secret information
                SecretInfo secretInfo = client.getSecretInfo("#secretName#");
                System.out.println(secretInfo);
            } catch (CacheSecretException e) {
                e.printStackTrace();
            }
        }
    }
  • Method 2: Using a custom configuration file

    Specify the custom configuration file name and path.

    Configuration file

    • Method 1: Obtain the client key password from an environment variable

      cache_client_dkms_config_info=[{"regionId":"<DKMS_REGION_ID>","endpoint":"<DKMS_ENDPOINT>","passwordFromEnvVariable":"<PASSWORD_ENV_VARIABLE>","clientKeyFile":"<CLIENT_KEY_FILE_PATH>","ignoreSslCerts":false,"caFilePath":"<CA_CERTIFICATE_FILE_PATH>"}]

      Before configurating the file, define an environment variable with a custom name and set the client key password as its value. Then, replace <PASSWORD_ENV_VARIABLE> with your variable name.

      Example:

      cache_client_dkms_config_info=[{"regionId":"ap-southeast-1","endpoint":"kst-hzz634e67d126u9p9****.cryptoservice.kms.aliyuncs.com","passwordFromEnvVariable":"passwordFromEnvVariable","clientKeyFile":"C:\RamSecretPlugin\src\main\resources\clientKey_KAAP.json","ignoreSslCerts":false,"caFilePath":"C:\RamSecretPlugin\src\main\resources\PrivateKmsCA_kst-hzz634e67d126u9p9****.pem"}]
    • Method 2: Obtain the client key password from a file

      The default filename for the Client Key Password (ClientKeyPassword) after download is clientKey_****_Password.txt. You can rename the file, but you'll need to replace <your Client Key file path> in the cache_client_dkms_config_info value with the new file path.

      cache_client_dkms_config_info=[{"regionId":"<your dkms regionId >","endpoint":"<your dkms endpoint>","passwordFromFilePath":"< your password file path >","clientKeyFile":"<your Client Key file path>","ignoreSslCerts":false,"caFilePath":"<your CA certificate file path>"}]

      Example:

      cache_client_dkms_config_info=[{"regionId":"cn-hangzhou","endpoint":"kst-hzz634e67d126u9p9****.cryptoservice.kms.aliyuncs.com","passwordFromFilePath":"C:\RamSecretPlugin\src\main\resources\clientKeyPassword.txt","clientKeyFile":"C:\RamSecretPlugin\src\main\resources\clientKey_KAAP.json","ignoreSslCerts":false,"caFilePath":"C:\RamSecretPlugin\src\main\resources\PrivateKmsCA_kst-hzz634e67d126u9p9****.pem"}]

    Parameter description

    Parameter

    Description

    Note

    regionId

    The region ID of the KMS instance.

    For specific region IDs, see Regions and endpoints.

    endpoint

    The domain name of the KMS instance, in the format {instance ID}.kms.aliyuncs.com.

    Visit the Instances page and check the Instance VPC Endpoint on the instance details page, which is the endpoint.

    clientKeyFile

    The absolute or relative path to the client key file in the JSON format.

    • Client key file: The Application Access Secret downloaded when you create a client key in the application access point (AAP). The default filename after download is ClientKey_******.json.

    • Password: The client key password downloaded when you create a client key in the AAP. The default filename after download is ClientKey_******_password.txt.

    Important

    Each client key has a unique password, both generated only upon creation. If you lose either, you must create a new client key in the AAP. For instructions, see Create an application access point.

    passwordFromFilePath or passwordFromEnvVariable

    • passwordFromFilePath: Obtains the password from a file. The value is the absolute or relative path to the file containing the client key password.

    • passwordFromEnvVariable: Obtains the password from an environment variable. The value is the name of the environment variable that the value is the client key password.

    ignoreSslCerts

    Specifies whether to ignore the validity check on the SSL certificate of the KMS instance. The KMS instance has a built-in SSL certificate that is used for identity verification and SSL- or TLS-encrypted communication. Valid values:

    • true: The validity check is ignored.

      If the value is true, the caFilePath parameter is not required.

    • false: The validity check is performed.

    In the production environment, set this parameter to false.

    caFilePath

    The absolute or relative path to the certificate authority (CA) certificate file of the KMS instance.

    The CA certificate validates the KMS instance's SSL certificate, including checks on the certificate's issuer, its validity period, and whether the domain name matches the KMS endpoint.

    Visit the Instances page. On the instance details page, click Download in the Instance CA Certificate section.

    Sample code

    Replace #customConfigFileName# with the name of your custom configuration file and #secretName# with your secret name.

    import com.aliyuncs.kms.secretsmanager.client.SecretCacheClient;
    import com.aliyuncs.kms.secretsmanager.client.SecretCacheClientBuilder;
    import com.aliyuncs.kms.secretsmanager.client.exception.CacheSecretException;
    import com.aliyuncs.kms.secretsmanager.client.model.SecretInfo;
    import com.aliyuncs.kms.secretsmanager.client.service.BaseSecretManagerClientBuilder;
    
    public class CacheClientCustomConfigFileSample {
    
        public static void main(String[] args) {
            try {
                SecretCacheClient client = SecretCacheClientBuilder.newCacheClientBuilder(
                        BaseSecretManagerClientBuilder.standard().withCustomConfigFile("#customConfigFileName#").build()).build();
                SecretInfo secretInfo = client.getSecretInfo("#secretName#");
                System.out.println(secretInfo);
            } catch (CacheSecretException e) {
                System.out.println("CacheSecretException:" + e.getMessage());
            }
        }
    }
  • Method 3: Specifying parameters (accessKey, accessSecret, and regionId)

    Applies only to the AccessKey authentication method.

    Note

    The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using the AccessKey pair to perform operations is a high-risk operation. In addition, use a RAM user to call API operations or perform routine O&M. We recommend that you do not save the AccessKey ID and AccessKey Secret in your project code. If you do, the AccessKey pair may be leaked and the security of all the resources that belong to your account may be compromised.

    In this example, the AccessKey pair is saved in ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables to implement identity authentication.

    Sample code

    Replace #regionId# with the actual region ID and #secretName# with your secret name.

    import com.aliyuncs.kms.secretsmanager.client.SecretCacheClient;
    import com.aliyuncs.kms.secretsmanager.client.SecretCacheClientBuilder;
    import com.aliyuncs.kms.secretsmanager.client.exception.CacheSecretException;
    import com.aliyuncs.kms.secretsmanager.client.model.SecretInfo;
    import com.aliyuncs.kms.secretsmanager.client.service.BaseSecretManagerClientBuilder;
    import com.aliyuncs.kms.secretsmanager.client.utils.CredentialsProviderUtils;
    
    public class CacheClientSimpleParametersSample {
    
        public static void main(String[] args) {
            try {
                SecretCacheClient client = SecretCacheClientBuilder.newCacheClientBuilder(
                        BaseSecretManagerClientBuilder.standard().withCredentialsProvider(CredentialsProviderUtils
                                .withAccessKey(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"), System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"))).withRegion("#regionId#").build()).build();
                SecretInfo secretInfo = client.getSecretInfo("#secretName#");
                System.out.println(secretInfo);
            } catch (CacheSecretException e) {
                e.printStackTrace();
            }
        }
    }

Python

  • Method 1: Using environment variables or the secretsmanager.properties configuration file

    You can use either environment variables or the secretsmanager.properties configuration file.

    Environment variables

    • Method 1: Obtain ClientKey credentials through environment variables

      Variable

      Value

      cache_client_dkms_config_info

      The format is [{"regionId":"<DKMS_REGION_ID >","endpoint":"<DKMS_ENDPOINT>","passwordFromEnvVariable":"<PASSWORD_ENV_VARIABLE>","clientKeyFile":"<CLIENT_KEY_FILE_PATH>","ignoreSslCerts":false,"caFilePath":"<CA_CERTIFICATE_FILE_PATH>"}].

      Before configuring it, define an environment variable with a custom name and set the client key password as its value. Then, replace <PASSWORD_ENV_VARIABLE> with your variable name.

      For Linux systems, the example is as follows:

      export cache_client_dkms_config_info=[{"regionId":"ap-southeast-1","endpoint":"kst-hzz634e67d126u9p9****.cryptoservice.kms.aliyuncs.com","passwordFromEnvVariable":"passwordFromEnvVariable","clientKeyFile":"C:\RamSecretPlugin\src\main\resources\clientKey_KAAP.json","ignoreSslCerts":false,"caFilePath":"C:\RamSecretPlugin\src\main\resources\PrivateKmsCA_kst-hzz634e67d126u9p9****.pem"}]
    • Method 2: Obtain the client key password from a file

      The default filename for the client key password after download is clientKey_****_Password.txt. You can rename the file, but you'll need to replace <your Client Key file path> in the cache_client_dkms_config_info value with the new file path.

      Variable

      Value

      cache_client_dkms_config_info

      The format is: [{"regionId":"<DKMS_REGION_ID>","endpoint":"<DKMS_ENDPOINT>","passwordFromFilePath":"<PASSWORD_FILE_PATH>","clientKeyFile":"<CLIENT_KEY_FILE_PATH>","ignoreSslCerts":false,"caFilePath":"<CA_CERTIFICATE_FILE_PATH>"}].

      For Linux systems, the example is as follows:

      export cache_client_dkms_config_info=[{"regionId":"ap-southeast-1","endpoint":"kst-hzz634e67d126u9p9****.cryptoservice.kms.aliyuncs.com","passwordFromFilePath":"C:\RamSecretPlugin\src\main\resources\clientKeyPassword.txt","clientKeyFile":"C:\RamSecretPlugin\src\main\resources\clientKey_KAAP.json","ignoreSslCerts":false,"caFilePath":"C:\RamSecretPlugin\src\main\resources\PrivateKmsCA_kst-hzz634e67d126u9p9****.pem"}]

    Parameter description

    Parameter

    Description

    Note

    regionId

    The region ID of the KMS instance.

    For specific region IDs, see Regions and endpoints.

    endpoint

    The domain name of the KMS instance, in the format {instance ID}.kms.aliyuncs.com.

    Visit the Instances page and check the Instance VPC Endpoint on the instance details page, which is the endpoint.

    clientKeyFile

    The absolute or relative path to the client key file in the JSON format.

    • Client key file: The Application Access Secret downloaded when you create a client key in the application access point (AAP). The default filename after download is ClientKey_******.json.

    • Password: The client key password downloaded when you create a client key in the AAP. The default filename after download is ClientKey_******_password.txt.

    Important

    Each client key has a unique password, both generated only upon creation. If you lose either, you must create a new client key in the AAP. For instructions, see Create an application access point.

    passwordFromFilePath or passwordFromEnvVariable

    • passwordFromFilePath: Obtains the password from a file. The value is the absolute or relative path to the file containing the client key password.

    • passwordFromEnvVariable: Obtains the password from an environment variable. The value is the name of the environment variable that the value is the client key password.

    ignoreSslCerts

    Specifies whether to ignore the validity check on the SSL certificate of the KMS instance. The KMS instance has a built-in SSL certificate that is used for identity verification and SSL- or TLS-encrypted communication. Valid values:

    • true: The validity check is ignored.

      If the value is true, the caFilePath parameter is not required.

    • false: The validity check is performed.

    In the production environment, set this parameter to false.

    caFilePath

    The absolute or relative path to the certificate authority (CA) certificate file of the KMS instance.

    The CA certificate validates the KMS instance's SSL certificate, including checks on the certificate's issuer, its validity period, and whether the domain name matches the KMS endpoint.

    Visit the Instances page. On the instance details page, click Download in the Instance CA Certificate section.

    Configuration file: secretsmanager.properties

    The configuration file name is fixed as secretsmanager.properties.

    • Method 1: Obtain the client key password from an environment variable

      cache_client_dkms_config_info=[{"regionId":"<DKMS_REGION_ID>","endpoint":"<DKMS_ENDPOINT>","passwordFromEnvVariable":"<PASSWORD_ENV_VARIABLE>","clientKeyFile":"<CLIENT_KEY_FILE_PATH>","ignoreSslCerts":false,"caFilePath":"<CA_CERTIFICATE_FILE_PATH>"}]

      Before configurating the file, define an environment variable with a custom name and set the client key password as its value. Then, replace <PASSWORD_ENV_VARIABLE> with your variable name.

      Example:

      cache_client_dkms_config_info=[{"regionId":"ap-southeast-1","endpoint":"kst-hzz634e67d126u9p9****.cryptoservice.kms.aliyuncs.com","passwordFromEnvVariable":"passwordFromEnvVariable","clientKeyFile":"C:\RamSecretPlugin\src\main\resources\clientKey_KAAP.json","ignoreSslCerts":false,"caFilePath":"C:\RamSecretPlugin\src\main\resources\PrivateKmsCA_kst-hzz634e67d126u9p9****.pem"}]
    • Method 2: Obtain the client key password from a file

      The default filename for the Client Key Password (ClientKeyPassword) after download is clientKey_****_Password.txt. You can rename the file, but you'll need to replace <your Client Key file path> in the cache_client_dkms_config_info value with the new file path.

      cache_client_dkms_config_info=[{"regionId":"<your dkms regionId >","endpoint":"<your dkms endpoint>","passwordFromFilePath":"< your password file path >","clientKeyFile":"<your Client Key file path>","ignoreSslCerts":false,"caFilePath":"<your CA certificate file path>"}]

      Example:

      cache_client_dkms_config_info=[{"regionId":"cn-hangzhou","endpoint":"kst-hzz634e67d126u9p9****.cryptoservice.kms.aliyuncs.com","passwordFromFilePath":"C:\RamSecretPlugin\src\main\resources\clientKeyPassword.txt","clientKeyFile":"C:\RamSecretPlugin\src\main\resources\clientKey_KAAP.json","ignoreSslCerts":false,"caFilePath":"C:\RamSecretPlugin\src\main\resources\PrivateKmsCA_kst-hzz634e67d126u9p9****.pem"}]

    Parameter description

    Parameter

    Description

    Note

    regionId

    The region ID of the KMS instance.

    For specific region IDs, see Regions and endpoints.

    endpoint

    The domain name of the KMS instance, in the format {instance ID}.kms.aliyuncs.com.

    Visit the Instances page and check the Instance VPC Endpoint on the instance details page, which is the endpoint.

    clientKeyFile

    The absolute or relative path to the client key file in the JSON format.

    • Client key file: The Application Access Secret downloaded when you create a client key in the application access point (AAP). The default filename after download is ClientKey_******.json.

    • Password: The client key password downloaded when you create a client key in the AAP. The default filename after download is ClientKey_******_password.txt.

    Important

    Each client key has a unique password, both generated only upon creation. If you lose either, you must create a new client key in the AAP. For instructions, see Create an application access point.

    passwordFromFilePath or passwordFromEnvVariable

    • passwordFromFilePath: Obtains the password from a file. The value is the absolute or relative path to the file containing the client key password.

    • passwordFromEnvVariable: Obtains the password from an environment variable. The value is the name of the environment variable that the value is the client key password.

    ignoreSslCerts

    Specifies whether to ignore the validity check on the SSL certificate of the KMS instance. The KMS instance has a built-in SSL certificate that is used for identity verification and SSL- or TLS-encrypted communication. Valid values:

    • true: The validity check is ignored.

      If the value is true, the caFilePath parameter is not required.

    • false: The validity check is performed.

    In the production environment, set this parameter to false.

    caFilePath

    The absolute or relative path to the certificate authority (CA) certificate file of the KMS instance.

    The CA certificate validates the KMS instance's SSL certificate, including checks on the certificate's issuer, its validity period, and whether the domain name matches the KMS endpoint.

    Visit the Instances page. On the instance details page, click Download in the Instance CA Certificate section.

    Sample code (using environment variables)

    Replace #secretName# with your secret name.

    from alibaba_cloud_secretsmanager_client.secret_manager_cache_client_builder import SecretManagerCacheClientBuilder
    
    if __name__ == '__main__':
        # Build the secret client
        secret_cache_client = SecretManagerCacheClientBuilder.new_client()
        # Use the secret client to retrieve secret information
        secret_info = secret_cache_client.get_secret_info("#secretName#")
        print(secret_info.__dict__)
  • Method 2: Specifying parameters (accessKey, accessSecret, and regionId)

    Applies only to the AccessKey authentication method.

    Note

    The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using the AccessKey pair to perform operations is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. We recommend that you do not save the AccessKey ID and AccessKey Secret in your project code. Otherwise, the AccessKey pair may be leaked and the security of all the resources that belong to your account may be compromised.

    In this example, the AccessKey pair is saved in ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables to implement identity authentication.

    Sample code

    Replace #regionId# with the actual region ID and #secretName# with your secret name.

    import os
    
    from alibaba_cloud_secretsmanager_client.secret_manager_cache_client_builder import SecretManagerCacheClientBuilder
    from alibaba_cloud_secretsmanager_client.service.default_secret_manager_client_builder import DefaultSecretManagerClientBuilder
    
    if __name__ == '__main__':
        secret_cache_client = SecretManagerCacheClientBuilder.new_cache_client_builder(DefaultSecretManagerClientBuilder.standard() \
            .with_access_key(os.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"), os.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")) \
            .with_region("#regionId#").build()) \
        .build();
        secret_info = secret_cache_client.get_secret_info("#secretName#")
        print(secret_info.__dict__)

Go

The sample code for retrieving secret values varies based on the client initialization method. Choose one of the following methods.

  • Method 1: Using environment variables or the secretsmanager.properties configuration file

    You can use either environment variables or the secretsmanager.properties configuration file.

    Environment variables

    • Method 1: Obtain ClientKey credentials through environment variables

      Variable

      Value

      cache_client_dkms_config_info

      The format is [{"regionId":"<DKMS_REGION_ID >","endpoint":"<DKMS_ENDPOINT>","passwordFromEnvVariable":"<PASSWORD_ENV_VARIABLE>","clientKeyFile":"<CLIENT_KEY_FILE_PATH>","ignoreSslCerts":false,"caFilePath":"<CA_CERTIFICATE_FILE_PATH>"}].

      Before configuring it, define an environment variable with a custom name and set the client key password as its value. Then, replace <PASSWORD_ENV_VARIABLE> with your variable name.

      For Linux systems, the example is as follows:

      export cache_client_dkms_config_info=[{"regionId":"ap-southeast-1","endpoint":"kst-hzz634e67d126u9p9****.cryptoservice.kms.aliyuncs.com","passwordFromEnvVariable":"passwordFromEnvVariable","clientKeyFile":"C:\RamSecretPlugin\src\main\resources\clientKey_KAAP.json","ignoreSslCerts":false,"caFilePath":"C:\RamSecretPlugin\src\main\resources\PrivateKmsCA_kst-hzz634e67d126u9p9****.pem"}]
    • Method 2: Obtain the client key password from a file

      The default filename for the client key password after download is clientKey_****_Password.txt. You can rename the file, but you'll need to replace <your Client Key file path> in the cache_client_dkms_config_info value with the new file path.

      Variable

      Value

      cache_client_dkms_config_info

      The format is: [{"regionId":"<DKMS_REGION_ID>","endpoint":"<DKMS_ENDPOINT>","passwordFromFilePath":"<PASSWORD_FILE_PATH>","clientKeyFile":"<CLIENT_KEY_FILE_PATH>","ignoreSslCerts":false,"caFilePath":"<CA_CERTIFICATE_FILE_PATH>"}].

      For Linux systems, the example is as follows:

      export cache_client_dkms_config_info=[{"regionId":"ap-southeast-1","endpoint":"kst-hzz634e67d126u9p9****.cryptoservice.kms.aliyuncs.com","passwordFromFilePath":"C:\RamSecretPlugin\src\main\resources\clientKeyPassword.txt","clientKeyFile":"C:\RamSecretPlugin\src\main\resources\clientKey_KAAP.json","ignoreSslCerts":false,"caFilePath":"C:\RamSecretPlugin\src\main\resources\PrivateKmsCA_kst-hzz634e67d126u9p9****.pem"}]

    Parameter description

    Parameter

    Description

    Note

    regionId

    The region ID of the KMS instance.

    For specific region IDs, see Regions and endpoints.

    endpoint

    The domain name of the KMS instance, in the format {instance ID}.kms.aliyuncs.com.

    Visit the Instances page and check the Instance VPC Endpoint on the instance details page, which is the endpoint.

    clientKeyFile

    The absolute or relative path to the client key file in the JSON format.

    • Client key file: The Application Access Secret downloaded when you create a client key in the application access point (AAP). The default filename after download is ClientKey_******.json.

    • Password: The client key password downloaded when you create a client key in the AAP. The default filename after download is ClientKey_******_password.txt.

    Important

    Each client key has a unique password, both generated only upon creation. If you lose either, you must create a new client key in the AAP. For instructions, see Create an application access point.

    passwordFromFilePath or passwordFromEnvVariable

    • passwordFromFilePath: Obtains the password from a file. The value is the absolute or relative path to the file containing the client key password.

    • passwordFromEnvVariable: Obtains the password from an environment variable. The value is the name of the environment variable that the value is the client key password.

    ignoreSslCerts

    Specifies whether to ignore the validity check on the SSL certificate of the KMS instance. The KMS instance has a built-in SSL certificate that is used for identity verification and SSL- or TLS-encrypted communication. Valid values:

    • true: The validity check is ignored.

      If the value is true, the caFilePath parameter is not required.

    • false: The validity check is performed.

    In the production environment, set this parameter to false.

    caFilePath

    The absolute or relative path to the certificate authority (CA) certificate file of the KMS instance.

    The CA certificate validates the KMS instance's SSL certificate, including checks on the certificate's issuer, its validity period, and whether the domain name matches the KMS endpoint.

    Visit the Instances page. On the instance details page, click Download in the Instance CA Certificate section.

    Configuration file: secretsmanager.properties

    The configuration file name is fixed as secretsmanager.properties.

    • Method 1: Obtain the client key password from an environment variable

      cache_client_dkms_config_info=[{"regionId":"<DKMS_REGION_ID>","endpoint":"<DKMS_ENDPOINT>","passwordFromEnvVariable":"<PASSWORD_ENV_VARIABLE>","clientKeyFile":"<CLIENT_KEY_FILE_PATH>","ignoreSslCerts":false,"caFilePath":"<CA_CERTIFICATE_FILE_PATH>"}]

      Before configurating the file, define an environment variable with a custom name and set the client key password as its value. Then, replace <PASSWORD_ENV_VARIABLE> with your variable name.

      Example:

      cache_client_dkms_config_info=[{"regionId":"ap-southeast-1","endpoint":"kst-hzz634e67d126u9p9****.cryptoservice.kms.aliyuncs.com","passwordFromEnvVariable":"passwordFromEnvVariable","clientKeyFile":"C:\RamSecretPlugin\src\main\resources\clientKey_KAAP.json","ignoreSslCerts":false,"caFilePath":"C:\RamSecretPlugin\src\main\resources\PrivateKmsCA_kst-hzz634e67d126u9p9****.pem"}]
    • Method 2: Obtain the client key password from a file

      The default filename for the Client Key Password (ClientKeyPassword) after download is clientKey_****_Password.txt. You can rename the file, but you'll need to replace <your Client Key file path> in the cache_client_dkms_config_info value with the new file path.

      cache_client_dkms_config_info=[{"regionId":"<your dkms regionId >","endpoint":"<your dkms endpoint>","passwordFromFilePath":"< your password file path >","clientKeyFile":"<your Client Key file path>","ignoreSslCerts":false,"caFilePath":"<your CA certificate file path>"}]

      Example:

      cache_client_dkms_config_info=[{"regionId":"cn-hangzhou","endpoint":"kst-hzz634e67d126u9p9****.cryptoservice.kms.aliyuncs.com","passwordFromFilePath":"C:\RamSecretPlugin\src\main\resources\clientKeyPassword.txt","clientKeyFile":"C:\RamSecretPlugin\src\main\resources\clientKey_KAAP.json","ignoreSslCerts":false,"caFilePath":"C:\RamSecretPlugin\src\main\resources\PrivateKmsCA_kst-hzz634e67d126u9p9****.pem"}]

    Parameter description

    Parameter

    Description

    Note

    regionId

    The region ID of the KMS instance.

    For specific region IDs, see Regions and endpoints.

    endpoint

    The domain name of the KMS instance, in the format {instance ID}.kms.aliyuncs.com.

    Visit the Instances page and check the Instance VPC Endpoint on the instance details page, which is the endpoint.

    clientKeyFile

    The absolute or relative path to the client key file in the JSON format.

    • Client key file: The Application Access Secret downloaded when you create a client key in the application access point (AAP). The default filename after download is ClientKey_******.json.

    • Password: The client key password downloaded when you create a client key in the AAP. The default filename after download is ClientKey_******_password.txt.

    Important

    Each client key has a unique password, both generated only upon creation. If you lose either, you must create a new client key in the AAP. For instructions, see Create an application access point.

    passwordFromFilePath or passwordFromEnvVariable

    • passwordFromFilePath: Obtains the password from a file. The value is the absolute or relative path to the file containing the client key password.

    • passwordFromEnvVariable: Obtains the password from an environment variable. The value is the name of the environment variable that the value is the client key password.

    ignoreSslCerts

    Specifies whether to ignore the validity check on the SSL certificate of the KMS instance. The KMS instance has a built-in SSL certificate that is used for identity verification and SSL- or TLS-encrypted communication. Valid values:

    • true: The validity check is ignored.

      If the value is true, the caFilePath parameter is not required.

    • false: The validity check is performed.

    In the production environment, set this parameter to false.

    caFilePath

    The absolute or relative path to the certificate authority (CA) certificate file of the KMS instance.

    The CA certificate validates the KMS instance's SSL certificate, including checks on the certificate's issuer, its validity period, and whether the domain name matches the KMS endpoint.

    Visit the Instances page. On the instance details page, click Download in the Instance CA Certificate section.

    Sample code (using environment variables)

    Replace #secretName# with your secret name.

    package main
    
    import (
        "fmt"
        "github.com/aliyun/aliyun-secretsmanager-client-go/sdk"
    )
    func main() { 
       // Build the secret client
        client, err := sdk.NewClient()
        if err != nil {
            // Handle exceptions
            panic(err)
        }
       // Use the secret client to retrieve secret information
        secretInfo, err := client.GetSecretInfo("#secretName#")
        if err != nil {
            // Handle exceptions
            panic(err)
        }
        fmt.Printf("SecretValue:%s\n",secretInfo.SecretValue)
    }
  • Method 2: Specifying parameters (accessKey, accessSecret, and regionId)

    Applies only to the AccessKey authentication method.

    Note

    The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using the AccessKey pair to perform operations is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. We recommend that you do not save the AccessKey ID and AccessKey Secret in your project code. Otherwise, the AccessKey pair may be leaked and the security of all the resources that belong to your account may be compromised.

    In this example, the AccessKey pair is saved in ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables to implement identity authentication.

    Sample code

    Replace #regionId# with the actual region ID and #secretName# with your secret name.

    package main
    
    import (
    	"github.com/aliyun/aliyun-secretsmanager-client-go/sdk/service"
    	"github.com/aliyun/aliyun-secretsmanager-client-go/sdk"
    	"os"
    )
    
    func main() {
    	client, err := sdk.NewSecretCacheClientBuilder(service.NewDefaultSecretManagerClientBuilder().Standard().WithAccessKey(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"), os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")).WithRegion("#regionId#").Build()).Build()
    	if err != nil {
    		// Handle exceptions
    		panic(err)
    	}
    	secretInfo, err := client.GetSecretInfo("#secretName#")
    	if err != nil {
    		// Handle exceptions
    		panic(err)
    	}
    }