Exemplos de Secrets Manager usando AWS SDK for .NET - AWS SDK for .NET

As traduções são geradas por tradução automática. Em caso de conflito entre o conteúdo da tradução e da versão original em inglês, a versão em inglês prevalecerá.

Exemplos de Secrets Manager usando AWS SDK for .NET

Os exemplos de código a seguir mostram como realizar ações e implementar cenários comuns usando o AWS SDK for .NET with Secrets Manager.

Ações são trechos de código de programas maiores e devem ser executadas em contexto. Embora as ações mostrem como chamar funções de serviço específicas, é possível ver as ações contextualizadas em seus devidos cenários e exemplos entre serviços.

Cenários são exemplos de código que mostram como realizar uma tarefa específica chamando várias funções dentro do mesmo serviço.

Cada exemplo inclui um link para GitHub, onde você pode encontrar instruções sobre como configurar e executar o código no contexto.

Tópicos

Ações

O código de exemplo a seguir mostra como usar GetSecretValue.

AWS SDK for .NET
nota

Tem mais sobre GitHub. Encontre o exemplo completo e veja como configurar e executar no AWS Code Examples Repository.

using System; using System.IO; using System.Threading.Tasks; using Amazon.SecretsManager; using Amazon.SecretsManager.Model; /// <summary> /// This example uses the Amazon Web Service Secrets Manager to retrieve /// the secret value for the provided secret name. /// </summary> public class GetSecretValue { /// <summary> /// The main method initializes the necessary values and then calls /// the GetSecretAsync and DecodeString methods to get the decoded /// secret value for the secret named in secretName. /// </summary> public static async Task Main() { string secretName = "<<{{MySecretName}}>>"; string secret; IAmazonSecretsManager client = new AmazonSecretsManagerClient(); var response = await GetSecretAsync(client, secretName); if (response is not null) { secret = DecodeString(response); if (!string.IsNullOrEmpty(secret)) { Console.WriteLine($"The decoded secret value is: {secret}."); } else { Console.WriteLine("No secret value was returned."); } } } /// <summary> /// Retrieves the secret value given the name of the secret to /// retrieve. /// </summary> /// <param name="client">The client object used to retrieve the secret /// value for the given secret name.</param> /// <param name="secretName">The name of the secret value to retrieve.</param> /// <returns>The GetSecretValueReponse object returned by /// GetSecretValueAsync.</returns> public static async Task<GetSecretValueResponse> GetSecretAsync( IAmazonSecretsManager client, string secretName) { GetSecretValueRequest request = new GetSecretValueRequest() { SecretId = secretName, VersionStage = "AWSCURRENT", // VersionStage defaults to AWSCURRENT if unspecified. }; GetSecretValueResponse response = null; // For the sake of simplicity, this example handles only the most // general SecretsManager exception. try { response = await client.GetSecretValueAsync(request); } catch (AmazonSecretsManagerException e) { Console.WriteLine($"Error: {e.Message}"); } return response; } /// <summary> /// Decodes the secret returned by the call to GetSecretValueAsync and /// returns it to the calling program. /// </summary> /// <param name="response">A GetSecretValueResponse object containing /// the requested secret value returned by GetSecretValueAsync.</param> /// <returns>A string representing the decoded secret value.</returns> public static string DecodeString(GetSecretValueResponse response) { // Decrypts secret using the associated AWS Key Management Service // Customer Master Key (CMK.) Depending on whether the secret is a // string or binary value, one of these fields will be populated. if (response.SecretString is not null) { var secret = response.SecretString; return secret; } else if (response.SecretBinary is not null) { var memoryStream = response.SecretBinary; StreamReader reader = new StreamReader(memoryStream); string decodedBinarySecret = System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(reader.ReadToEnd())); return decodedBinarySecret; } else { return string.Empty; } } }
  • Para obter detalhes da API, consulte GetSecretValuea Referência AWS SDK for .NET da API.