Partilhar via


Ligação de entrada Dapr Secret para o Azure Functions

A ligação de entrada secreta Dapr permite que você leia dados secretos como entrada durante a execução da função.

Para obter informações sobre detalhes de instalação e configuração da extensão Dapr, consulte a visão geral da extensão Dapr.

Example

Uma função C# pode ser criada usando um dos seguintes modos C#:

Execution model Description
Modelo de trabalhador isolado Seu código de função é executado em um processo de trabalho .NET separado. Use com versões suportadas do .NET e .NET Framework. Para saber mais, consulte Guia para executar o C# Azure Functions no modelo de trabalhador isolado.
In-process model Seu código de função é executado no mesmo processo que o processo de host de funções. Suporta apenas versões LTS (Long Term Support) do .NET. Para saber mais, consulte Desenvolver funções de biblioteca de classes C# usando o Azure Functions.
[FunctionName("RetrieveSecret")]
public static void Run(
    [DaprServiceInvocationTrigger] object args,
    [DaprSecret("kubernetes", "my-secret", Metadata = "metadata.namespace=default")] IDictionary<string, string> secret,
    ILogger log)
{
    log.LogInformation("C# function processed a RetrieveSecret request from the Dapr Runtime.");
}

O exemplo a seguir cria uma "RetrieveSecret" função usando a DaprSecretInput associação com o DaprServiceInvocationTrigger:

@FunctionName("RetrieveSecret")
public void run(
    @DaprServiceInvocationTrigger(
        methodName = "RetrieveSecret") Object args,
    @DaprSecretInput(
        secretStoreName = "kubernetes", 
        key = "my-secret", 
        metadata = "metadata.namespace=default") 
        Map<String, String> secret,
    final ExecutionContext context)

No exemplo a seguir, a ligação de entrada secreta do Dapr é emparelhada com um gatilho app de invocação do Dapr, que é registrado pelo objeto:

const { app, trigger } = require('@azure/functions');

app.generic('RetrieveSecret', {
    trigger: trigger.generic({
        type: 'daprServiceInvocationTrigger',
        name: "payload"
    }),
    extraInputs: [daprSecretInput],
    handler: async (request, context) => {
        context.log("Node function processed a RetrieveSecret request from the Dapr Runtime.");
        const daprSecretInputValue = context.extraInputs.get(daprSecretInput);

        // print the fetched secret value
        for (var key in daprSecretInputValue) {
            context.log(`Stored secret: Key=${key}, Value=${daprSecretInputValue[key]}`);
        }
    }
});

The following examples show Dapr triggers in a function.json file and PowerShell code that uses those bindings.

Here's the function.json file for daprServiceInvocationTrigger:

{
  "bindings": 
    {
      "type": "daprSecret",
      "direction": "in",
      "name": "secret",
      "key": "my-secret",
      "secretStoreName": "localsecretstore",
      "metadata": "metadata.namespace=default"
    }
}

For more information about function.json file properties, see the Configuration section.

In code:

using namespace System
using namespace Microsoft.Azure.WebJobs
using namespace Microsoft.Extensions.Logging
using namespace Microsoft.Azure.WebJobs.Extensions.Dapr
using namespace Newtonsoft.Json.Linq

param (
    $payload, $secret
)

# PowerShell function processed a CreateNewOrder request from the Dapr Runtime.
Write-Host "PowerShell function processed a RetrieveSecretLocal request from the Dapr Runtime."

# Convert the object to a JSON-formatted string with ConvertTo-Json
$jsonString = $secret | ConvertTo-Json

Write-Host "$jsonString"

O exemplo a seguir mostra uma ligação de entrada Dapr Secret, que usa o modelo de programação Python v2. Para usar a daprSecret associação ao lado do código do daprServiceInvocationTrigger aplicativo da função Python:

import logging
import json
import azure.functions as func

app = func.FunctionApp()

@app.function_name(name="RetrieveSecret")
@app.dapr_service_invocation_trigger(arg_name="payload", method_name="RetrieveSecret")
@app.dapr_secret_input(arg_name="secret", secret_store_name="localsecretstore", key="my-secret", metadata="metadata.namespace=default")
def main(payload, secret: str) :
    # Function should be invoked with this command: dapr invoke --app-id functionapp --method RetrieveSecret  --data '{}'
    logging.info('Python function processed a RetrieveSecret request from the Dapr Runtime.')
    secret_dict = json.loads(secret)

    for key in secret_dict:
        logging.info("Stored secret: Key = " + key +
                     ', Value = ' + secret_dict[key])

Attributes

In the in-process model, use the DaprSecret to define a Dapr secret input binding, which supports these parameters:

Parameter Description
SecretStoreName O nome da loja secreta para obter o segredo.
Key A chave que identifica o nome do segredo a obter.
Metadata Optional. Uma matriz de propriedades de metadados no formato "key1=value1&key2=value2".

Annotations

A DaprSecretInput anotação permite que você tenha sua função acessando um segredo.

Element Description
secretStoreName O nome da loja secreta Dapr.
key O valor da chave secreta.
metadata Optional. Os valores de metadados.

Configuration

A tabela a seguir explica as propriedades de configuração de vinculação definidas no código.

Property Description
key O valor da chave secreta.
secretStoreName Name of the secret store as defined in the local-secret-store.yaml component file.
metadata O namespace de metadados.

A tabela a seguir explica as propriedades de configuração de vinculação definidas no arquivo function.json.

function.json property Description
key O valor da chave secreta.
secretStoreName Name of the secret store as defined in the local-secret-store.yaml component file.
metadata O namespace de metadados.

A tabela a seguir explica as propriedades de configuração de vinculação definidas @dapp.dapr_secret_input no código Python.

Property Description
secret_store_name O nome da loja secreta.
key O valor da chave secreta.
metadata O namespace de metadados.

See the Example section for complete examples.

Usage

Para usar a ligação de entrada secreta do Dapr, comece configurando um componente de armazenamento secreto do Dapr. Você pode saber mais sobre qual componente usar e como configurá-lo na documentação oficial do Dapr.

To use the daprSecret in Python v2, set up your project with the correct dependencies.

  1. Crie e ative um ambiente virtual.

  2. No ficheiro requirements.text , adicione a seguinte linha:

    azure-functions==1.18.0b3
    
  3. No terminal, instale a biblioteca Python.

    pip install -r .\requirements.txt
    
  4. Modifique seu local.setting.json arquivo com a seguinte configuração:

    "PYTHON_ISOLATE_WORKER_DEPENDENCIES":1
    

Next steps

Saiba mais sobre os segredos do Dapr.