AWS Secrets Manager: Retrieve Multiple Secrets and Handle Partial Failures
See more AWS Secrets Manager Examples
Retrieves two named secrets in one explicit-ID batch and handles per-secret errors even when the overall HTTP status is 200. Successful values are processed individually in memory; failures are reported by secret identifier and error code. Production applications should reconcile results by identifier, not response position, and retry only appropriate failed items.
BatchGetSecretValue accepts up to 20 explicit names/ARNs. Alternatively, use filters with MaxResults and NextToken, but do not combine Filters with SecretIdList. This example uses an explicit list, so it does not set MaxResults or paginate. Changing the requested names also requires changing the response-name checks in this demonstrative sample.
Required actions: secretsmanager:BatchGetSecretValue, secretsmanager:GetSecretValue.
GetSecretValue permission is needed for each requested secret; customer-managed encryption keys need kms:Decrypt. Filter-based batches additionally require ListSecrets.
Uses direct Chilkat.Rest requests with AWS Signature Version 4, signing service secretsmanager, and the AWS JSON 1.1 protocol. Configure the region in the code. The illustrated amazonaws.com endpoint is for the commercial AWS partition; use the appropriate endpoint for other partitions. HTTPS certificate verification is enabled.
Supply nonempty string fields access_key and secret_key in private qa_data/aws/secrets-manager.json. For temporary role or STS credentials, also supply the matching nonempty session_token; it is included in the signed query. Prefer short-lived role credentials in production. These samples consume credentials already obtained by the application; they do not implement an SDK credential-provider chain or refresh expired credentials. Protect local credential files and keep them outside source control and public web directories.
The sample distinguishes transport failures, HTTP errors, and invalid JSON. It prints status, AWS error code, and request ID, without printing secret values or full diagnostic bodies. Request URLs and Chilkat diagnostics can contain sensitive data; inspect them privately. Production retry policies should use bounded exponential backoff with jitter for transient failures. Reconcile uncertain writes and preserve their idempotency token and payload before retrying.
AWS BatchGetSecretValue reference
Chilkat Delphi DLL Downloads
var
success: Boolean;
stringCompare: HCkStringBuilder;
credentials: HCkJsonObject;
stringMatch1: Boolean;
stringMatch2: Boolean;
region: PWideChar;
endpoint: HCkStringBuilder;
aws: HCkAuthAws;
rest: HCkRest;
stringMatch3: Boolean;
connection: HCkSocket;
body: HCkJsonObject;
result: HCkJsonObject;
responseJson: PWideChar;
values: HCkJsonArray;
errors: HCkJsonArray;
item: HCkJsonObject;
seen: HCkHashtable;
successCount: Integer;
errorCount: Integer;
i: Integer;
stringMatch4: Boolean;
stringMatch5: Boolean;
stringMatch6: Boolean;
stringMatch7: Boolean;
stringMatch8: Boolean;
hasText: Boolean;
hasBinary: Boolean;
stringMatch9: Boolean;
secretText: PWideChar;
stringMatch10: Boolean;
secretBytes: HCkBinData;
stringMatch11: Boolean;
stringMatch12: Boolean;
stringMatch13: Boolean;
stringMatch14: Boolean;
begin
success := False;
stringCompare := CkStringBuilder_Create();
// Assumes Chilkat is unlocked. See Global Unlock Sample.
// Keep this credentials file outside public web content and source control.
credentials := CkJsonObject_Create();
CkJsonObject_putStrict(credentials,True);
success := CkJsonObject_LoadFile(credentials,'qa_data/aws/secrets-manager.json');
if (success <> True) then
begin
Memo1.Lines.Add('Could not load private Secrets Manager configuration.');
Exit;
end;
CkStringBuilder_SetString(stringCompare,CkJsonObject__stringOf(credentials,'access_key'));
stringMatch1 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
if ((CkJsonObject_JsonTypeOf(credentials,'access_key') <> 1) or (stringMatch1 = True)) then
begin
Memo1.Lines.Add('Missing or invalid access_key.');
Exit;
end;
CkStringBuilder_SetString(stringCompare,CkJsonObject__stringOf(credentials,'secret_key'));
stringMatch2 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
if ((CkJsonObject_JsonTypeOf(credentials,'secret_key') <> 1) or (stringMatch2 = True)) then
begin
Memo1.Lines.Add('Missing or invalid secret_key.');
Exit;
end;
region := 'us-west-2';
endpoint := CkStringBuilder_Create();
CkStringBuilder_Append(endpoint,'secretsmanager.');
CkStringBuilder_Append(endpoint,region);
CkStringBuilder_Append(endpoint,'.amazonaws.com');
aws := CkAuthAws_Create();
CkAuthAws_putAccessKey(aws,CkJsonObject__stringOf(credentials,'access_key'));
CkAuthAws_putSecretKey(aws,CkJsonObject__stringOf(credentials,'secret_key'));
CkAuthAws_putRegion(aws,region);
CkAuthAws_putServiceName(aws,'secretsmanager');
CkAuthAws_putSignatureVersion(aws,4);
rest := CkRest_Create();
CkRest_putConnectTimeoutMs(rest,20000);
CkRest_putIdleTimeoutMs(rest,60000);
CkRest_putVerboseLogging(rest,False);
success := CkRest_SetAuthAws(rest,aws);
if (success <> True) then
begin
Memo1.Lines.Add('Could not configure AWS signing.');
Exit;
end;
if (CkJsonObject_HasMember(credentials,'session_token') = True) then
begin
CkStringBuilder_SetString(stringCompare,CkJsonObject__stringOf(credentials,'session_token'));
stringMatch3 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
if ((CkJsonObject_JsonTypeOf(credentials,'session_token') <> 1) or (stringMatch3 = True)) then
begin
Memo1.Lines.Add('Missing or invalid session_token.');
Exit;
end;
end;
connection := CkSocket_Create();
CkSocket_putRequireSslCertVerify(connection,True);
CkSocket_putMaxReadIdleMs(connection,60000);
CkSocket_putMaxSendIdleMs(connection,60000);
// Keep connection alive while Rest uses it.
body := CkJsonObject_Create();
result := CkJsonObject_Create();
CkJsonObject_putStrict(result,True);
// Use 1 to 20 distinct names or complete ARNs. This example uses two names.
success := CkJsonObject_UpdateString(body,'SecretIdList[0]','example/application');
if (success <> True) then
begin
Memo1.Lines.Add('Could not set SecretIdList[0].');
Exit;
end;
success := CkJsonObject_UpdateString(body,'SecretIdList[1]','example/service');
if (success <> True) then
begin
Memo1.Lines.Add('Could not set SecretIdList[1].');
Exit;
end;
// MaxResults is for filter-based requests; do not add it to this explicit ID request.
success := CkRest_ClearAllQueryParams(rest);
if (success <> True) then
begin
Memo1.Lines.Add('Could not clear query parameters.');
Exit;
end;
// Temporary role credentials require the session token as well as both keys.
// Include it in the signed query; keep request URLs and diagnostics private.
if (CkJsonObject_HasMember(credentials,'session_token') = True) then
begin
success := CkRest_AddQueryParam(rest,'X-Amz-Security-Token',CkJsonObject__stringOf(credentials,'session_token'));
if (success <> True) then
begin
Memo1.Lines.Add('Could not set session token.');
Exit;
end;
end;
success := CkRest_AddHeader(rest,'Content-Type','application/x-amz-json-1.1');
if (success <> True) then
begin
Memo1.Lines.Add('Could not set content type.');
Exit;
end;
success := CkRest_AddHeader(rest,'X-Amz-Target','secretsmanager.BatchGetSecretValue');
if (success <> True) then
begin
Memo1.Lines.Add('Could not select operation.');
Exit;
end;
// Establish a connection for this deliberate operation. Do not replay a write
// automatically if the server receives it but its response is lost.
CkRest_Disconnect(rest,10);
success := CkSocket_Connect(connection,CkStringBuilder__getAsString(endpoint),443,True,20000);
if (success <> True) then
begin
Memo1.Lines.Add('TLS connection failed; inspect diagnostics privately.');
Exit;
end;
success := CkRest_UseConnection(rest,connection,False);
if (success <> True) then
begin
Memo1.Lines.Add('Could not attach the TLS connection.');
Exit;
end;
responseJson := CkRest__fullRequestString(rest,'POST','/',CkJsonObject__emit(body));
if (CkRest_getLastMethodSuccess(rest) <> True) then
begin
Memo1.Lines.Add('Secrets Manager request did not complete; inspect diagnostics privately. A write may have succeeded.');
Exit;
end;
if (CkRest_getResponseStatusCode(rest) <> 200) then
begin
Memo1.Lines.Add('Secrets Manager HTTP status: ' + IntToStr(CkRest_getResponseStatusCode(rest)));
success := CkJsonObject_Load(result,responseJson);
if (success = True) then
begin
if (CkJsonObject_JsonTypeOf(result,'__type') = 1) then
begin
Memo1.Lines.Add('AWS error code: ' + CkJsonObject__stringOf(result,'__type'));
end;
end;
Memo1.Lines.Add('AWS request ID: ' + CkRest__responseHdrByName(rest,'x-amzn-RequestId'));
// Do not print response bodies, request bodies, credentials, or secret values.
Exit;
end;
success := CkJsonObject_Load(result,responseJson);
if (success <> True) then
begin
Memo1.Lines.Add('Expected a well-formed JSON response.');
Exit;
end;
if (CkJsonObject_HasMember(result,'NextToken') = True) then
begin
Memo1.Lines.Add('Unexpected continuation token for this explicit-ID example.');
Exit;
end;
values := CkJsonArray_Create();
errors := CkJsonArray_Create();
item := CkJsonObject_Create();
seen := CkHashtable_Create();
successCount := 0;
errorCount := 0;
i := 0;
if (CkJsonObject_HasMember(result,'SecretValues') = True) then
begin
if (CkJsonObject_JsonTypeOf(result,'SecretValues') <> 4) then
begin
Memo1.Lines.Add('Missing or invalid SecretValues.');
Exit;
end;
success := CkJsonObject_ArrayOf2(result,'SecretValues',values);
if (success <> True) then
begin
Memo1.Lines.Add('Could not read SecretValues.');
Exit;
end;
while (i < CkJsonArray_getSize(values)) do
begin
success := CkJsonArray_ObjectAt2(values,i,item);
if (success <> True) then
begin
Memo1.Lines.Add('Invalid secret result.');
Exit;
end;
CkStringBuilder_SetString(stringCompare,CkJsonObject__stringOf(item,'ARN'));
stringMatch4 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
if ((CkJsonObject_JsonTypeOf(item,'ARN') <> 1) or (stringMatch4 = True)) then
begin
Memo1.Lines.Add('Missing or invalid ARN.');
Exit;
end;
CkStringBuilder_SetString(stringCompare,CkJsonObject__stringOf(item,'Name'));
stringMatch5 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
if ((CkJsonObject_JsonTypeOf(item,'Name') <> 1) or (stringMatch5 = True)) then
begin
Memo1.Lines.Add('Missing or invalid Name.');
Exit;
end;
CkStringBuilder_SetString(stringCompare,CkJsonObject__stringOf(item,'VersionId'));
stringMatch6 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
if ((CkJsonObject_JsonTypeOf(item,'VersionId') <> 1) or (stringMatch6 = True)) then
begin
Memo1.Lines.Add('Missing or invalid VersionId.');
Exit;
end;
CkStringBuilder_SetString(stringCompare,CkJsonObject__stringOf(item,'Name'));
stringMatch7 := CkStringBuilder_ContentsEqual(stringCompare,'example/application',True);
CkStringBuilder_SetString(stringCompare,CkJsonObject__stringOf(item,'Name'));
stringMatch8 := CkStringBuilder_ContentsEqual(stringCompare,'example/service',True);
if ((stringMatch7 <> True) and (stringMatch8 <> True)) then
begin
Memo1.Lines.Add('Unexpected secret returned.');
Exit;
end;
if (CkHashtable_Contains(seen,CkJsonObject__stringOf(item,'Name')) = True) then
begin
Memo1.Lines.Add('Duplicate batch result.');
Exit;
end;
success := CkHashtable_AddStr(seen,CkJsonObject__stringOf(item,'Name'),'seen');
if (success <> True) then
begin
Memo1.Lines.Add('Could not track batch results.');
Exit;
end;
hasText := CkJsonObject_HasMember(item,'SecretString');
hasBinary := CkJsonObject_HasMember(item,'SecretBinary');
if (hasText = hasBinary) then
begin
Memo1.Lines.Add('Expected exactly one secret value.');
Exit;
end;
if (hasText = True) then
begin
CkStringBuilder_SetString(stringCompare,CkJsonObject__stringOf(item,'SecretString'));
stringMatch9 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
if ((CkJsonObject_JsonTypeOf(item,'SecretString') <> 1) or (stringMatch9 = True)) then
begin
Memo1.Lines.Add('Missing or invalid SecretString.');
Exit;
end;
secretText := CkJsonObject__stringOf(item,'SecretString');
// Pass secretText to the consumer associated with this secret name; never print it.
end
else
begin
CkStringBuilder_SetString(stringCompare,CkJsonObject__stringOf(item,'SecretBinary'));
stringMatch10 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
if ((CkJsonObject_JsonTypeOf(item,'SecretBinary') <> 1) or (stringMatch10 = True)) then
begin
Memo1.Lines.Add('Missing or invalid SecretBinary.');
Exit;
end;
secretBytes := CkBinData_Create();
success := CkBinData_AppendEncoded(secretBytes,CkJsonObject__stringOf(item,'SecretBinary'),'base64');
if (success <> True) then
begin
Memo1.Lines.Add('Could not decode a binary secret.');
Exit;
end;
if ((CkBinData_getNumBytes(secretBytes) < 1) or (CkBinData_getNumBytes(secretBytes) > 65536)) then
begin
Memo1.Lines.Add('Invalid binary secret size.');
Exit;
end;
// Pass secretBytes to its consumer without assuming the bytes are text.
end;
Memo1.Lines.Add('Retrieved secret: ' + CkJsonObject__stringOf(item,'Name'));
successCount := successCount + 1;
i := i + 1;
end;
end;
if (CkJsonObject_HasMember(result,'Errors') = True) then
begin
if (CkJsonObject_JsonTypeOf(result,'Errors') <> 4) then
begin
Memo1.Lines.Add('Missing or invalid Errors.');
Exit;
end;
success := CkJsonObject_ArrayOf2(result,'Errors',errors);
if (success <> True) then
begin
Memo1.Lines.Add('Could not read Errors.');
Exit;
end;
i := 0;
while (i < CkJsonArray_getSize(errors)) do
begin
success := CkJsonArray_ObjectAt2(errors,i,item);
if (success <> True) then
begin
Memo1.Lines.Add('Invalid per-secret error.');
Exit;
end;
CkStringBuilder_SetString(stringCompare,CkJsonObject__stringOf(item,'SecretId'));
stringMatch11 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
if ((CkJsonObject_JsonTypeOf(item,'SecretId') <> 1) or (stringMatch11 = True)) then
begin
Memo1.Lines.Add('Missing or invalid SecretId.');
Exit;
end;
CkStringBuilder_SetString(stringCompare,CkJsonObject__stringOf(item,'ErrorCode'));
stringMatch12 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
if ((CkJsonObject_JsonTypeOf(item,'ErrorCode') <> 1) or (stringMatch12 = True)) then
begin
Memo1.Lines.Add('Missing or invalid ErrorCode.');
Exit;
end;
CkStringBuilder_SetString(stringCompare,CkJsonObject__stringOf(item,'SecretId'));
stringMatch13 := CkStringBuilder_ContentsEqual(stringCompare,'example/application',True);
CkStringBuilder_SetString(stringCompare,CkJsonObject__stringOf(item,'SecretId'));
stringMatch14 := CkStringBuilder_ContentsEqual(stringCompare,'example/service',True);
if ((stringMatch13 <> True) and (stringMatch14 <> True)) then
begin
Memo1.Lines.Add('Unexpected secret identifier in batch errors.');
Exit;
end;
if (CkHashtable_Contains(seen,CkJsonObject__stringOf(item,'SecretId')) = True) then
begin
Memo1.Lines.Add('Duplicate batch success/error result.');
Exit;
end;
success := CkHashtable_AddStr(seen,CkJsonObject__stringOf(item,'SecretId'),'seen');
if (success <> True) then
begin
Memo1.Lines.Add('Could not track batch errors.');
Exit;
end;
Memo1.Lines.Add('Failed secret: ' + CkJsonObject__stringOf(item,'SecretId') + ' code: ' + CkJsonObject__stringOf(item,'ErrorCode'));
// Error Message and full response are intentionally not logged.
errorCount := errorCount + 1;
i := i + 1;
end;
end;
if ((successCount + errorCount) <> 2) then
begin
Memo1.Lines.Add('Incomplete or unexpected batch results; reconcile each requested secret.');
Exit;
end;
if (errorCount > 0) then
begin
Memo1.Lines.Add('Batch finished with per-secret failures. Successful results are still usable.');
Exit;
end;
Memo1.Lines.Add('All requested secrets retrieved.');
CkStringBuilder_Dispose(stringCompare);
CkJsonObject_Dispose(credentials);
CkStringBuilder_Dispose(endpoint);
CkAuthAws_Dispose(aws);
CkRest_Dispose(rest);
CkSocket_Dispose(connection);
CkJsonObject_Dispose(body);
CkJsonObject_Dispose(result);
CkJsonArray_Dispose(values);
CkJsonArray_Dispose(errors);
CkJsonObject_Dispose(item);
CkHashtable_Dispose(seen);
CkBinData_Dispose(secretBytes);