AWS Secrets Manager API Guide
AWS Secrets Manager stores encrypted secret values such as passwords, API credentials, and tokens. Its API lets an application retrieve those values, create and manage versions, control access, rotate supported credentials, and replicate secrets to other AWS regions. This guide links to 15 complete examples using signed Chilkat.Rest requests.
Choose a language to update all 15 example links below. Each link opens the complete example in that language. The guide text and request-mapping table stay the same.
Secrets, versions, and identifiers
A secret is the resource identified by a name and an Amazon Resource Name (ARN). Its metadata includes the description, encryption key, tags, and rotation configuration. A version holds a particular value. Updating a value normally creates a new version; staging labels identify which version an application should use.
Use a secret name within the configured account and region, or its complete ARN. Cross-account retrieval requires an ARN and the corresponding access permissions. Save returned ARNs and version IDs as strings. A name such as example/application is a secret name, not a directory path. There is no need to list all secrets before retrieving a known name.
Credentials and prerequisites
The examples require Chilkat 11.6.0 or later and an unlocked library. They can run wherever the application has network access to the regional service endpoint and an authorized AWS identity. Grant the IAM actions and resource access needed for the chosen operation; encryption under a customer-managed KMS key can require additional KMS permissions and key-policy access.
Each example explicitly loads the private file qa_data/aws/secrets-manager.json. Supply nonempty string fields access_key and secret_key, plus the matching session_token when using temporary role or STS credentials. Prefer short-lived role credentials in production. These examples consume credentials already obtained by the application; they do not discover AWS profiles, obtain a role session, or refresh expired credentials. Protect configuration files and keep them outside source control and public web directories.
How the REST requests map to Chilkat
Secrets Manager uses JSON request bodies sent by HTTPS POST to /. The X-Amz-Target header selects the operation, for example secretsmanager.GetSecretValue. Chilkat signs the request with AWS Signature Version 4. The signing credentials identify the caller; the endpoint and signing region select the region.
| API requirement | Chilkat implementation |
|---|---|
| Regional service endpoint | Use secretsmanager.{region}.amazonaws.com, with the same region in AuthAws.Region. Other AWS partitions use their appropriate endpoints. |
| Signed request | Set AuthAws.ServiceName to secretsmanager, select signature version 4, and pass the credentials object to Rest.SetAuthAws. |
| Temporary credentials | The examples add X-Amz-Security-Token to the signed query with AddQueryParam. Keep request URLs private because they contain this token. |
| Operation and body | Set Content-Type: application/x-amz-json-1.1 and X-Amz-Target with AddHeader. Build the operation's fields using JsonObject. |
| HTTPS exchange | A Socket with RequireSslCertVerify=true supplies the TLS connection to Rest.UseConnection. FullRequestString("POST","/",body.Emit()) sends the request. |
| Result handling | Check LastMethodSuccess, then ResponseStatusCode, then parse and validate the response. Tag and untag operations can return an empty HTTP 200 body. |
The value-update, rotation, and replication examples explicitly establish a connection for each operation with automatic reconnection disabled. If a write reaches AWS but its response is lost, they stop for reconciliation instead of automatically replaying it. Preserve the logical operation's token and payload when implementing retries.
Reading and Discovery
Use GetSecretValue when the application knows the secret's name or ARN. With no version selector, AWS returns AWSCURRENT. The response contains either SecretString or SecretBinary. A string can be ordinary text or JSON; the application decides its schema. Binary values from the raw HTTP API are Base64-encoded and should be decoded to BinData, without assuming they are text. See GetSecretValue.
The retrieval example defaults to the username/password JSON schema used by the create example. Set its parseAsJson option to false for ordinary text, or adapt the fields to your schema. Values are consumed in memory, not printed. Cache frequently used values in protected application memory with an expiration and refresh strategy that accommodates rotation; repeatedly retrieving the same secret adds latency and API charges.
BatchGetSecretValue can retrieve up to 20 explicitly identified secrets. Its HTTP 200 response can still contain per-secret errors, so inspect both successful values and the Errors array. The example requests two names and matches results by identity rather than assuming response order. Filter-based batches are a separate mode that can use pagination; do not combine filters with an explicit ID list. See BatchGetSecretValue.
ListSecrets inventories metadata without retrieving values. Follow every continuation token, including after an empty page. The example uses Hashtable to detect repeated tokens and reports an incomplete enumeration if its page bound is reached. List results can lag changes by five minutes; DescribeSecret is the better choice for more recent metadata about one known secret. Both remain subject to eventual consistency. See ListSecrets.
Creating and Updating Secrets
CreateSecret creates the resource and, when a value is supplied, its initial version. PutSecretValue adds a version to an existing secret. Supply either SecretString or SecretBinary, not both. To store a JSON object as SecretString, serialize the inner object and use UpdateString to place that text in the outer request; Chilkat handles the JSON escaping.
The create example reads qa_data/aws/secret-value.json with username/password fields. The new-version example reads UTF-8 text from secret-value.txt or raw bytes from secret-value.bin in the same directory. It checks the value's byte length against the 65,536-byte limit. Keep these input files private. GetRandomPassword generates a value in memory, but does not store it or change credentials at an external service.
Raw REST callers supply their own ClientRequestToken for create/value operations; AWS SDKs normally generate one. The examples generate a UUID or accept the operation's saved token from configuration. A retry must use the same token and identical value. Persist both before sending when the application must recover across a restart. The token becomes the version ID. See CreateSecret and PutSecretValue.
| Configuration field | Purpose |
|---|---|
client_request_token | Optional saved UUID for the create-secret operation. |
put_request_token | Optional saved UUID for storing a particular new value. |
rotation_request_token | Optional saved UUID for one rotation request. |
kms_key_id | Optional customer-managed key ARN or alias for the metadata-update example. |
move_to_version_id, remove_from_version_id | Required string IDs for a deliberate move of AWSCURRENT. |
replica_kms_key_id | Optional key in the destination region for replication. |
A metadata-only UpdateSecret can change the description or encryption key without adding a new secret value. When changing keys, assess permissions and existing-version encryption before retiring the old key; changing the configured key does not establish that every historical version has migrated. Omit KmsKeyId when creating a secret to use aws/secretsmanager, or specify a suitable customer-managed key. See UpdateSecret.
Versions and Rotation
Version IDs identify stored values; staging labels select their role. AWSCURRENT selects the current value, AWSPREVIOUS commonly identifies the value it replaced, and AWSPENDING participates in rotation. When PutSecretValue moves AWSCURRENT, AWS also moves AWSPREVIOUS to the formerly current version. If GetSecretValue includes both a VersionId and VersionStage, they must identify the same version.
ListSecretVersionIds lists versions containing values, optionally including unlabeled versions with IncludeDeprecated=true. Those deprecated versions can be cleaned up by AWS; they are not a permanent archive. DescribeSecret.VersionIdsToStages can also contain labeled versions without values. Avoid sustained value updates more often than once every ten minutes, because creating versions faster than AWS removes them can exhaust the version quota.
The staging-label example uses both the desired destination version and the expected current source version. AWS rejects the move if AWSCURRENT has moved elsewhere. Investigate that conflict instead of silently replacing the expected source ID. Moving a label does not change the password or token at an external system; a rollback is useful only when the selected value is still valid there. See UpdateSecretVersionStage.
The rotation example starts an immediate rotation using an already-enabled Lambda-backed configuration. It does not create the Lambda function, its permissions, or the target credential integration. It polls for the exact requested version to acquire AWSCURRENT, rather than treating an accepted request as completion. Its 30-check limit leaves a still-pending operation unresolved, not cancelled. Inspect rotation state and Lambda logs before starting another rotation. Service-managed and managed-external secrets use their corresponding service or partner workflows. See RotateSecret.
Tags and Access Policies
Tags belong to the secret rather than an individual version. The tag example can add/update one key, remove it, or inspect the current set. Unrelated tags are preserved. Tag keys are case-sensitive and can affect access when policies use tag conditions. Keep passwords and other secret values out of tags, names, and descriptions.
A resource policy controls access through the secret resource. The policy example reads the existing document, validates a proposed replacement from qa_data/aws/secret-policy.json, and optionally writes it with BlockPublicPolicy=true. It starts in validation-only mode. A successful HTTP response from validation is not sufficient: check PolicyValidationPassed. Applying a policy replaces the document rather than merging statements, so review the current policy and coordinate concurrent edits. See ValidateResourcePolicy and PutResourcePolicy.
Cross-account reads require the caller's IAM permissions, an appropriate secret resource policy, and access to a customer-managed KMS key. The AWS managed aws/secretsmanager key cannot provide that cross-account access. Resource-policy validation and public-policy blocking do not replace an assessment of IAM policies, KMS policies, explicit denies, and other account controls. The example does not grant IAM or KMS permissions.
Deletion and Recovery
The deletion example starts with action="inspect". Select schedule to request a 30-day recovery window or restore to cancel a scheduled deletion in a separate run. During scheduled deletion, secret values cannot be retrieved. Restore the secret before its recovery window ends if it is still needed.
The supported recovery window is 7 to 30 days. Permanent deletion occurs asynchronously after the window and cannot be undone with RestoreSecret. The example does not use ForceDeleteWithoutRecovery. It also distinguishes DeleteSecret.DeletionDate from DescribeSecret.DeletedDate; these are different response field names for the relevant deletion information. See DeleteSecret.
Deleting a replicated primary secret requires separate replica cleanup. Regional replica deletion is immediate and does not inherit the primary recovery window. Replica removal and forced deletion are outside this example's scope.
Multi-Region Replication
ReplicateSecretToRegions adds a regional replica while the request is sent to the primary region. The example resolves the source to its full ARN, selects a different destination region, and sets ForceOverwriteReplicaSecret=false. It does not overwrite a conflicting destination secret automatically.
Choose a customer-managed key in the destination region through replica_kms_key_id, or let AWS use that region's aws/secretsmanager key. Permissions can include kms:Decrypt on a customer-managed source key and kms:GenerateDataKey/kms:Encrypt on the destination key. The primary and destination must be in compatible AWS partitions. See ReplicateSecretToRegions.
The example polls metadata from the primary and checks the selected destination's status: InProgress, InSync, or Failed. An HTTP 200 response alone is not proof of completion. A timeout leaves replication pending or unconfirmed and does not cancel it. Read a replica through its regional endpoint; keep value updates and rotation on the primary. Replication is asynchronous and is not a separate version-history backup. This example does not promote a replica or configure cross-account replication.
Handling failures and sensitive data
Separate transport failure, an AWS HTTP error, and an invalid or incomplete response. The examples report the HTTP status, AWS error type, and x-amzn-RequestId without dumping secret values or full bodies. Access errors can involve IAM, resource policies, KMS policies, or secret state; an expired session requires refreshed credentials. Use bounded backoff with jitter for retryable failures, and reconcile writes whose outcome is uncertain.
SecretString, SecretBinary, generated passwords, credential files, signed URLs, and Chilkat diagnostics need private handling. Use returned values directly in the authorized application component and retain them only as long as needed. Releasing an ordinary string does not guarantee secure memory erasure. Metadata can also be sensitive even when the operation does not retrieve a secret value.