Sample code for 30+ languages & platforms
Delphi DLL Requires Chilkat v11.6.0+

AWS Secrets Manager: Create a Secret with a JSON Value

See more AWS Secrets Manager Examples

Creates a secret and its initial AWSCURRENT version. Loads username/password fields from a protected local JSON file and passes the serialized object as SecretString. A secret string can also be ordinary text; JSON is an application convention, not a requirement. The value is encrypted by Secrets Manager using AWS KMS. Do not place confidential data in the name, description, or tags.

A raw HTTP caller must provide a ClientRequestToken. This example generates a random UUID once per run, or reuses optional string client_request_token from the private configuration. Preserve the same token and exact value when retrying a logical create, including across process restarts; do not generate a new token for a retry. The token becomes the version ID. Use PutSecretValue to change an existing secret's value.

Requires secretsmanager:CreateSecret. With a customer-managed KMS key, also arrange kms:GenerateDataKey and kms:Decrypt permissions and key-policy access. Omitting KmsKeyId uses aws/secretsmanager; cross-account encryption requires a customer-managed key. Adding tags or replicas needs their additional Secrets Manager permissions. The example performs a real create when configured and run.

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 CreateSecret reference

Chilkat Delphi DLL Downloads

Delphi DLL
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;
secretName: PWideChar;
secretData: HCkJsonObject;
stringMatch4: Boolean;
stringMatch5: Boolean;
clientRequestToken: PWideChar;
stringMatch6: Boolean;
tokenText: HCkStringBuilder;
crypt: HCkCrypt2;
stringMatch7: Boolean;
stringMatch8: Boolean;
stringMatch9: 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);
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,True);
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not attach TLS connection.');
    Exit;
  end;
//  Keep connection alive while Rest uses it.
body := CkJsonObject_Create();
result := CkJsonObject_Create();
CkJsonObject_putStrict(result,True);

//  Use a new name for a new secret. CreateSecret does not update an existing value.
secretName := 'example/application';
//  Example private file: {"username":"...","password":"..."}.
//  Load values at runtime instead of embedding credentials in source code.
secretData := CkJsonObject_Create();
CkJsonObject_putStrict(secretData,True);
success := CkJsonObject_LoadFile(secretData,'qa_data/aws/secret-value.json');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not load private secret-value.json.');
    Exit;
  end;
CkStringBuilder_SetString(stringCompare,CkJsonObject__stringOf(secretData,'username'));
stringMatch4 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
if ((CkJsonObject_JsonTypeOf(secretData,'username') <> 1) or (stringMatch4 = True)) then
  begin
    Memo1.Lines.Add('Missing or invalid username.');
    Exit;
  end;
CkStringBuilder_SetString(stringCompare,CkJsonObject__stringOf(secretData,'password'));
stringMatch5 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
if ((CkJsonObject_JsonTypeOf(secretData,'password') <> 1) or (stringMatch5 = True)) then
  begin
    Memo1.Lines.Add('Missing or invalid password.');
    Exit;
  end;
//  A raw REST caller must supply its own UUID; an AWS SDK would supply one.
//  Reuse BOTH the token and the same payload when retrying this logical create.
//  Persist them privately before sending if the application must survive a restart.

if (CkJsonObject_HasMember(credentials,'client_request_token') = True) then
  begin
    CkStringBuilder_SetString(stringCompare,CkJsonObject__stringOf(credentials,'client_request_token'));
    stringMatch6 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
    if ((CkJsonObject_JsonTypeOf(credentials,'client_request_token') <> 1) or (stringMatch6 = True)) then
      begin
        Memo1.Lines.Add('Missing or invalid client_request_token.');
        Exit;
      end;
    clientRequestToken := CkJsonObject__stringOf(credentials,'client_request_token');
    tokenText := CkStringBuilder_Create();
    CkStringBuilder_Append(tokenText,clientRequestToken);
    if ((CkStringBuilder_getLength(tokenText) < 32) or (CkStringBuilder_getLength(tokenText) > 64)) then
      begin
        Memo1.Lines.Add('client_request_token must contain 32 to 64 characters.');
        Exit;
      end;
  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;
success := CkJsonObject_UpdateString(body,'Name',secretName);
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not set Name.');
    Exit;
  end;
success := CkJsonObject_UpdateString(body,'Description','Application credentials');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not set Description.');
    Exit;
  end;
success := CkJsonObject_UpdateString(body,'ClientRequestToken',clientRequestToken);
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not set ClientRequestToken.');
    Exit;
  end;
//  Emit the inner JSON as a STRING in the outer request. UpdateString escapes it.
success := CkJsonObject_UpdateString(body,'SecretString',CkJsonObject__emit(secretData));
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not set SecretString.');
    Exit;
  end;
//  Omit KmsKeyId to use aws/secretsmanager. Supply it for a customer-managed key.
//  Do not send SecretBinary together with SecretString.
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.CreateSecret');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not select operation.');
    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'));
stringMatch7 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
if ((CkJsonObject_JsonTypeOf(result,'ARN') <> 1) or (stringMatch7 = True)) then
  begin
    Memo1.Lines.Add('Missing or invalid ARN.');
    Exit;
  end;
CkStringBuilder_SetString(stringCompare,CkJsonObject__stringOf(result,'VersionId'));
stringMatch8 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
if ((CkJsonObject_JsonTypeOf(result,'VersionId') <> 1) or (stringMatch8 = True)) then
  begin
    Memo1.Lines.Add('Missing or invalid VersionId.');
    Exit;
  end;
CkStringBuilder_SetString(stringCompare,CkJsonObject__stringOf(result,'VersionId'));
stringMatch9 := CkStringBuilder_ContentsEqual(stringCompare,clientRequestToken,True);
if (stringMatch9 <> True) then
  begin
    Memo1.Lines.Add('Unexpected version ID; reconcile the create result before retrying.');
    Exit;
  end;
Memo1.Lines.Add('Created secret ARN: ' + CkJsonObject__stringOf(result,'ARN'));
Memo1.Lines.Add('Initial version ID: ' + CkJsonObject__stringOf(result,'VersionId'));
//  The initial value receives AWSCURRENT. Save the ARN for subsequent operations.

CkStringBuilder_Dispose(stringCompare);
CkJsonObject_Dispose(credentials);
CkStringBuilder_Dispose(endpoint);
CkAuthAws_Dispose(aws);
CkRest_Dispose(rest);
CkSocket_Dispose(connection);
CkJsonObject_Dispose(body);
CkJsonObject_Dispose(result);
CkJsonObject_Dispose(secretData);
    CkStringBuilder_Dispose(tokenText);
    CkCrypt2_Dispose(crypt);