AWS Secrets Manager: Replicate a Secret and Check Regional Status
See more AWS Secrets Manager Examples
Replicates a primary secret from the signing region to destinationRegion and polls the primary metadata for that specific region. It never overwrites an existing destination secret automatically. Optional replica_kms_key_id must identify a suitable key in the destination region; otherwise AWS uses that region's aws/secretsmanager key. Source and destination must be in compatible AWS partitions.
HTTP 200 is not proof of completed replication. The example distinguishes InProgress, InSync and Failed and bounds polling at 30 checks two seconds apart. An unobserved destination or timeout remains inconclusive. This does not cancel or remove replicas, promote a replica, or configure cross-account replication. Read replicas through their regional endpoints; primary updates and rotations propagate asynchronously.
Required actions: secretsmanager:DescribeSecret, secretsmanager:ReplicateSecretToRegions.
A customer-managed source key requires kms:Decrypt; a customer-managed destination key requires kms:GenerateDataKey and kms:Encrypt, with appropriate key policies.
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 ReplicateSecretToRegions reference
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;
destinationRegion: PWideChar;
stringMatch4: Boolean;
stringMatch5: Boolean;
stringMatch6: Boolean;
stringMatch7: Boolean;
stringMatch8: Boolean;
replicas: HCkJsonArray;
replica: HCkJsonObject;
inSync: Boolean;
attempt: Integer;
stringMatch9: Boolean;
i: Integer;
stringMatch10: Boolean;
stringMatch11: Boolean;
stringMatch12: Boolean;
status: PWideChar;
stringMatch13: Boolean;
stringMatch14: Boolean;
stringMatch15: Boolean;
stringMatch16: 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';
// Requests go to the PRIMARY region (region in the signing setup).
destinationRegion := 'us-east-1';
CkStringBuilder_SetString(stringCompare,destinationRegion);
stringMatch4 := CkStringBuilder_ContentsEqual(stringCompare,region,True);
if (stringMatch4 = True) then
begin
Memo1.Lines.Add('Choose a destination different from the primary region.');
Exit;
end;
CkJsonObject_Clear(body);
success := CkJsonObject_UpdateString(body,'SecretId',secretId);
if (success <> True) then
begin
Memo1.Lines.Add('Could not set SecretId.');
Exit;
end;
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.DescribeSecret');
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;
secretId := CkJsonObject__stringOf(result,'ARN');
if (CkJsonObject_HasMember(result,'PrimaryRegion') = True) then
begin
CkStringBuilder_SetString(stringCompare,CkJsonObject__stringOf(result,'PrimaryRegion'));
stringMatch6 := CkStringBuilder_ContentsEqual(stringCompare,region,True);
if (stringMatch6 <> True) then
begin
Memo1.Lines.Add('Call this example in the primary secret region, not a replica region.');
Exit;
end;
end;
CkJsonObject_Clear(body);
success := CkJsonObject_UpdateString(body,'SecretId',secretId);
if (success <> True) then
begin
Memo1.Lines.Add('Could not set SecretId.');
Exit;
end;
success := CkJsonObject_UpdateString(body,'AddReplicaRegions[0].Region',destinationRegion);
if (success <> True) then
begin
Memo1.Lines.Add('Could not set AddReplicaRegions[0].Region.');
Exit;
end;
success := CkJsonObject_UpdateBool(body,'ForceOverwriteReplicaSecret',False);
if (success <> True) then
begin
Memo1.Lines.Add('Could not set ForceOverwriteReplicaSecret.');
Exit;
end;
// Optional destination-region customer-managed key (not the source-region key).
if (CkJsonObject_HasMember(credentials,'replica_kms_key_id') = True) then
begin
CkStringBuilder_SetString(stringCompare,CkJsonObject__stringOf(credentials,'replica_kms_key_id'));
stringMatch7 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
if ((CkJsonObject_JsonTypeOf(credentials,'replica_kms_key_id') <> 1) or (stringMatch7 = True)) then
begin
Memo1.Lines.Add('Missing or invalid replica_kms_key_id.');
Exit;
end;
success := CkJsonObject_UpdateString(body,'AddReplicaRegions[0].KmsKeyId',CkJsonObject__stringOf(credentials,'replica_kms_key_id'));
if (success <> True) then
begin
Memo1.Lines.Add('Could not set AddReplicaRegions[0].KmsKeyId.');
Exit;
end;
end;
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.ReplicateSecretToRegions');
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'));
stringMatch8 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
if ((CkJsonObject_JsonTypeOf(result,'ARN') <> 1) or (stringMatch8 = True)) then
begin
Memo1.Lines.Add('Missing or invalid ARN.');
Exit;
end;
Memo1.Lines.Add('Replication request accepted. Checking the selected region.');
replicas := CkJsonArray_Create();
replica := CkJsonObject_Create();
inSync := False;
attempt := 0;
while ((attempt < 30) and (inSync <> True)) do
begin
if (attempt > 0) then
begin
CkSocket_SleepMs(connection,2000);
end;
attempt := attempt + 1;
CkJsonObject_Clear(body);
success := CkJsonObject_UpdateString(body,'SecretId',secretId);
if (success <> True) then
begin
Memo1.Lines.Add('Could not set SecretId.');
Exit;
end;
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.DescribeSecret');
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'));
stringMatch9 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
if ((CkJsonObject_JsonTypeOf(result,'ARN') <> 1) or (stringMatch9 = True)) then
begin
Memo1.Lines.Add('Missing or invalid ARN.');
Exit;
end;
if (CkJsonObject_HasMember(result,'ReplicationStatus') = True) then
begin
if (CkJsonObject_JsonTypeOf(result,'ReplicationStatus') <> 4) then
begin
Memo1.Lines.Add('Missing or invalid ReplicationStatus.');
Exit;
end;
success := CkJsonObject_ArrayOf2(result,'ReplicationStatus',replicas);
if (success <> True) then
begin
Memo1.Lines.Add('Could not read ReplicationStatus.');
Exit;
end;
i := 0;
while (i < CkJsonArray_getSize(replicas)) do
begin
success := CkJsonArray_ObjectAt2(replicas,i,replica);
if (success <> True) then
begin
Memo1.Lines.Add('Invalid replica status.');
Exit;
end;
CkStringBuilder_SetString(stringCompare,CkJsonObject__stringOf(replica,'Region'));
stringMatch10 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
if ((CkJsonObject_JsonTypeOf(replica,'Region') <> 1) or (stringMatch10 = True)) then
begin
Memo1.Lines.Add('Missing or invalid Region.');
Exit;
end;
CkStringBuilder_SetString(stringCompare,CkJsonObject__stringOf(replica,'Region'));
stringMatch11 := CkStringBuilder_ContentsEqual(stringCompare,destinationRegion,True);
if (stringMatch11 = True) then
begin
CkStringBuilder_SetString(stringCompare,CkJsonObject__stringOf(replica,'Status'));
stringMatch12 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
if ((CkJsonObject_JsonTypeOf(replica,'Status') <> 1) or (stringMatch12 = True)) then
begin
Memo1.Lines.Add('Missing or invalid Status.');
Exit;
end;
status := CkJsonObject__stringOf(replica,'Status');
CkStringBuilder_SetString(stringCompare,status);
stringMatch13 := CkStringBuilder_ContentsEqual(stringCompare,'Failed',True);
if (stringMatch13 = True) then
begin
Memo1.Lines.Add('Replication failed. Inspect the regional KMS permissions, name conflicts, and StatusMessage privately.');
Exit;
end;
CkStringBuilder_SetString(stringCompare,status);
stringMatch14 := CkStringBuilder_ContentsEqual(stringCompare,'InSync',True);
if (stringMatch14 = True) then
begin
inSync := True;
end;
CkStringBuilder_SetString(stringCompare,status);
stringMatch15 := CkStringBuilder_ContentsEqual(stringCompare,'InSync',True);
CkStringBuilder_SetString(stringCompare,status);
stringMatch16 := CkStringBuilder_ContentsEqual(stringCompare,'InProgress',True);
if ((stringMatch15 <> True) and (stringMatch16 <> True)) then
begin
Memo1.Lines.Add('Unrecognized replication state.');
Exit;
end;
end;
i := i + 1;
end;
end;
end;
if (inSync <> True) then
begin
Memo1.Lines.Add('Replication not yet observed InSync. Check again later; this does not cancel replication.');
Exit;
end;
Memo1.Lines.Add('Selected replica is InSync in: ' + destinationRegion);
// Read the replica through its regional endpoint; keep writes/rotation on the primary.
CkStringBuilder_Dispose(stringCompare);
CkJsonObject_Dispose(credentials);
CkStringBuilder_Dispose(endpoint);
CkAuthAws_Dispose(aws);
CkRest_Dispose(rest);
CkSocket_Dispose(connection);
CkJsonObject_Dispose(body);
CkJsonObject_Dispose(result);
CkJsonArray_Dispose(replicas);
CkJsonObject_Dispose(replica);