Todos os produtos
Search
Central de documentação

Key Management Service:Código de exemplo para recuperar o valor do segredo

Última atualização: Jun 27, 2026

Utilize o SDK para Python 3 para chamar a API GetSecretValue e obter um valor de segredo de uma instância do KMS.

Para Python 2, consulte o source no GitHub. Para Python 3, acesse o source no GitHub.

Pré-requisitos

Antes de começar, verifique se você já possui um cliente SDK da instância do KMS inicializado. Consulte Inicializar o cliente.

Exemplo completo

O exemplo abaixo inicializa um cliente e chama a API GetSecretValue para recuperar um segredo pelo nome.

# -*- coding: utf-8 -*-
"""
Retrieve a secret value from a KMS instance using the GetSecretValue API.
"""
import os

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

# Configure the client
config = Config()
# KMS instance services only allow access through HTTPS.
config.protocol = "https"
# Path to your Client Key file.
config.client_key_file = "<CLIENT_KEY_FILE>"
# Client Key decryption password, read from an environment variable.
config.password = os.getenv('CLIENT_KEY_PASSWORD')
# Endpoint format: <your-kms-instance-id>.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()
    # Ignore server-side certificate.
    # runtime_options.ignore_ssl = True
    # Path to the KMS instance CA certificate.
    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)

Substitua os placeholders a seguir pelos seus valores reais:

Placeholder

Descrição

Exemplo

<CLIENT_KEY_FILE>

Caminho para o arquivo da sua Client Key

/etc/kms/clientKey.json

<ENDPOINT>

Endpoint da instância do KMS

kms-instance-id.cryptoservice.kms.aliyuncs.com

<CA_CERTIFICATE_FILE_PATH>

Caminho para o certificado CA da instância do KMS

/etc/kms/ca.pem

<SECRET_NAME>

Nome do segredo a ser recuperado

my-db-password

Detalhamento do exemplo

Inicializar o cliente

import os

from openapi.models import Config
from sdk.client import Client

config = Config()
# KMS instance services only allow access through HTTPS.
config.protocol = "https"
# Path to your Client Key file.
config.client_key_file = "<CLIENT_KEY_FILE>"
# Client Key decryption password, read from an environment variable.
config.password = os.getenv('CLIENT_KEY_PASSWORD')
# Endpoint format: <your-kms-instance-id>.cryptoservice.kms.aliyuncs.com
config.endpoint = "<ENDPOINT>"
client = Client(config)

A variável CLIENT_KEY_PASSWORD é lida de uma variável de ambiente em vez de ser codificada diretamente, evitando que credenciais fiquem expostas no seu source code.

Chamar a API GetSecretValue

def get_secret_value(secret_name):
    request = GetSecretValueRequest()
    request.secret_name = secret_name

    runtime_options = RuntimeOptions()
    # Ignore server-side certificate.
    # runtime_options.ignore_ssl = True
    # Path to the KMS instance CA certificate.
    runtime_options.verify = "<CA_CERTIFICATE_FILE_PATH>"

    resp = client.get_secret_value_with_options(request, runtime_options)
    print(resp)

O método get_secret_value_with_options recebe um objeto GetSecretValueRequest e um objeto RuntimeOptions. O campo verify aponta para o certificado CA da instância do KMS, utilizado pelo SDK para validar a conexão com o servidor.