All Products
Search
Document Center

Key Management Service:Secret client

Last Updated:Apr 28, 2024

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

SDK overview

The secret client is based on KMS API and KMS Instance API and encapsulates secret caching capabilities, best practices, and design patterns. This simplifies the process for developers to integrate the secret client into applications. In addition, KMS provides KMS Instance SDK and Alibaba Cloud SDK for you to retrieve secret values. For more information, see SDK references.

Note

To manage a secret, you must use Alibaba Cloud SDK.

The secret client provides the following features:

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

  • Encapsulates the capabilities to cache and refresh secrets in applications.

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

  • Uses a plug-in design model that allows developers to configure custom features such as extended cache and error-based retry.

Precautions

  • Supported secret types: generic secrets, Resource Access Management (RAM) secrets, Elastic Compute Service (ECS) secrets, and ApsaraDB RDS secrets.

  • Supported programming languages: Java, Go, and Python. Java 8 and later are supported.

  • Supported access credentials: AccessKey pair, RAM role, instance RAM role of an ECS instance, Security Token Service (STS) token, and client key. Client keys are recommended.

Step 1: Create an access credential

    Important
    • If you use AccessKey pairs, RAM roles, instance RAM roles of ECS instances, or STS tokens as credentials, use a KMS endpoint to retrieve the values of secrets that store the credentials. If you use client keys as credentials, use a KMS endpoint or a KMS instance endpoint to retrieve the values of secrets that store the credentials. For more information about endpoints, see SDK references.

    • KMS instance endpoints support high performance. We recommend that you use client keys as credentials and use KMS instance endpoints to retrieve the values of secrets that store the client keys.

AccessKey pair

For more information, see Create an AccessKey pair.

RAM role

  1. Create a RAM role. For more information, see Create a RAM role.

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

    Note

    RamRoleArn is the Alibaba Cloud Resource Name (ARN) of the RAM role, which is the ID of the RAM role to be assumed. Format: acs:ram::$accountID:role/$roleName. $accountID is the ID of the Alibaba Cloud account. $roleName is the name of the RAM role.

Instance RAM role of an ECS instance

Attach an instance RAM role to an ECS instance. For more information, see Attach an instance RAM role to an ECS instance.

STS

  1. Create a RAM user or a RAM role. For more information, see Create a RAM user and Create a RAM role.

  2. Grant the AliyunSTSAssumeRoleAccess permission to the RAM user or the RAM role. For more information, see Grant permissions to a RAM user and Grant permissions to a RAM role.

  3. Use the RAM user or the RAM role to call the AssumeRole operation of STS to obtain an STS token. For more information, see AssumeRole.

Client key

Create an application access point (AAP) and then create a client key in the AAP. For more information, see Create an AAP.

Step 2: Install the secret client

Java

Visit alibabacloud-secretsmanager-client-java to view more installation information and source code.

Install the secret client in your project by using Maven.

<dependency>
    <groupId>com.aliyun</groupId>
    <artifactId>alibabacloud-secretsmanager-client</artifactId>
    <version>x.x.x</version>
</dependency>
Note

We recommend that you install the latest version.

Python

Visit aliyun-secretsmanager-client-python to view more installation information and source code.

Run the pip command to install the secret client.

pip install aliyun-secret-manager-client

Go

Visit aliyun-secretsmanager-client-go to view more installation information and source code.

Run the go get command to use the secret client in your project.

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

Step 3: Build the secret client

Java

  • Method 1: Use environment variables or the secretsmanager.properties configuration file to build the secret client

    For more information about environment variables, see Appendix 1: Environment variables. For more information about configuration files, see Appendix 2: Configuration files. The name of the configuration file is fixed as secretsmanager.properties.

    Replace #secretName# in the sample code with the name of your secret.

    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: Use a custom configuration file to build the secret client

    For more information about configuration files, see Appendix 2: Configuration files. Specify the name and path of the custom configuration file.

    Replace #customConfigFileName# in the sample code with the name of the custom configuration file. Replace #secretName# with the name of your secret.

    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: Configure parameters such as accessKey, accessSecret, and regionId to build the secret client

    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 the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables to implement identity authentication. For more information about how to configure authentication information, see Configure credentials.

    Replace #regionId# in the sample code with the actual region ID. Replace #secretName# with the name of your secret.

    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: Use environment variables to build the secret client

    For more information about environment variables, see Appendix 1: Environment variables. Replace #secretName# in the sample code with the name of your secret.

    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: Configure parameters such as accessKey, accessSecret, and regionId to build the secret client

    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 the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables to implement identity authentication. For more information about how to configure authentication information, see Instantiate a client and configure a credential.

    Replace #regionId# in the sample code with the actual region ID. Replace #secretName# with the name of your secret.

    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: Use environment variables or the secretsmanager.properties configuration file to build the secret client

    For more information about environment variables, see Appendix 1: Environment variables. For more information about configuration files, see Appendix 2: Configuration files. The name of the configuration file is fixed as secretsmanager.properties.

    Replace #secretName# in the sample code with the name of your secret.

    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)
    }
  • Configure parameters such as accessKey, accessSecret, and regionId to build the secret client

    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 the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables to implement identity authentication. For more information about how to configure authentication information, see Instantiate a client and configure a credential.

    Replace #regionId# in the sample code with the actual region ID. Replace #secretName# with the name of your secret.

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

Appendix 1: Environment variables

The environment variables vary based on the authentication method that you use. For more information, see the following tables.

AccessKey pair

Parameter

Example

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 value is in the [{"regionId":"<your region id>"}] format. Replace <your region id> with the actual region ID.

RAM role

Parameter

Example

credentials_type

The value is fixed as ram_role.

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 value is in the [{"regionId":"<your region id>"}] format. Replace <your region id> with the actual region ID.

Instance RAM role of an ECS instance

Parameter

Example

credentials_type

The value is fixed as ecs_ram_role.

credentials_role_session_name

The name of the RAM role.

cache_client_region_id

The value is in the [{"regionId":"<your region id>"}] format. Replace <your region id> with the actual region ID.

STS

Parameter

Example

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 value is in the [{"regionId":"<your region id>"}] format. Replace <your region id> with the actual region ID.

Client key

  • KMS endpoint

    Parameter

    Example

    credentials_type

    The value is fixed as client_key.

    client_key_password_from_env_variable

    Specifies that the password of the client key is obtained from an environment variable. The value is the name of the environment variable that contains the password.

    To configure the parameter, you must save the password to an environment variable. You can specify a custom name for the environment variable.

    client_key_password_from_file_path

    Specifies that the password of the client key is obtained from a file. The value is the absolute or relative path to the password file.

    To configure the parameter, you must save the password to a file. You can specify a custom name for the file.

    Note

    client_key_password_from_env_variable and client_key_password_from_file_path are mutually exclusive options.

    client_key_private_key_path

    The absolute or relative path to the client key file.

    To configure the parameter, you must save the client key file in a secure location. You can specify a custom name for the file.

    cache_client_region_id

    The value is in the [{"regionId":"<your region id>"}] format. Replace <your region id> with the actual region ID.

  • KMS instance endpoint

    Parameter

    Example

    cache_client_dkms_config_info

    • Method 1: Obtain the password of the client key from a file

      Save the password to a file. The name of the file must be the same as the value of passwordFromFilePath.

      cache_client_dkms_config_info=[{"regionId":"<your dkms region>","endpoint":"<your dkms endpoint>","passwordFromFilePath":"< your password file path >","clientKeyFile":"<your Client Key file path>","ignoreSslCerts":false,"caFilePath":"<your CA certificate file path>"}]
    • Method 2: Obtain the password for the client key from an environment variable

      Save the password to an environment variable. The name of the environment variable must be the same as the value of passwordFromEnvVariable.

      cache_client_dkms_config_info=[{"regionId":"<your dkms region>","endpoint":"<your dkms endpoint>","passwordFromEnvVariable":"<your_password_env_variable>","clientKeyFile":"<your ClientKey file path>","ignoreSslCerts":false,"caFilePath":"<your CA certificate file path>"}]
    Note

    For more information about the values in cache_client_dkms_config_info, see Appendix 2: Configuration files.

Appendix 2: Configuration files

Different authentication methods require different configuration files.

AccessKey pair

# The type of the access credential.
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#"}]

RAM role

# The type of the access credential.
credentials_type=ram_role
# The name of the RAM 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#"}]

Instance RAM role of an ECS instance

# The type of the access credential.
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#"}]

STS

# The type of the access credential.
credentials_type=sts
# The name of the RAM 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#"}]

Client key

  • KMS endpoint

    # The type of the access credential.
    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#
    
    # The path to 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#"}]
  • KMS instance endpoint

    The configuration item is cache_client_dkms_config_info. The cache_client_dkms_config_info configuration item is a JSON array. You can configure multiple KMS instances to ensure high service availability and disaster recovery capabilities.

    • Method 1: Obtain the password of the client key from a file

      Save the password to a file. The name of the file must be the same as the value of passwordFromFilePath.

      cache_client_dkms_config_info=[{"regionId":"<your dkms region>","endpoint":"<your dkms endpoint>","passwordFromFilePath":"< your password file path >","clientKeyFile":"<your Client Key file path>","ignoreSslCerts":false,"caFilePath":"<your CA certificate file path>"}]
    • Method 2: Obtain the password for the client key from an environment variable

      Save the password to an environment variable. The name of the environment variable must be the same as the value of passwordFromEnvVariable.

      cache_client_dkms_config_info=[{"regionId":"<your dkms region>","endpoint":"<your dkms endpoint>","passwordFromEnvVariable":"<your_password_env_variable>","clientKeyFile":"<your ClientKey file path>","ignoreSslCerts":false,"caFilePath":"<your CA certificate file path>"}]

    Parameter description

    Parameter

    Description

    Remarks

    regionId

    The ID of the region where the KMS instance resides.

    For more information about how to obtain the region ID, see Regions and endpoints.

    endpoint

    The endpoint of the KMS instance, which is in the {Instance ID}.kms.aliyuncs.com format.

    To view the endpoint of a KMS instance, go to the Instances page in the KMS console, view the details of the KMS instance, obtain the value of Instance VPC Endpoint, and then remove https:// from the value.

    clientKeyFile

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

    • Client key file: The file is downloaded when you create a client key for an AAP. The file stores the content of Application Access Secret(ClientKeyContent) and is named in the ClientKey_******.json format.

    • Password file: The file is downloaded when you create a client key for an AAP. The file stores the content of Password and is named in the ClientKey_******_password.txt format.

    Important

    The client key and the password have a one-to-one correspondence. You can obtain both only when you create the client key. If you do not save the client key or password when you create the client key, you must create another client key. For more information, see Create an AAP.

    passwordFromFilePath or passwordFromEnvVariable

    • passwordFromFilePath: The password of the client key is obtained from a file. The value is the absolute or relative path to the file that contains the password of the client key. To configure passwordFromFilePath, you must save the password to a file.

    • passwordFromEnvVariable: The password for the client key is obtained from an environment variable. The value is the name of the environment variable that contains the password of the client key. To configure passwordFromEnvVariable, you must save the password to an environment variable.

    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-encrypted or TLS-encrypted communication. Valid values:

    • true: The validity check is ignored.

      Note

      If you set this parameter to true, you do not need to configure caFilePath.

    • 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 is used to check the validity of the SSL certificate of the KMS instance. For example, you can check whether the SSL certificate is issued by the required CA, whether the SSL certificate is within the validity period, and whether the domain name bound to the SSL certificate is the endpoint of the KMS instance.

    To obtain the CA certificate, go to the Instances page and click Download below Instance CA Certificate.