全部產品
Search
文件中心

Key Management Service:擷取憑據值樣本

更新時間:Dec 26, 2024

初始化KMS執行個體SDK用戶端後,您可以通過用戶端調用GetSecretValue介面擷取憑據值。本文介紹擷取憑據值的程式碼範例。

完整程式碼範例

調用GetSecretValue介面擷取憑據值。

Python 2版本源碼github地址:get_secret_value_sample.py

Python 3版本源碼github地址:get_secret_value_sample.py

本文以Python 3版本為例介紹。

擷取憑據值完整程式碼範例

# -*- coding: utf-8 -*-
import os

from openapi.models import Config
from openapi_util.models import RuntimeOptions
from sdk.client import Client
from sdk.models import GetSecretValueRequest

config = Config()
# 連線協定請設定為"https"。KMS執行個體服務僅允許通過HTTPS協議訪問。
config.protocol = "https"
# Client Key。
config.client_key_file = "<your-client-key-file>"
# Client Key解密口令。
config.password = os.getenv('CLIENT_KEY_PASSWORD')
# 設定endpoint為<your KMS Instance Id>.cryptoservice.kms.aliyuncs.com。
config.endpoint = "<your-endpoint>"
client = Client(config)


def get_secret_value(secret_name):
    request = GetSecretValueRequest()
    request.secret_name = secret_name
    runtime_options = RuntimeOptions()
    # 忽略服務端認證
    # runtime_options.ignore_ssl = True
    # verify表示執行個體CA認證的路徑
    runtime_options.verify = "<your-ca-certificate-file-path>"
    resp = client.get_secret_value_with_options(request, runtime_options)
    print(resp)


secret_name = "<your-secret-name>"
get_secret_value(secret_name)

程式碼範例解析

初始化用戶端

關於初始化用戶端的詳細介紹,請參見初始化用戶端

# -*- coding: utf-8 -*-
from openapi.models import Config
from sdk.client import Client

config = Config()
# 連線協定請設定為"https"。KMS執行個體服務僅允許通過HTTPS協議訪問。
config.protocol = "https"

# Client Key。
config.client_key_file = "<your-client-key-file>"

# Client Key解密口令。
config.password = os.getenv('CLIENT_KEY_PASSWORD')

# 設定endpoint為<your KMS Instance Id>.cryptoservice.kms.aliyuncs.com。
config.endpoint = "<your-endpoint>"
client = Client(config)

調用GetSecretValue介面擷取憑據值

def get_secret_value(secret_name):
    request = GetSecretValueRequest()
    request.secret_name = secret_name
    runtime_options = RuntimeOptions()
    # 忽略服務端認證
    # runtime_options.ignore_ssl = True
    # verify表示執行個體CA認證的路徑
    runtime_options.verify = "<your-ca-certificate-file-path>"
    resp = client.get_secret_value_with_options(request, runtime_options)
    print(resp)