Sample code for 30+ languages & platforms
CkPython 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 CkPython Downloads

CkPython
import sys
import chilkat

success = False

stringCompare = chilkat.CkStringBuilder()
#  Assumes Chilkat is unlocked. See Global Unlock Sample.
#  Keep this credentials file outside public web content and source control.
credentials = chilkat.CkJsonObject()
credentials.put_Strict(True)
success = credentials.LoadFile("qa_data/aws/secrets-manager.json")
if (success != True):
    print("Could not load private Secrets Manager configuration.")
    sys.exit()

stringCompare.SetString(credentials.stringOf("access_key"))
stringMatch1 = stringCompare.ContentsEqual("",True)
if ((credentials.JsonTypeOf("access_key") != 1) or (stringMatch1 == True)):
    print("Missing or invalid access_key.")
    sys.exit()

stringCompare.SetString(credentials.stringOf("secret_key"))
stringMatch2 = stringCompare.ContentsEqual("",True)
if ((credentials.JsonTypeOf("secret_key") != 1) or (stringMatch2 == True)):
    print("Missing or invalid secret_key.")
    sys.exit()

region = "us-west-2"
endpoint = chilkat.CkStringBuilder()
endpoint.Append("secretsmanager.")
endpoint.Append(region)
endpoint.Append(".amazonaws.com")
aws = chilkat.CkAuthAws()
aws.put_AccessKey(credentials.stringOf("access_key"))
aws.put_SecretKey(credentials.stringOf("secret_key"))
aws.put_Region(region)
aws.put_ServiceName("secretsmanager")
aws.put_SignatureVersion(4)
rest = chilkat.CkRest()
rest.put_ConnectTimeoutMs(20000)
rest.put_IdleTimeoutMs(60000)
rest.put_VerboseLogging(False)
success = rest.SetAuthAws(aws)
if (success != True):
    print("Could not configure AWS signing.")
    sys.exit()

if (credentials.HasMember("session_token") == True):
    stringCompare.SetString(credentials.stringOf("session_token"))
    stringMatch3 = stringCompare.ContentsEqual("",True)
    if ((credentials.JsonTypeOf("session_token") != 1) or (stringMatch3 == True)):
        print("Missing or invalid session_token.")
        sys.exit()

connection = chilkat.CkSocket()
connection.put_RequireSslCertVerify(True)
connection.put_MaxReadIdleMs(60000)
connection.put_MaxSendIdleMs(60000)
success = connection.Connect(endpoint.getAsString(),443,True,20000)
if (success != True):
    print("TLS connection failed; inspect diagnostics privately.")
    sys.exit()

success = rest.UseConnection(connection,True)
if (success != True):
    print("Could not attach TLS connection.")
    sys.exit()

#  Keep connection alive while Rest uses it.
body = chilkat.CkJsonObject()
result = chilkat.CkJsonObject()
result.put_Strict(True)

seenTokens = chilkat.CkHashtable()
secrets = chilkat.CkJsonArray()
secretEntry = chilkat.CkJsonObject()
versions = chilkat.CkJsonObject()
stages = chilkat.CkJsonArray()
nextToken = ""
page = 0

more = True
while (more == True) :
    if (page == 10000):
        print("Page bound reached; secret enumeration is incomplete.")
        sys.exit()

    page = page + 1
    body.Clear()
    success = body.UpdateInt("MaxResults",100)
    if (success != True):
        print("Could not set page size.")
        sys.exit()

    #  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.
    stringCompare.SetString(nextToken)
    stringMatch4 = stringCompare.ContentsEqual("",True)
    if (stringMatch4 != True):
        success = body.UpdateString("NextToken",nextToken)
        if (success != True):
            print("Could not set NextToken.")
            sys.exit()

    success = rest.ClearAllQueryParams()
    if (success != True):
        print("Could not clear query parameters.")
        sys.exit()

    #  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 (credentials.HasMember("session_token") == True):
        success = rest.AddQueryParam("X-Amz-Security-Token",credentials.stringOf("session_token"))
        if (success != True):
            print("Could not set session token.")
            sys.exit()

    success = rest.AddHeader("Content-Type","application/x-amz-json-1.1")
    if (success != True):
        print("Could not set content type.")
        sys.exit()

    success = rest.AddHeader("X-Amz-Target","secretsmanager.ListSecrets")
    if (success != True):
        print("Could not select operation.")
        sys.exit()

    responseJson = rest.fullRequestString("POST","/",body.emit())
    if (rest.get_LastMethodSuccess() != True):
        print("Secrets Manager request did not complete; inspect diagnostics privately. A write may have succeeded.")
        sys.exit()

    if (rest.get_ResponseStatusCode() != 200):
        print("Secrets Manager HTTP status: " + str(rest.get_ResponseStatusCode()))
        success = result.Load(responseJson)
        if (success == True):
            if (result.JsonTypeOf("__type") == 1):
                print("AWS error code: " + result.stringOf("__type"))

        print("AWS request ID: " + rest.responseHdrByName("x-amzn-RequestId"))
        #  Do not print response bodies, request bodies, credentials, or secret values.
        sys.exit()

    success = result.Load(responseJson)
    if (success != True):
        print("Expected a well-formed JSON response.")
        sys.exit()

    if (result.JsonTypeOf("SecretList") != 4):
        print("Expected a SecretList array.")
        sys.exit()

    success = result.ArrayOf2("SecretList",secrets)
    if (success != True):
        print("Could not read secret entries.")
        sys.exit()

    i = 0
    while (i < secrets.get_Size()) :
        success = secrets.ObjectAt2(i,secretEntry)
        if (success != True):
            print("Invalid secret entry.")
            sys.exit()

        stringCompare.SetString(secretEntry.stringOf("Name"))
        stringMatch5 = stringCompare.ContentsEqual("",True)
        if ((secretEntry.JsonTypeOf("Name") != 1) or (stringMatch5 == True)):
            print("Missing or invalid Name.")
            sys.exit()

        stringCompare.SetString(secretEntry.stringOf("ARN"))
        stringMatch6 = stringCompare.ContentsEqual("",True)
        if ((secretEntry.JsonTypeOf("ARN") != 1) or (stringMatch6 == True)):
            print("Missing or invalid ARN.")
            sys.exit()

        print("Secret name: " + secretEntry.stringOf("Name"))
        print("Secret ARN: " + secretEntry.stringOf("ARN"))
        #  Metadata only: ListSecrets never returns the decrypted value.
        #  A secret without an initial value may have no version-to-stage mapping.
        if (secretEntry.HasMember("SecretVersionsToStages") == True):
            if (secretEntry.JsonTypeOf("SecretVersionsToStages") != 3):
                print("Expected a version-to-stage object.")
                sys.exit()

            success = secretEntry.ObjectOf2("SecretVersionsToStages",versions)
            if (success != True):
                print("Could not read version mapping.")
                sys.exit()

            j = 0
            while (j < versions.get_Size()) :
                #  Version IDs are opaque strings, including when used as JSON member names.
                versionId = versions.nameAt(j)
                success = versions.ArrayAt2(j,stages)
                if (success != True):
                    print("Expected a staging-label array.")
                    sys.exit()

                k = 0
                while (k < stages.get_Size()) :
                    if (stages.TypeAt(k) != 1):
                        print("Expected a string staging label.")
                        sys.exit()

                    print("  Version " + versionId + " label: " + stages.stringAt(k))
                    k = k + 1

                j = j + 1

        i = i + 1

    #  An empty page can still have NextToken. Stop only when there is no next token.
    more = result.HasMember("NextToken")
    if (more == True):
        stringCompare.SetString(result.stringOf("NextToken"))
        stringMatch7 = stringCompare.ContentsEqual("",True)
        if ((result.JsonTypeOf("NextToken") != 1) or (stringMatch7 == True)):
            print("Missing or invalid NextToken.")
            sys.exit()

        nextToken = result.stringOf("NextToken")
        if (seenTokens.Contains(nextToken) == True):
            print("Repeated pagination token; secret enumeration is incomplete.")
            sys.exit()

        success = seenTokens.AddStr(nextToken,"seen")
        if (success != True):
            print("Could not track pagination.")
            sys.exit()

print("Secret enumeration complete.")