Azure Storage Accounts: Add or Update a Lifecycle Tiering Rule
See more Azure Storage Accounts Examples
Reads the lifecycle policy, replaces only the named rule, and preserves other rules. The new rule moves matching block blobs to Cool after 30 days without modification, scoped by container/blob prefix. It adds no deletion action; existing rules retain their actions.
Review the prefix, existing rule ownership, account support, and tiering/retrieval charges. A policy update schedules background processing; it does not immediately move blobs. The policy PUT replaces the document, so coordinate concurrent writers. If the policy GET returns 404, the default is to stop. Verify that no policy exists, then set createMissingPolicy=true to start a new one.
These calls manage Azure resources at management.azure.com. They do not upload or download stored data. Supply a current Microsoft Entra access token for Azure Resource Manager in private qa_data/tokens/azureToken.json, with a nonempty access_token string. For v2 client credentials, request https://management.azure.com/.default; obtain a new token when it expires. A storage account key, SAS, Microsoft Graph token, or Storage data-plane token is not an ARM token. Never print the token or commit its file.
Azure RBAC must grant the caller the required management actions at the appropriate scope. An app registration alone does not grant resource access. Management permissions and blob/file data permissions are distinct. These examples target public Azure; sovereign clouds require the corresponding authority, ARM endpoint, token audience, and continuation-host validation.
Chilkat Delphi DLL Downloads
var
success: Boolean;
token: HCkJsonObject;
subscriptionId: PWideChar;
http: HCkHttp;
response: HCkHttpResponse;
result: HCkJsonObject;
parsed: HCkUrl;
resourceGroupName: PWideChar;
accountName: PWideChar;
resourceUrl: PWideChar;
policyUrl: PWideChar;
createMissingPolicy: Boolean;
request: HCkJsonObject;
mergedRules: HCkJsonArray;
ruleName: PWideChar;
existingRules: HCkJsonArray;
oldRule: HCkJsonObject;
i: Integer;
rule: HCkJsonObject;
begin
success := False;
// This example requires the Chilkat API to have been previously unlocked.
// See Global.UnlockBundle for sample code.
// This is Azure Resource Manager (the management plane), not a blob data request.
// Load an unexpired Microsoft Entra token whose audience is Azure Resource Manager.
// For the v2 token endpoint, request scope https://management.azure.com/.default.
// Keep the token file private and out of source control and public web directories.
token := CkJsonObject_Create();
CkJsonObject_putStrict(token,True);
success := CkJsonObject_LoadFile(token,'qa_data/tokens/azureToken.json');
if (success <> True) then
begin
Memo1.Lines.Add('Could not load the private Azure Resource Manager token file.');
Exit;
end;
if ((CkJsonObject_JsonTypeOf(token,'access_token') <> 1) or (CkJsonObject_StringOfEquals(token,'access_token','',True) = True)) then
begin
Memo1.Lines.Add('A nonempty access_token string is required.');
Exit;
end;
// Use your subscription ID as a string. The all-zero value is only a placeholder.
subscriptionId := '00000000-0000-0000-0000-000000000000';
http := CkHttp_Create();
CkHttp_putAuthToken(http,CkJsonObject__stringOf(token,'access_token'));
CkHttp_putAccept(http,'application/json');
CkHttp_putRequireSslCertVerify(http,True);
CkHttp_putFollowRedirects(http,False);
CkHttp_putConnectTimeout(http,30);
CkHttp_putReadTimeout(http,60);
success := CkHttp_SetUrlVar(http,'subscriptionId',subscriptionId);
if (success <> True) then
begin
Memo1.Lines.Add('Could not encode subscription ID.');
Exit;
end;
response := CkHttpResponse_Create();
result := CkJsonObject_Create();
CkJsonObject_putStrict(result,True);
parsed := CkUrl_Create();
resourceGroupName := 'my-resource-group';
success := CkHttp_SetUrlVar(http,'resourceGroupName',resourceGroupName);
if (success <> True) then
begin
Memo1.Lines.Add('Could not encode resource group.');
Exit;
end;
accountName := 'youruniquestorageaccount';
success := CkHttp_SetUrlVar(http,'accountName',accountName);
if (success <> True) then
begin
Memo1.Lines.Add('Could not encode account name.');
Exit;
end;
resourceUrl := 'https://management.azure.com/subscriptions/{$subscriptionId}/resourceGroups/{$resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{$accountName}?api-version=2026-09-01';
success := CkHttp_HttpNoBody(http,'GET',resourceUrl,response);
if (CkHttpResponse_getStatusCode(response) = 0) then
begin
Memo1.Lines.Add('No HTTP response. Inspect LastErrorText privately; it may contain credentials.');
Exit;
end;
if ((CkHttpResponse_getStatusCode(response) <> 200)) then
begin
Memo1.Lines.Add('HTTP status: ' + IntToStr(CkHttpResponse_getStatusCode(response)));
Memo1.Lines.Add('Request ID: ' + CkHttpResponse__getHeaderField(response,'x-ms-request-id'));
Memo1.Lines.Add('Retry-After: ' + CkHttpResponse__getHeaderField(response,'Retry-After'));
// Inspect the error body privately. Do not log tokens, headers, or full responses.
// For 401 check the token/audience; for 403 check Azure RBAC and policy.
// Honor Retry-After for 429 and use bounded backoff for transient failures.
Exit;
end;
if (success <> True) then
begin
Memo1.Lines.Add('The HTTP response could not be read completely.');
Exit;
end;
success := CkJsonObject_Load(result,CkHttpResponse__bodyStr(response));
if (success <> True) then
begin
Memo1.Lines.Add('Expected a well-formed JSON response.');
Exit;
end;
policyUrl := 'https://management.azure.com/subscriptions/{$subscriptionId}/resourceGroups/{$resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{$accountName}/managementPolicies/default?api-version=2026-09-01';
// Read the account first so a nonexistent account is not mistaken for no policy.
// Opt in after confirming that a 404 here means no policy has been configured.
createMissingPolicy := False;
success := CkHttp_HttpNoBody(http,'GET',policyUrl,response);
if ((CkHttpResponse_getStatusCode(response) <> 200) and (CkHttpResponse_getStatusCode(response) <> 404)) then
begin
Memo1.Lines.Add('Could not read policy. HTTP status: ' + IntToStr(CkHttpResponse_getStatusCode(response)));
Memo1.Lines.Add('Retry-After: ' + CkHttpResponse__getHeaderField(response,'Retry-After'));
Exit;
end;
if ((CkHttpResponse_getStatusCode(response) = 200) and (success <> True)) then
begin
Memo1.Lines.Add('Incomplete policy response.');
Exit;
end;
request := CkJsonObject_Create();
CkJsonObject_UpdateNewArray(request,'properties.policy.rules');
mergedRules := CkJsonArray_Create();
success := CkJsonObject_ArrayOf2(request,'properties.policy.rules',mergedRules);
if (success <> True) then
begin
Memo1.Lines.Add('Could not prepare rule array.');
Exit;
end;
// Only this named rule belongs to this example. Other rules are copied unchanged.
ruleName := 'CoolSelectedBlobsAfter30Days';
if (CkHttpResponse_getStatusCode(response) = 200) then
begin
success := CkJsonObject_Load(result,CkHttpResponse__bodyStr(response));
if (success <> True) then
begin
Memo1.Lines.Add('Expected a well-formed JSON response.');
Exit;
end;
if (CkJsonObject_JsonTypeOf(result,'properties.policy.rules') <> 4) then
begin
Memo1.Lines.Add('Missing or invalid properties.policy.rules.');
Exit;
end;
existingRules := CkJsonArray_Create();
success := CkJsonObject_ArrayOf2(result,'properties.policy.rules',existingRules);
if (success <> True) then
begin
Memo1.Lines.Add('Could not read existing rules.');
Exit;
end;
oldRule := CkJsonObject_Create();
i := 0;
while (i < CkJsonArray_getSize(existingRules)) do
begin
success := CkJsonArray_ObjectAt2(existingRules,i,oldRule);
if (success <> True) then
begin
Memo1.Lines.Add('Invalid existing rule.');
Exit;
end;
if (CkJsonObject_JsonTypeOf(oldRule,'name') <> 1) then
begin
Memo1.Lines.Add('Missing or invalid name.');
Exit;
end;
if (CkJsonObject_StringOfEquals(oldRule,'name',ruleName,True) <> True) then
begin
success := CkJsonArray_AddObjectCopyAt(mergedRules,-1,oldRule);
if (success <> True) then
begin
Memo1.Lines.Add('Could not preserve rule.');
Exit;
end;
end;
i := i + 1;
end;
end
else
begin
if (createMissingPolicy <> True) then
begin
Memo1.Lines.Add('No policy returned (404). Verify the target, then set createMissingPolicy to true to create one.');
Exit;
end;
end;
rule := CkJsonObject_Create();
success := CkJsonArray_AddObjectAt2(mergedRules,-1,rule);
if (success <> True) then
begin
Memo1.Lines.Add('Could not add lifecycle rule.');
Exit;
end;
CkJsonObject_UpdateString(rule,'name',ruleName);
CkJsonObject_UpdateString(rule,'type','Lifecycle');
CkJsonObject_UpdateBool(rule,'enabled',True);
CkJsonObject_UpdateString(rule,'definition.filters.blobTypes[0]','blockBlob');
// Prefix begins with a container name; it is not a URL or wildcard expression.
CkJsonObject_UpdateString(rule,'definition.filters.prefixMatch[0]','my-container/archive/');
CkJsonObject_UpdateInt(rule,'definition.actions.baseBlob.tierToCool.daysAfterModificationGreaterThan',30);
// No delete action is added. Existing rules, including their actions, remain.
// PUT replaces the policy document; coordinate writers to avoid losing updates.
// On a write timeout, read the resource before deciding whether to retry.
success := CkHttp_HttpJson(http,'PUT',policyUrl,request,'application/json',response);
if (CkHttpResponse_getStatusCode(response) = 0) then
begin
Memo1.Lines.Add('No HTTP response. Inspect LastErrorText privately; it may contain credentials.');
Exit;
end;
if ((CkHttpResponse_getStatusCode(response) <> 200)) then
begin
Memo1.Lines.Add('HTTP status: ' + IntToStr(CkHttpResponse_getStatusCode(response)));
Memo1.Lines.Add('Request ID: ' + CkHttpResponse__getHeaderField(response,'x-ms-request-id'));
Memo1.Lines.Add('Retry-After: ' + CkHttpResponse__getHeaderField(response,'Retry-After'));
// Inspect the error body privately. Do not log tokens, headers, or full responses.
// For 401 check the token/audience; for 403 check Azure RBAC and policy.
// Honor Retry-After for 429 and use bounded backoff for transient failures.
Exit;
end;
if (success <> True) then
begin
Memo1.Lines.Add('The HTTP response could not be read completely.');
Exit;
end;
success := CkJsonObject_Load(result,CkHttpResponse__bodyStr(response));
if (success <> True) then
begin
Memo1.Lines.Add('Expected a well-formed JSON response.');
Exit;
end;
Memo1.Lines.Add('Lifecycle policy updated. Matching blobs are processed asynchronously by Azure.');
CkJsonObject_Dispose(token);
CkHttp_Dispose(http);
CkHttpResponse_Dispose(response);
CkJsonObject_Dispose(result);
CkUrl_Dispose(parsed);
CkJsonObject_Dispose(request);
CkJsonArray_Dispose(mergedRules);
CkJsonArray_Dispose(existingRules);
CkJsonObject_Dispose(oldRule);
CkJsonObject_Dispose(rule);