AWS Secrets Manager: Store a New Text or Binary Secret Version
See more AWS Secrets Manager Examples
Creates a new version of an existing secret from a private UTF-8 text file or binary file. Text is sent as SecretString; binary is Base64-encoded as SecretBinary. Only one is included. The default updates AWSCURRENT and lets AWS maintain AWSPREVIOUS. It does not modify an external database password or API credential.
Uses optional string put_request_token in the private configuration, or generates a UUID. Persist it and the exact payload before sending for restart-safe retries; the same token with different data fails. Avoid sustained updates more frequently than once every ten minutes: each update creates a version and can exhaust the version quota. The sample loads up to 65,536 bytes in memory and never logs the value.
Required actions: secretsmanager:PutSecretValue.
Encryption under a customer-managed key may require kms:GenerateDataKey and kms:Decrypt.
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 Delphi DLL Downloads
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;
secretId: PWideChar;
clientRequestToken: PWideChar;
stringMatch4: Boolean;
crypt: HCkCrypt2;
requestTokenText: HCkStringBuilder;
useBinary: Boolean;
secretData: HCkBinData;
secretText: HCkStringBuilder;
stringMatch5: Boolean;
stringMatch6: Boolean;
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);
// Keep connection alive while Rest uses it.
body := CkJsonObject_Create();
result := CkJsonObject_Create();
CkJsonObject_putStrict(result,True);
// Use a secret name or complete ARN. IDs remain opaque strings.
secretId := 'example/application';
// One token per logical operation. Keep it and the identical payload for retries.
// Persist the token before sending if retrying across process restarts.
if (CkJsonObject_HasMember(credentials,'put_request_token') = True) then
begin
CkStringBuilder_SetString(stringCompare,CkJsonObject__stringOf(credentials,'put_request_token'));
stringMatch4 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
if ((CkJsonObject_JsonTypeOf(credentials,'put_request_token') <> 1) or (stringMatch4 = True)) then
begin
Memo1.Lines.Add('Missing or invalid put_request_token.');
Exit;
end;
clientRequestToken := CkJsonObject__stringOf(credentials,'put_request_token');
end
else
begin
crypt := CkCrypt2_Create();
clientRequestToken := CkCrypt2__generateUuid(crypt);
if (CkCrypt2_getLastMethodSuccess(crypt) <> True) then
begin
Memo1.Lines.Add('Could not generate a request UUID.');
Exit;
end;
end;
requestTokenText := CkStringBuilder_Create();
CkStringBuilder_Append(requestTokenText,clientRequestToken);
if ((CkStringBuilder_getLength(requestTokenText) < 32) or (CkStringBuilder_getLength(requestTokenText) > 64)) then
begin
Memo1.Lines.Add('Request token must contain 32 to 64 characters.');
Exit;
end;
// False: read a UTF-8 text secret (JSON is also text). True: read raw binary.
useBinary := False;
secretData := CkBinData_Create();
success := CkJsonObject_UpdateString(body,'SecretId',secretId);
if (success <> True) then
begin
Memo1.Lines.Add('Could not set SecretId.');
Exit;
end;
success := CkJsonObject_UpdateString(body,'ClientRequestToken',clientRequestToken);
if (success <> True) then
begin
Memo1.Lines.Add('Could not set ClientRequestToken.');
Exit;
end;
if (useBinary = True) then
begin
success := CkBinData_LoadFile(secretData,'qa_data/aws/secret-value.bin');
if (success <> True) then
begin
Memo1.Lines.Add('Could not load the private binary secret.');
Exit;
end;
if ((CkBinData_getNumBytes(secretData) < 1) or (CkBinData_getNumBytes(secretData) > 65536)) then
begin
Memo1.Lines.Add('Secret must contain 1 to 65536 bytes.');
Exit;
end;
success := CkJsonObject_UpdateString(body,'SecretBinary',CkBinData__getEncoded(secretData,'base64'));
if (success <> True) then
begin
Memo1.Lines.Add('Could not set SecretBinary.');
Exit;
end;
end
else
begin
secretText := CkStringBuilder_Create();
success := CkStringBuilder_LoadFile(secretText,'qa_data/aws/secret-value.txt','utf-8');
if (success <> True) then
begin
Memo1.Lines.Add('Could not load the private text secret.');
Exit;
end;
success := CkBinData_AppendString(secretData,CkStringBuilder__getAsString(secretText),'utf-8');
if (success <> True) then
begin
Memo1.Lines.Add('Could not encode the text secret.');
Exit;
end;
if ((CkBinData_getNumBytes(secretData) < 1) or (CkBinData_getNumBytes(secretData) > 65536)) then
begin
Memo1.Lines.Add('Secret must contain 1 to 65536 UTF-8 bytes.');
Exit;
end;
success := CkJsonObject_UpdateString(body,'SecretString',CkStringBuilder__getAsString(secretText));
if (success <> True) then
begin
Memo1.Lines.Add('Could not set SecretString.');
Exit;
end;
end;
// Omitting VersionStages moves AWSCURRENT to this new version.
// AWS moves AWSPREVIOUS to the version that previously held AWSCURRENT.
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.PutSecretValue');
if (success <> True) then
begin
Memo1.Lines.Add('Could not select operation.');
Exit;
end;
// Establish a connection for this deliberate operation. Do not replay a write
// automatically if the server receives it but its response is lost.
CkRest_Disconnect(rest,10);
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,False);
if (success <> True) then
begin
Memo1.Lines.Add('Could not attach the TLS connection.');
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;
CkStringBuilder_SetString(stringCompare,CkJsonObject__stringOf(result,'ARN'));
stringMatch5 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
if ((CkJsonObject_JsonTypeOf(result,'ARN') <> 1) or (stringMatch5 = True)) then
begin
Memo1.Lines.Add('Missing or invalid ARN.');
Exit;
end;
CkStringBuilder_SetString(stringCompare,CkJsonObject__stringOf(result,'VersionId'));
stringMatch6 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
if ((CkJsonObject_JsonTypeOf(result,'VersionId') <> 1) or (stringMatch6 = True)) then
begin
Memo1.Lines.Add('Missing or invalid VersionId.');
Exit;
end;
CkStringBuilder_SetString(stringCompare,CkJsonObject__stringOf(result,'VersionId'));
stringMatch7 := CkStringBuilder_ContentsEqual(stringCompare,clientRequestToken,True);
if (stringMatch7 <> True) then
begin
Memo1.Lines.Add('Unexpected version ID; reconcile before retrying.');
Exit;
end;
Memo1.Lines.Add('Stored secret version: ' + CkJsonObject__stringOf(result,'VersionId'));
// This stores a value; it does not change credentials in the external system.
CkStringBuilder_Dispose(stringCompare);
CkJsonObject_Dispose(credentials);
CkStringBuilder_Dispose(endpoint);
CkAuthAws_Dispose(aws);
CkRest_Dispose(rest);
CkSocket_Dispose(connection);
CkJsonObject_Dispose(body);
CkJsonObject_Dispose(result);
CkCrypt2_Dispose(crypt);
CkStringBuilder_Dispose(requestTokenText);
CkBinData_Dispose(secretData);
CkStringBuilder_Dispose(secretText);