Sample code for 30+ languages & platforms
Delphi DLL Requires Chilkat v11.6.0+

AWS Secrets Manager: List Secrets with Pagination

See more AWS Secrets Manager Examples

Lists secret metadata in the configured account and region, following every NextToken. Requests up to 100 entries per page, continues through empty pages that have a continuation token, and stops with an incomplete-result message on repeated tokens or a defensive page bound. Uses Hashtable to track opaque continuation strings. Processes every staging label attached to each returned version, not just the first label.

Requires secretsmanager:ListSecrets. Results contain metadata, not decrypted secret values; this action does not require permission to read each secret value. Metadata can still be confidential. Secrets scheduled for deletion are excluded by default; IncludePlannedDeletion=true includes them. The commented name-prefix filter illustrates a case-sensitive prefix search. ListSecrets is eventually consistent and may lag recent changes by five minutes; use DescribeSecret for more recent metadata on a known secret.

The version-to-stage mapping is useful for inventory, but ListSecretVersionIds is the dedicated version-history operation, including deprecated versions when requested. Use GetSecretValue or BatchGetSecretValue when the application needs the secret contents. An inventory spanning multiple requests is not an atomic snapshot if secrets change while it runs.

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 ListSecrets reference

Chilkat Delphi DLL Downloads

Delphi DLL
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;
seenTokens: HCkHashtable;
secrets: HCkJsonArray;
secretEntry: HCkJsonObject;
versions: HCkJsonObject;
stages: HCkJsonArray;
nextToken: PWideChar;
page: Integer;
i: Integer;
j: Integer;
k: Integer;
more: Boolean;
stringMatch4: Boolean;
stringMatch5: Boolean;
stringMatch6: Boolean;
versionId: PWideChar;
stringMatch7: 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);
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,True);
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not attach TLS connection.');
    Exit;
  end;
//  Keep connection alive while Rest uses it.
body := CkJsonObject_Create();
result := CkJsonObject_Create();
CkJsonObject_putStrict(result,True);

seenTokens := CkHashtable_Create();
secrets := CkJsonArray_Create();
secretEntry := CkJsonObject_Create();
versions := CkJsonObject_Create();
stages := CkJsonArray_Create();
nextToken := '';
page := 0;

more := True;
while (more = True) do
  begin
    if (page = 10000) then
      begin
        Memo1.Lines.Add('Page bound reached; secret enumeration is incomplete.');
        Exit;
      end;
    page := page + 1;
    CkJsonObject_Clear(body);
    success := CkJsonObject_UpdateInt(body,'MaxResults',100);
    if (success <> True) then
      begin
        Memo1.Lines.Add('Could not set page size.');
        Exit;
      end;
    //  Optional filter: name prefixes are case-sensitive.
    //  body.UpdateString("Filters[0].Key","name");
    //  body.UpdateString("Filters[0].Values[0]","example/");
    //  IncludePlannedDeletion defaults to false. Set true to inventory scheduled deletions.
    CkStringBuilder_SetString(stringCompare,nextToken);
    stringMatch4 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
    if (stringMatch4 <> True) then
      begin
        success := CkJsonObject_UpdateString(body,'NextToken',nextToken);
        if (success <> True) then
          begin
            Memo1.Lines.Add('Could not set NextToken.');
            Exit;
          end;
      end;
    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.ListSecrets');
    if (success <> True) then
      begin
        Memo1.Lines.Add('Could not select operation.');
        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_JsonTypeOf(result,'SecretList') <> 4) then
      begin
        Memo1.Lines.Add('Expected a SecretList array.');
        Exit;
      end;
    success := CkJsonObject_ArrayOf2(result,'SecretList',secrets);
    if (success <> True) then
      begin
        Memo1.Lines.Add('Could not read secret entries.');
        Exit;
      end;
    i := 0;
    while (i < CkJsonArray_getSize(secrets)) do
      begin
        success := CkJsonArray_ObjectAt2(secrets,i,secretEntry);
        if (success <> True) then
          begin
            Memo1.Lines.Add('Invalid secret entry.');
            Exit;
          end;
        CkStringBuilder_SetString(stringCompare,CkJsonObject__stringOf(secretEntry,'Name'));
        stringMatch5 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
        if ((CkJsonObject_JsonTypeOf(secretEntry,'Name') <> 1) or (stringMatch5 = True)) then
          begin
            Memo1.Lines.Add('Missing or invalid Name.');
            Exit;
          end;
        CkStringBuilder_SetString(stringCompare,CkJsonObject__stringOf(secretEntry,'ARN'));
        stringMatch6 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
        if ((CkJsonObject_JsonTypeOf(secretEntry,'ARN') <> 1) or (stringMatch6 = True)) then
          begin
            Memo1.Lines.Add('Missing or invalid ARN.');
            Exit;
          end;
        Memo1.Lines.Add('Secret name: ' + CkJsonObject__stringOf(secretEntry,'Name'));
        Memo1.Lines.Add('Secret ARN: ' + CkJsonObject__stringOf(secretEntry,'ARN'));
        //  Metadata only: ListSecrets never returns the decrypted value.
        //  A secret without an initial value may have no version-to-stage mapping.
        if (CkJsonObject_HasMember(secretEntry,'SecretVersionsToStages') = True) then
          begin
            if (CkJsonObject_JsonTypeOf(secretEntry,'SecretVersionsToStages') <> 3) then
              begin
                Memo1.Lines.Add('Expected a version-to-stage object.');
                Exit;
              end;
            success := CkJsonObject_ObjectOf2(secretEntry,'SecretVersionsToStages',versions);
            if (success <> True) then
              begin
                Memo1.Lines.Add('Could not read version mapping.');
                Exit;
              end;
            j := 0;
            while (j < CkJsonObject_getSize(versions)) do
              begin
                //  Version IDs are opaque strings, including when used as JSON member names.
                versionId := CkJsonObject__nameAt(versions,j);
                success := CkJsonObject_ArrayAt2(versions,j,stages);
                if (success <> True) then
                  begin
                    Memo1.Lines.Add('Expected a staging-label array.');
                    Exit;
                  end;
                k := 0;
                while (k < CkJsonArray_getSize(stages)) do
                  begin
                    if (CkJsonArray_TypeAt(stages,k) <> 1) then
                      begin
                        Memo1.Lines.Add('Expected a string staging label.');
                        Exit;
                      end;
                    Memo1.Lines.Add('  Version ' + versionId + ' label: ' + CkJsonArray__stringAt(stages,k));
                    k := k + 1;
                  end;

                j := j + 1;
              end;

          end;
        i := i + 1;
      end;

    //  An empty page can still have NextToken. Stop only when there is no next token.
    more := CkJsonObject_HasMember(result,'NextToken');
    if (more = True) then
      begin
        CkStringBuilder_SetString(stringCompare,CkJsonObject__stringOf(result,'NextToken'));
        stringMatch7 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
        if ((CkJsonObject_JsonTypeOf(result,'NextToken') <> 1) or (stringMatch7 = True)) then
          begin
            Memo1.Lines.Add('Missing or invalid NextToken.');
            Exit;
          end;
        nextToken := CkJsonObject__stringOf(result,'NextToken');
        if (CkHashtable_Contains(seenTokens,nextToken) = True) then
          begin
            Memo1.Lines.Add('Repeated pagination token; secret enumeration is incomplete.');
            Exit;
          end;
        success := CkHashtable_AddStr(seenTokens,nextToken,'seen');
        if (success <> True) then
          begin
            Memo1.Lines.Add('Could not track pagination.');
            Exit;
          end;
      end;
  end;

Memo1.Lines.Add('Secret enumeration complete.');

CkStringBuilder_Dispose(stringCompare);
CkJsonObject_Dispose(credentials);
CkStringBuilder_Dispose(endpoint);
CkAuthAws_Dispose(aws);
CkRest_Dispose(rest);
CkSocket_Dispose(connection);
CkJsonObject_Dispose(body);
CkJsonObject_Dispose(result);
CkHashtable_Dispose(seenTokens);
CkJsonArray_Dispose(secrets);
CkJsonObject_Dispose(secretEntry);
CkJsonObject_Dispose(versions);
CkJsonArray_Dispose(stages);