AWS Secrets Manager: Start Rotation and Check the Requested Version
See more AWS Secrets Manager Examples
Starts immediate rotation of an already-enabled, Lambda-backed secret using its existing configuration. It does not create a Lambda function or configure its permissions, networking, database access, or secret schema. Service-managed and managed-external secrets require their corresponding service/partner workflow.
Supply optional rotation_request_token or let the sample generate a UUID. Preserve the token for retries. HTTP 200 means the asynchronous rotation was accepted. The sample polls up to 30 times, two seconds apart, until the exact requested version has AWSCURRENT. A timeout is inconclusive and does not cancel rotation; inspect the Lambda logs and rotation state rather than starting another operation. An AWSPENDING label on another version can indicate an earlier incomplete rotation.
Required actions: secretsmanager:DescribeSecret, secretsmanager:RotateSecret.
The caller and rotation integration also need the relevant Lambda invocation/execution and KMS permissions. Moving labels alone is not credential rotation.
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 CkJava Downloads
import com.chilkatsoft.*;
public class ChilkatExample {
static {
try {
System.loadLibrary("chilkat");
} catch (UnsatisfiedLinkError e) {
System.err.println("Native code library failed to load.\n" + e);
System.exit(1);
}
}
public static void main(String argv[])
{
boolean success = false;
CkStringBuilder stringCompare = new CkStringBuilder();
// Assumes Chilkat is unlocked. See Global Unlock Sample.
// Keep this credentials file outside public web content and source control.
CkJsonObject credentials = new CkJsonObject();
credentials.put_Strict(true);
success = credentials.LoadFile("qa_data/aws/secrets-manager.json");
if (success != true) {
System.out.println("Could not load private Secrets Manager configuration.");
return;
}
stringCompare.SetString(credentials.stringOf("access_key"));
boolean stringMatch1 = stringCompare.ContentsEqual("",true);
if ((credentials.JsonTypeOf("access_key") != 1) || (stringMatch1 == true)) {
System.out.println("Missing or invalid access_key.");
return;
}
stringCompare.SetString(credentials.stringOf("secret_key"));
boolean stringMatch2 = stringCompare.ContentsEqual("",true);
if ((credentials.JsonTypeOf("secret_key") != 1) || (stringMatch2 == true)) {
System.out.println("Missing or invalid secret_key.");
return;
}
String region = "us-west-2";
CkStringBuilder endpoint = new CkStringBuilder();
endpoint.Append("secretsmanager.");
endpoint.Append(region);
endpoint.Append(".amazonaws.com");
CkAuthAws aws = new 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);
CkRest rest = new CkRest();
rest.put_ConnectTimeoutMs(20000);
rest.put_IdleTimeoutMs(60000);
rest.put_VerboseLogging(false);
success = rest.SetAuthAws(aws);
if (success != true) {
System.out.println("Could not configure AWS signing.");
return;
}
if (credentials.HasMember("session_token") == true) {
stringCompare.SetString(credentials.stringOf("session_token"));
boolean stringMatch3 = stringCompare.ContentsEqual("",true);
if ((credentials.JsonTypeOf("session_token") != 1) || (stringMatch3 == true)) {
System.out.println("Missing or invalid session_token.");
return;
}
}
CkSocket connection = new CkSocket();
connection.put_RequireSslCertVerify(true);
connection.put_MaxReadIdleMs(60000);
connection.put_MaxSendIdleMs(60000);
// Keep connection alive while Rest uses it.
CkJsonObject body = new CkJsonObject();
CkJsonObject result = new CkJsonObject();
result.put_Strict(true);
String responseJson;
// Use a secret name or complete ARN. IDs remain opaque strings.
String secretId = "example/application";
body.Clear();
success = body.UpdateString("SecretId",secretId);
if (success != true) {
System.out.println("Could not set SecretId.");
return;
}
success = rest.ClearAllQueryParams();
if (success != true) {
System.out.println("Could not clear query parameters.");
return;
}
// 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) {
System.out.println("Could not set session token.");
return;
}
}
success = rest.AddHeader("Content-Type","application/x-amz-json-1.1");
if (success != true) {
System.out.println("Could not set content type.");
return;
}
success = rest.AddHeader("X-Amz-Target","secretsmanager.DescribeSecret");
if (success != true) {
System.out.println("Could not select operation.");
return;
}
// Establish a connection for this deliberate operation. Do not replay a write
// automatically if the server receives it but its response is lost.
rest.Disconnect(10);
success = connection.Connect(endpoint.getAsString(),443,true,20000);
if (success != true) {
System.out.println("TLS connection failed; inspect diagnostics privately.");
return;
}
success = rest.UseConnection(connection,false);
if (success != true) {
System.out.println("Could not attach the TLS connection.");
return;
}
responseJson = rest.fullRequestString("POST","/",body.emit());
if (rest.get_LastMethodSuccess() != true) {
System.out.println("Secrets Manager request did not complete; inspect diagnostics privately. A write may have succeeded.");
return;
}
if (rest.get_ResponseStatusCode() != 200) {
System.out.println("Secrets Manager HTTP status: " + rest.get_ResponseStatusCode());
success = result.Load(responseJson);
if (success == true) {
if (result.JsonTypeOf("__type") == 1) {
System.out.println("AWS error code: " + result.stringOf("__type"));
}
}
System.out.println("AWS request ID: " + rest.responseHdrByName("x-amzn-RequestId"));
// Do not print response bodies, request bodies, credentials, or secret values.
return;
}
success = result.Load(responseJson);
if (success != true) {
System.out.println("Expected a well-formed JSON response.");
return;
}
stringCompare.SetString(result.stringOf("ARN"));
boolean stringMatch4 = stringCompare.ContentsEqual("",true);
if ((result.JsonTypeOf("ARN") != 1) || (stringMatch4 == true)) {
System.out.println("Missing or invalid ARN.");
return;
}
secretId = result.stringOf("ARN");
if (result.JsonTypeOf("RotationEnabled") != 5) {
System.out.println("Missing or invalid RotationEnabled.");
return;
}
if (result.BoolOf("RotationEnabled") != true) {
System.out.println("Configure and enable rotation before running this example.");
return;
}
stringCompare.SetString(result.stringOf("RotationLambdaARN"));
boolean stringMatch5 = stringCompare.ContentsEqual("",true);
if ((result.JsonTypeOf("RotationLambdaARN") != 1) || (stringMatch5 == true)) {
System.out.println("Missing or invalid RotationLambdaARN.");
return;
}
// One token per logical operation. Keep it and the identical payload for retries.
// Persist the token before sending if retrying across process restarts.
String clientRequestToken;
if (credentials.HasMember("rotation_request_token") == true) {
stringCompare.SetString(credentials.stringOf("rotation_request_token"));
boolean stringMatch6 = stringCompare.ContentsEqual("",true);
if ((credentials.JsonTypeOf("rotation_request_token") != 1) || (stringMatch6 == true)) {
System.out.println("Missing or invalid rotation_request_token.");
return;
}
clientRequestToken = credentials.stringOf("rotation_request_token");
}
else {
CkCrypt2 crypt = new CkCrypt2();
clientRequestToken = crypt.generateUuid();
if (crypt.get_LastMethodSuccess() != true) {
System.out.println("Could not generate a request UUID.");
return;
}
}
CkStringBuilder requestTokenText = new CkStringBuilder();
requestTokenText.Append(clientRequestToken);
if ((requestTokenText.get_Length() < 32) || (requestTokenText.get_Length() > 64)) {
System.out.println("Request token must contain 32 to 64 characters.");
return;
}
body.Clear();
success = body.UpdateString("SecretId",secretId);
if (success != true) {
System.out.println("Could not set SecretId.");
return;
}
success = body.UpdateString("ClientRequestToken",clientRequestToken);
if (success != true) {
System.out.println("Could not set ClientRequestToken.");
return;
}
success = body.UpdateBool("RotateImmediately",true);
if (success != true) {
System.out.println("Could not set RotateImmediately.");
return;
}
// Uses the existing Lambda and schedule; no new rotation configuration is sent.
success = rest.ClearAllQueryParams();
if (success != true) {
System.out.println("Could not clear query parameters.");
return;
}
// 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) {
System.out.println("Could not set session token.");
return;
}
}
success = rest.AddHeader("Content-Type","application/x-amz-json-1.1");
if (success != true) {
System.out.println("Could not set content type.");
return;
}
success = rest.AddHeader("X-Amz-Target","secretsmanager.RotateSecret");
if (success != true) {
System.out.println("Could not select operation.");
return;
}
// Establish a connection for this deliberate operation. Do not replay a write
// automatically if the server receives it but its response is lost.
rest.Disconnect(10);
success = connection.Connect(endpoint.getAsString(),443,true,20000);
if (success != true) {
System.out.println("TLS connection failed; inspect diagnostics privately.");
return;
}
success = rest.UseConnection(connection,false);
if (success != true) {
System.out.println("Could not attach the TLS connection.");
return;
}
responseJson = rest.fullRequestString("POST","/",body.emit());
if (rest.get_LastMethodSuccess() != true) {
System.out.println("Secrets Manager request did not complete; inspect diagnostics privately. A write may have succeeded.");
return;
}
if (rest.get_ResponseStatusCode() != 200) {
System.out.println("Secrets Manager HTTP status: " + rest.get_ResponseStatusCode());
success = result.Load(responseJson);
if (success == true) {
if (result.JsonTypeOf("__type") == 1) {
System.out.println("AWS error code: " + result.stringOf("__type"));
}
}
System.out.println("AWS request ID: " + rest.responseHdrByName("x-amzn-RequestId"));
// Do not print response bodies, request bodies, credentials, or secret values.
return;
}
success = result.Load(responseJson);
if (success != true) {
System.out.println("Expected a well-formed JSON response.");
return;
}
stringCompare.SetString(result.stringOf("VersionId"));
boolean stringMatch7 = stringCompare.ContentsEqual("",true);
if ((result.JsonTypeOf("VersionId") != 1) || (stringMatch7 == true)) {
System.out.println("Missing or invalid VersionId.");
return;
}
stringCompare.SetString(result.stringOf("VersionId"));
boolean stringMatch8 = stringCompare.ContentsEqual(clientRequestToken,true);
if (stringMatch8 != true) {
System.out.println("Unexpected rotation version; inspect the operation before retrying.");
return;
}
String rotationVersionId = result.stringOf("VersionId");
System.out.println("Rotation requested for version: " + rotationVersionId);
CkJsonObject versions = new CkJsonObject();
CkJsonArray labels = new CkJsonArray();
int attempt = 0;
boolean current = false;
while (((attempt < 30) && (current != true))) {
if (attempt > 0) {
connection.SleepMs(2000);
}
attempt = attempt+1;
body.Clear();
success = body.UpdateString("SecretId",secretId);
if (success != true) {
System.out.println("Could not set SecretId.");
return;
}
success = rest.ClearAllQueryParams();
if (success != true) {
System.out.println("Could not clear query parameters.");
return;
}
// 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) {
System.out.println("Could not set session token.");
return;
}
}
success = rest.AddHeader("Content-Type","application/x-amz-json-1.1");
if (success != true) {
System.out.println("Could not set content type.");
return;
}
success = rest.AddHeader("X-Amz-Target","secretsmanager.DescribeSecret");
if (success != true) {
System.out.println("Could not select operation.");
return;
}
// Establish a connection for this deliberate operation. Do not replay a write
// automatically if the server receives it but its response is lost.
rest.Disconnect(10);
success = connection.Connect(endpoint.getAsString(),443,true,20000);
if (success != true) {
System.out.println("TLS connection failed; inspect diagnostics privately.");
return;
}
success = rest.UseConnection(connection,false);
if (success != true) {
System.out.println("Could not attach the TLS connection.");
return;
}
responseJson = rest.fullRequestString("POST","/",body.emit());
if (rest.get_LastMethodSuccess() != true) {
System.out.println("Secrets Manager request did not complete; inspect diagnostics privately. A write may have succeeded.");
return;
}
if (rest.get_ResponseStatusCode() != 200) {
System.out.println("Secrets Manager HTTP status: " + rest.get_ResponseStatusCode());
success = result.Load(responseJson);
if (success == true) {
if (result.JsonTypeOf("__type") == 1) {
System.out.println("AWS error code: " + result.stringOf("__type"));
}
}
System.out.println("AWS request ID: " + rest.responseHdrByName("x-amzn-RequestId"));
// Do not print response bodies, request bodies, credentials, or secret values.
return;
}
success = result.Load(responseJson);
if (success != true) {
System.out.println("Expected a well-formed JSON response.");
return;
}
stringCompare.SetString(result.stringOf("ARN"));
boolean stringMatch9 = stringCompare.ContentsEqual("",true);
if ((result.JsonTypeOf("ARN") != 1) || (stringMatch9 == true)) {
System.out.println("Missing or invalid ARN.");
return;
}
if (result.HasMember("VersionIdsToStages") == true) {
if (result.JsonTypeOf("VersionIdsToStages") != 3) {
System.out.println("Missing or invalid VersionIdsToStages.");
return;
}
success = result.ObjectOf2("VersionIdsToStages",versions);
if (success != true) {
System.out.println("Could not read rotation versions.");
return;
}
int i = 0;
while ((i < versions.get_Size())) {
stringCompare.SetString(versions.nameAt(i));
boolean stringMatch10 = stringCompare.ContentsEqual(rotationVersionId,true);
if (stringMatch10 == true) {
success = versions.ArrayAt2(i,labels);
if (success != true) {
System.out.println("Expected staging labels.");
return;
}
int j = 0;
while ((j < labels.get_Size())) {
if (labels.TypeAt(j) != 1) {
System.out.println("Expected a string staging label.");
return;
}
stringCompare.SetString(labels.stringAt(j));
boolean stringMatch11 = stringCompare.ContentsEqual("AWSCURRENT",true);
if (stringMatch11 == true) {
current = true;
}
j = j+1;
}
}
i = i+1;
}
}
}
if (current != true) {
System.out.println("Rotation is not yet observed as current. Check Lambda/CloudTrail; do not start another rotation blindly.");
return;
}
System.out.println("Requested rotation version is now AWSCURRENT.");
}
}