Há mais AWS SDK exemplos disponíveis no GitHub repositório AWS Doc SDK Examples
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á.
Use GetSecretValue
com um AWS SDK ou CLI
Os exemplos de código a seguir mostram como usar o GetSecretValue
.
- .NET
-
- AWS SDK for .NET
-
nota
Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da AWS
. 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 API obter detalhes, consulte GetSecretValueem AWS SDK for .NET APIReferência.
-
- C++
-
- SDKpara C++
-
nota
Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da AWS
. //! Retrieve an AWS Secrets Manager encrypted secret. /*! \param secretID: The ID for the secret. \return bool: Function succeeded. */ bool AwsDoc::SecretsManager::getSecretValue(const Aws::String &secretID, const Aws::Client::ClientConfiguration &clientConfiguration) { Aws::SecretsManager::SecretsManagerClient secretsManagerClient(clientConfiguration); Aws::SecretsManager::Model::GetSecretValueRequest request; request.SetSecretId(secretID); Aws::SecretsManager::Model::GetSecretValueOutcome getSecretValueOutcome = secretsManagerClient.GetSecretValue( request); if (getSecretValueOutcome.IsSuccess()) { std::cout << "Secret is: " << getSecretValueOutcome.GetResult().GetSecretString() << std::endl; } else { std::cerr << "Failed with Error: " << getSecretValueOutcome.GetError() << std::endl; } return getSecretValueOutcome.IsSuccess(); }
-
Para API obter detalhes, consulte GetSecretValueem AWS SDK for C++ APIReferência.
-
- CLI
-
- AWS CLI
-
Exemplo 1: como recuperar o valor secreto criptografado de um segredo
O exemplo de
get-secret-value
a seguir obtém o valor atual do segredo.aws secretsmanager get-secret-value \ --secret-id
MyTestSecret
Saída:
{ "ARN": "arn:aws:secretsmanager:us-west-2:123456789012:secret:MyTestSecret-a1b2c3", "Name": "MyTestSecret", "VersionId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111", "SecretString": "{\"user\":\"diegor\",\"password\":\"EXAMPLE-PASSWORD\"}", "VersionStages": [ "AWSCURRENT" ], "CreatedDate": 1523477145.713 }
Para obter mais informações, consulte Recuperar segredos no Guia do usuário do Secrets Manager.
Exemplo 2: como recuperar o valor secreto anterior
O seguinte exemplo de
get-secret-value
recupera o valor secreto anterior:aws secretsmanager get-secret-value \ --secret-id
MyTestSecret
--version-stageAWSPREVIOUS
Saída:
{ "ARN": "arn:aws:secretsmanager:us-west-2:123456789012:secret:MyTestSecret-a1b2c3", "Name": "MyTestSecret", "VersionId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE22222", "SecretString": "{\"user\":\"diegor\",\"password\":\"PREVIOUS-EXAMPLE-PASSWORD\"}", "VersionStages": [ "AWSPREVIOUS" ], "CreatedDate": 1523477145.713 }
Para obter mais informações, consulte Recuperar segredos no Guia do usuário do Secrets Manager.
-
Para API obter detalhes, consulte GetSecretValue
na Referência de AWS CLI Comandos.
-
- Java
-
- SDKpara Java 2.x
-
nota
Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da AWS
. import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.secretsmanager.SecretsManagerClient; import software.amazon.awssdk.services.secretsmanager.model.GetSecretValueRequest; import software.amazon.awssdk.services.secretsmanager.model.GetSecretValueResponse; import software.amazon.awssdk.services.secretsmanager.model.SecretsManagerException; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html * * We recommend that you cache your secret values by using client-side caching. * * Caching secrets improves speed and reduces your costs. For more information, * see the following documentation topic: * * https://docs.aws.amazon.com/secretsmanager/latest/userguide/retrieving-secrets.html */ public class GetSecretValue { public static void main(String[] args) { final String usage = """ Usage: <secretName>\s Where: secretName - The name of the secret (for example, tutorials/MyFirstSecret).\s """; if (args.length != 1) { System.out.println(usage); System.exit(1); } String secretName = args[0]; Region region = Region.US_EAST_1; SecretsManagerClient secretsClient = SecretsManagerClient.builder() .region(region) .build(); getValue(secretsClient, secretName); secretsClient.close(); } public static void getValue(SecretsManagerClient secretsClient, String secretName) { try { GetSecretValueRequest valueRequest = GetSecretValueRequest.builder() .secretId(secretName) .build(); GetSecretValueResponse valueResponse = secretsClient.getSecretValue(valueRequest); String secret = valueResponse.secretString(); System.out.println(secret); } catch (SecretsManagerException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } }
-
Para API obter detalhes, consulte GetSecretValueem AWS SDK for Java 2.x APIReferência.
-
- JavaScript
-
- SDKpara JavaScript (v3)
-
nota
Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da AWS
. import { GetSecretValueCommand, SecretsManagerClient, } from "@aws-sdk/client-secrets-manager"; export const getSecretValue = async (secretName = "SECRET_NAME") => { const client = new SecretsManagerClient(); const response = await client.send( new GetSecretValueCommand({ SecretId: secretName, }), ); console.log(response); // { // '$metadata': { // httpStatusCode: 200, // requestId: '584eb612-f8b0-48c9-855e-6d246461b604', // extendedRequestId: undefined, // cfId: undefined, // attempts: 1, // totalRetryDelay: 0 // }, // ARN: 'arn:aws:secretsmanager:us-east-1:xxxxxxxxxxxx:secret:binary-secret-3873048-xxxxxx', // CreatedDate: 2023-08-08T19:29:51.294Z, // Name: 'binary-secret-3873048', // SecretBinary: Uint8Array(11) [ // 98, 105, 110, 97, 114, // 121, 32, 100, 97, 116, // 97 // ], // VersionId: '712083f4-0d26-415e-8044-16735142cd6a', // VersionStages: [ 'AWSCURRENT' ] // } if (response.SecretString) { return response.SecretString; } if (response.SecretBinary) { return response.SecretBinary; } };
-
Para API obter detalhes, consulte GetSecretValueem AWS SDK for JavaScript APIReferência.
-
- Kotlin
-
- SDKpara Kotlin
-
nota
Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da AWS
. suspend fun getValue(secretName: String?) { val valueRequest = GetSecretValueRequest { secretId = secretName } SecretsManagerClient { region = "us-east-1" }.use { secretsClient -> val response = secretsClient.getSecretValue(valueRequest) val secret = response.secretString println("The secret value is $secret") } }
-
Para API obter detalhes, consulte a GetSecretValue
referência AWS SDKdo Kotlin API.
-
- Python
-
- SDKpara Python (Boto3)
-
nota
Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da AWS
. class GetSecretWrapper: def __init__(self, secretsmanager_client): self.client = secretsmanager_client def get_secret(self, secret_name): """ Retrieve individual secrets from AWS Secrets Manager using the get_secret_value API. This function assumes the stack mentioned in the source code README has been successfully deployed. This stack includes 7 secrets, all of which have names beginning with "mySecret". :param secret_name: The name of the secret fetched. :type secret_name: str """ try: get_secret_value_response = self.client.get_secret_value( SecretId=secret_name ) logging.info("Secret retrieved successfully.") return get_secret_value_response["SecretString"] except self.client.exceptions.ResourceNotFoundException: msg = f"The requested secret {secret_name} was not found." logger.info(msg) return msg except Exception as e: logger.error(f"An unknown error occurred: {str(e)}.") raise
-
Para API obter detalhes, consulte a GetSecretValueReferência AWS SDK do Python (Boto3). API
-
- Rust
-
- SDKpara Rust
-
nota
Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da AWS
. async fn show_secret(client: &Client, name: &str) -> Result<(), Error> { let resp = client.get_secret_value().secret_id(name).send().await?; println!("Value: {}", resp.secret_string().unwrap_or("No value!")); Ok(()) }
-
Para API obter detalhes, consulte GetSecretValue
a AWS SDKAPIreferência do Rust.
-