全部产品
Search
文档中心

Key Management Service:Contoh kode untuk mengambil nilai rahasia

更新时间:Jul 02, 2025

Setelah menginisialisasi SDK client instance KMS, Anda dapat memanggil API GetSecretValue untuk mengambil nilai rahasia. Topik ini menyediakan contoh kode terkait.

Sumber kode Github:

Contoh dalam topik ini menggunakan Python 3.

Contoh lengkap

# -*- 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()
# Atur protokol koneksi ke "https". Layanan instance KMS hanya mengizinkan akses melalui protokol HTTPS.
config.protocol = "https"
# Client Key.
config.client_key_file = "<CLIENT_KEY_FILE>"
# Kata sandi dekripsi Client Key.
config.password = os.getenv('CLIENT_KEY_PASSWORD')
# Atur titik akhir ke <ID instance KMS Anda>.cryptoservice.kms.aliyuncs.com.
config.endpoint = "<ENDPOINT>"
client = Client(config)


def get_secret_value(secret_name):
    request = GetSecretValueRequest()
    request.secret_name = secret_name
    runtime_options = RuntimeOptions()
    # Abaikan sertifikat sisi server.
    # runtime_options.ignore_ssl = True
    # verify menunjukkan jalur sertifikat CA instance.
    runtime_options.verify = "<CA_CERTIFICATE_FILE_PATH>"
    resp = client.get_secret_value_with_options(request, runtime_options)
    print(resp)


secret_name = "<SECRET_NAME>"
get_secret_value(secret_name)

Penjelasan contoh

Inisialisasi client

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

config = Config()
# Protokol koneksi. Atur nilainya menjadi https. Layanan instance KMS hanya mengizinkan akses melalui protokol HTTPS.
config.protocol = "https"

# Client Key.
config.client_key_file = "<CLIENT_KEY_FILE>"

# Kata sandi dekripsi Client Key.
config.password = os.getenv('CLIENT_KEY_PASSWORD')

# Titik akhir instance KMS Anda. Atur nilainya dalam format berikut: <ID instance KMS Anda>.cryptoservice.kms.aliyuncs.com.
config.endpoint = "<ENDPOINT>"
client = Client(config)

Panggil GetSecretValue API

def get_secret_value(secret_name):
    request = GetSecretValueRequest()
    request.secret_name = secret_name
    runtime_options = RuntimeOptions()
    # Abaikan sertifikat sisi server.
    # runtime_options.ignore_ssl = True
    # verify menunjukkan jalur sertifikat CA instance.
    runtime_options.verify = "<CA_CERTIFICATE_FILE_PATH>"
    resp = client.get_secret_value_with_options(request, runtime_options)
    print(resp)