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.
Chilkat Ruby Downloads
require 'chilkat'
success = false
stringCompare = Chilkat::CkStringBuilder.new()
# Assumes Chilkat is unlocked. See Global Unlock Sample.
# Keep this credentials file outside public web content and source control.
credentials = Chilkat::CkJsonObject.new()
credentials.put_Strict(true)
success = credentials.LoadFile("qa_data/aws/secrets-manager.json")
if (success != true)
print "Could not load private Secrets Manager configuration." + "\n";
exit
end
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." + "\n";
exit
end
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." + "\n";
exit
end
region = "us-west-2"
endpoint = Chilkat::CkStringBuilder.new()
endpoint.Append("secretsmanager.")
endpoint.Append(region)
endpoint.Append(".amazonaws.com")
aws = Chilkat::CkAuthAws.new()
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.new()
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." + "\n";
exit
end
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." + "\n";
exit
end
end
connection = Chilkat::CkSocket.new()
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." + "\n";
exit
end
success = rest.UseConnection(connection,true)
if (success != true)
print "Could not attach TLS connection." + "\n";
exit
end
# Keep connection alive while Rest uses it.
body = Chilkat::CkJsonObject.new()
result = Chilkat::CkJsonObject.new()
result.put_Strict(true)
seenTokens = Chilkat::CkHashtable.new()
secrets = Chilkat::CkJsonArray.new()
secretEntry = Chilkat::CkJsonObject.new()
versions = Chilkat::CkJsonObject.new()
stages = Chilkat::CkJsonArray.new()
nextToken = ""
page = 0
more = true
while (more == true)
if (page == 10000)
print "Page bound reached; secret enumeration is incomplete." + "\n";
exit
end
page = page + 1
body.Clear()
success = body.UpdateInt("MaxResults",100)
if (success != true)
print "Could not set page size." + "\n";
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.
stringCompare.SetString(nextToken)
stringMatch4 = stringCompare.ContentsEqual("",true)
if (stringMatch4 != true)
success = body.UpdateString("NextToken",nextToken)
if (success != true)
print "Could not set NextToken." + "\n";
exit
end
end
success = rest.ClearAllQueryParams()
if (success != true)
print "Could not clear query parameters." + "\n";
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 (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." + "\n";
exit
end
end
success = rest.AddHeader("Content-Type","application/x-amz-json-1.1")
if (success != true)
print "Could not set content type." + "\n";
exit
end
success = rest.AddHeader("X-Amz-Target","secretsmanager.ListSecrets")
if (success != true)
print "Could not select operation." + "\n";
exit
end
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." + "\n";
exit
end
if (rest.get_ResponseStatusCode() != 200)
print "Secrets Manager HTTP status: " + rest.get_ResponseStatusCode().to_s() + "\n";
success = result.Load(responseJson)
if (success == true)
if (result.JsonTypeOf("__type") == 1)
print "AWS error code: " + result.stringOf("__type") + "\n";
end
end
print "AWS request ID: " + rest.responseHdrByName("x-amzn-RequestId") + "\n";
# Do not print response bodies, request bodies, credentials, or secret values.
exit
end
success = result.Load(responseJson)
if (success != true)
print "Expected a well-formed JSON response." + "\n";
exit
end
if (result.JsonTypeOf("SecretList") != 4)
print "Expected a SecretList array." + "\n";
exit
end
success = result.ArrayOf2("SecretList",secrets)
if (success != true)
print "Could not read secret entries." + "\n";
exit
end
i = 0
while (i < secrets.get_Size())
success = secrets.ObjectAt2(i,secretEntry)
if (success != true)
print "Invalid secret entry." + "\n";
exit
end
stringCompare.SetString(secretEntry.stringOf("Name"))
stringMatch5 = stringCompare.ContentsEqual("",true)
if ((secretEntry.JsonTypeOf("Name") != 1) or (stringMatch5 == true))
print "Missing or invalid Name." + "\n";
exit
end
stringCompare.SetString(secretEntry.stringOf("ARN"))
stringMatch6 = stringCompare.ContentsEqual("",true)
if ((secretEntry.JsonTypeOf("ARN") != 1) or (stringMatch6 == true))
print "Missing or invalid ARN." + "\n";
exit
end
print "Secret name: " + secretEntry.stringOf("Name") + "\n";
print "Secret ARN: " + secretEntry.stringOf("ARN") + "\n";
# 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." + "\n";
exit
end
success = secretEntry.ObjectOf2("SecretVersionsToStages",versions)
if (success != true)
print "Could not read version mapping." + "\n";
exit
end
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." + "\n";
exit
end
k = 0
while (k < stages.get_Size())
if (stages.TypeAt(k) != 1)
print "Expected a string staging label." + "\n";
exit
end
print " Version " + versionId + " label: " + stages.stringAt(k) + "\n";
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 = 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." + "\n";
exit
end
nextToken = result.stringOf("NextToken")
if (seenTokens.Contains(nextToken) == true)
print "Repeated pagination token; secret enumeration is incomplete." + "\n";
exit
end
success = seenTokens.AddStr(nextToken,"seen")
if (success != true)
print "Could not track pagination." + "\n";
exit
end
end
end
print "Secret enumeration complete." + "\n";