AWS Certified Developer – Associate (DVA-C02)Development with AWS ServicesMedium
A developer is creating an AWS Lambda function that needs to retrieve a secret from AWS Secrets Manager. To avoid hardcoding the secret and ensure secure access, the developer should use the AWS SDK within the Lambda function. Which of the following code snippets (pseudo-code) demonstrates the correct way to retrieve a secret named 'MyDatabaseSecret' using the AWS SDK for Python (Boto3)?
- Asecret_value = os.environ.get('MyDatabaseSecret')
- Bsecret_value = requests.get('http://secretsmanager.aws.com/MyDatabaseSecret').json()
- Cclient = boto3.client('ssm') response = client.get_parameter(Name='MyDatabaseSecret', WithDecryption=True) secret_value = response['Parameter']['Value']
- Dclient = boto3.client('secretsmanager') response = client.get_secret_value(SecretId='MyDatabaseSecret') secret_value = response['SecretString']
Show answer & explanationAnswer & explanation
Correct answer: D. client = boto3.client('secretsmanager') response = client.get_secret_value(SecretId='MyDatabaseSecret') secret_value = response['SecretString']
The correct way to retrieve a secret from AWS Secrets Manager using Boto3 (AWS SDK for Python) is to instantiate the 'secretsmanager' client and then call the 'get_secret_value' method, specifying the 'SecretId'. The secret's value is typically found in the 'SecretString' key of the response.
Why the other options are wrong
- A. This retrieves an environment variable, which is not how Secrets Manager secrets are accessed programmatically.
- B. Direct HTTP calls to AWS service endpoints are generally not the secure or recommended way to interact with AWS services, especially for sensitive data; the SDK should be used.
- C. This code retrieves a parameter from AWS Systems Manager Parameter Store, not from AWS Secrets Manager.
AWS SDK for Secrets Manager
The official AWS Software Development Kits (SDKs) provide programmatic access to AWS Secrets Manager, allowing applications to securely retrieve secrets without hardcoding.
- Uses the `secretsmanager` client.
- The `get_secret_value` API call is used.
- Requires appropriate IAM permissions for the calling entity.
- Secrets are typically returned in `SecretString` or `SecretBinary`.
Memory trick: Boto3 is the secure key to unlock Secrets Manager's vault.