文件 AWS SDK AWS 範例 SDK 儲存庫中有更多可用的
本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
GetSecretValue
搭配 a AWS SDK 或 CLI 使用
下列程式碼範例示範如何使用 GetSecretValue
。
- .NET
-
- AWS SDK for .NET
-
注意
還有更多 on GitHub。尋找完整範例,並了解如何在 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; } } }
-
如需 API 詳細資訊,請參閱 GetSecretValue AWS SDK for .NET 參考中的 API。
-
- C++
-
- C++ 的 SDK
-
注意
還有更多 on GitHub。尋找完整範例,並了解如何在 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(); }
-
如需 API 詳細資訊,請參閱 GetSecretValue AWS SDK for C++ 參考中的 API。
-
- CLI
-
- AWS CLI
-
範例 1:擷取秘密的加密秘密值
下列
get-secret-value
範例會取得目前機密值。aws secretsmanager get-secret-value \ --secret-id
MyTestSecret
輸出:
{ "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 }
如需詳細資訊,請參閱 Secrets Manager 使用者指南中的擷取秘密。
範例 2:擷取先前的秘密值
下列
get-secret-value
範例會取得先前的秘密值:aws secretsmanager get-secret-value \ --secret-id
MyTestSecret
--version-stageAWSPREVIOUS
輸出:
{ "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 }
如需詳細資訊,請參閱 Secrets Manager 使用者指南中的擷取秘密。
-
如需 API 詳細資訊,請參閱 AWS CLI 命令參考中的 GetSecretValue
。
-
- Java
-
- Java 2.x 的 SDK
-
注意
還有更多 on GitHub。尋找完整範例,並了解如何在 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); } } }
-
如需 API 詳細資訊,請參閱 GetSecretValue AWS SDK for Java 2.x 參考中的 API。
-
- JavaScript
-
- SDK for JavaScript (v3)
-
注意
還有更多 on GitHub。尋找完整範例,並了解如何在 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; } };
-
如需 API 詳細資訊,請參閱 GetSecretValue AWS SDK for JavaScript 參考中的 API。
-
- Kotlin
-
- SDK for Kotlin
-
注意
還有更多 on GitHub。尋找完整範例,並了解如何在 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") } }
-
如需 API 詳細資訊,請參閱 GetSecretValue
AWS for Kotlin SDK 參考中的 API。
-
- Python
-
- SDK for Python (Boto3)
-
注意
還有更多 on GitHub。尋找完整範例,並了解如何在 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
-
如需 API 詳細資訊,請參閱 GetSecretValue AWS SDK for Python (Boto3) Word 參考中的 API。
-
- Rust
-
- Rust 的 SDK
-
注意
還有更多 on GitHub。尋找完整範例,並了解如何在 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(()) }
-
如需 API 詳細資訊,請參閱 GetSecretValue
AWS for Rust SDK 參考中的 API。
-