Sample code for 30+ languages & platforms
Unicode C++ Requires Chilkat v11.6.0+

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.

Microsoft API reference

Chilkat Unicode C++ Downloads

Unicode C++
#include <CkJsonObjectW.h>
#include <CkHttpW.h>
#include <CkHttpResponseW.h>
#include <CkUrlW.h>
#include <CkJsonArrayW.h>

void ChilkatSample(void)
    {
    bool 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.
    CkJsonObjectW token;
    token.put_Strict(true);
    success = token.LoadFile(L"qa_data/tokens/azureToken.json");
    if (success != true) {
        wprintf(L"Could not load the private Azure Resource Manager token file.\n");
        return;
    }

    if ((token.JsonTypeOf(L"access_token") != 1) || (token.StringOfEquals(L"access_token",L"",true) == true)) {
        wprintf(L"A nonempty access_token string is required.\n");
        return;
    }

    //  Use your subscription ID as a string. The all-zero value is only a placeholder.
    const wchar_t *subscriptionId = L"00000000-0000-0000-0000-000000000000";
    CkHttpW http;
    http.put_AuthToken(token.stringOf(L"access_token"));
    http.put_Accept(L"application/json");
    http.put_RequireSslCertVerify(true);
    http.put_FollowRedirects(false);
    http.put_ConnectTimeout(30);
    http.put_ReadTimeout(60);
    success = http.SetUrlVar(L"subscriptionId",subscriptionId);
    if (success != true) {
        wprintf(L"Could not encode subscription ID.\n");
        return;
    }

    CkHttpResponseW response;
    CkJsonObjectW result;
    result.put_Strict(true);
    CkUrlW parsed;
    const wchar_t *resourceGroupName = L"my-resource-group";
    success = http.SetUrlVar(L"resourceGroupName",resourceGroupName);
    if (success != true) {
        wprintf(L"Could not encode resource group.\n");
        return;
    }

    const wchar_t *accountName = L"youruniquestorageaccount";
    success = http.SetUrlVar(L"accountName",accountName);
    if (success != true) {
        wprintf(L"Could not encode account name.\n");
        return;
    }

    const wchar_t *resourceUrl = L"https://management.azure.com/subscriptions/{$subscriptionId}/resourceGroups/{$resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{$accountName}?api-version=2026-09-01";
    success = http.HttpNoBody(L"GET",resourceUrl,response);
    if (response.get_StatusCode() == 0) {
        wprintf(L"No HTTP response. Inspect LastErrorText privately; it may contain credentials.\n");
        return;
    }

    if ((response.get_StatusCode() != 200)) {
        wprintf(L"HTTP status: %d\n",response.get_StatusCode());
        wprintf(L"Request ID: %s\n",response.getHeaderField(L"x-ms-request-id"));
        wprintf(L"Retry-After: %s\n",response.getHeaderField(L"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.
        return;
    }

    if (success != true) {
        wprintf(L"The HTTP response could not be read completely.\n");
        return;
    }

    success = result.Load(response.bodyStr());
    if (success != true) {
        wprintf(L"Expected a well-formed JSON response.\n");
        return;
    }

    const wchar_t *policyUrl = L"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.
    bool createMissingPolicy = false;
    success = http.HttpNoBody(L"GET",policyUrl,response);
    if ((response.get_StatusCode() != 200) && (response.get_StatusCode() != 404)) {
        wprintf(L"Could not read policy. HTTP status: %d\n",response.get_StatusCode());
        wprintf(L"Retry-After: %s\n",response.getHeaderField(L"Retry-After"));
        return;
    }

    if ((response.get_StatusCode() == 200) && (success != true)) {
        wprintf(L"Incomplete policy response.\n");
        return;
    }

    CkJsonObjectW request;
    request.UpdateNewArray(L"properties.policy.rules");
    CkJsonArrayW mergedRules;
    success = request.ArrayOf2(L"properties.policy.rules",mergedRules);
    if (success != true) {
        wprintf(L"Could not prepare rule array.\n");
        return;
    }

    //  Only this named rule belongs to this example. Other rules are copied unchanged.
    const wchar_t *ruleName = L"CoolSelectedBlobsAfter30Days";
    if (response.get_StatusCode() == 200) {
        success = result.Load(response.bodyStr());
        if (success != true) {
            wprintf(L"Expected a well-formed JSON response.\n");
            return;
        }

        if (result.JsonTypeOf(L"properties.policy.rules") != 4) {
            wprintf(L"Missing or invalid properties.policy.rules.\n");
            return;
        }

        CkJsonArrayW existingRules;
        success = result.ArrayOf2(L"properties.policy.rules",existingRules);
        if (success != true) {
            wprintf(L"Could not read existing rules.\n");
            return;
        }

        CkJsonObjectW oldRule;
        int i = 0;
        while ((i < existingRules.get_Size())) {
            success = existingRules.ObjectAt2(i,oldRule);
            if (success != true) {
                wprintf(L"Invalid existing rule.\n");
                return;
            }

            if (oldRule.JsonTypeOf(L"name") != 1) {
                wprintf(L"Missing or invalid name.\n");
                return;
            }

            if (oldRule.StringOfEquals(L"name",ruleName,true) != true) {
                success = mergedRules.AddObjectCopyAt(-1,oldRule);
                if (success != true) {
                    wprintf(L"Could not preserve rule.\n");
                    return;
                }

            }

            i = i + 1;
        }

    }
    else {
        if (createMissingPolicy != true) {
            wprintf(L"No policy returned (404). Verify the target, then set createMissingPolicy to true to create one.\n");
            return;
        }

    }

    CkJsonObjectW rule;
    success = mergedRules.AddObjectAt2(-1,rule);
    if (success != true) {
        wprintf(L"Could not add lifecycle rule.\n");
        return;
    }

    rule.UpdateString(L"name",ruleName);
    rule.UpdateString(L"type",L"Lifecycle");
    rule.UpdateBool(L"enabled",true);
    rule.UpdateString(L"definition.filters.blobTypes[0]",L"blockBlob");
    //  Prefix begins with a container name; it is not a URL or wildcard expression.
    rule.UpdateString(L"definition.filters.prefixMatch[0]",L"my-container/archive/");
    rule.UpdateInt(L"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 = http.HttpJson(L"PUT",policyUrl,request,L"application/json",response);
    if (response.get_StatusCode() == 0) {
        wprintf(L"No HTTP response. Inspect LastErrorText privately; it may contain credentials.\n");
        return;
    }

    if ((response.get_StatusCode() != 200)) {
        wprintf(L"HTTP status: %d\n",response.get_StatusCode());
        wprintf(L"Request ID: %s\n",response.getHeaderField(L"x-ms-request-id"));
        wprintf(L"Retry-After: %s\n",response.getHeaderField(L"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.
        return;
    }

    if (success != true) {
        wprintf(L"The HTTP response could not be read completely.\n");
        return;
    }

    success = result.Load(response.bodyStr());
    if (success != true) {
        wprintf(L"Expected a well-formed JSON response.\n");
        return;
    }

    wprintf(L"Lifecycle policy updated. Matching blobs are processed asynchronously by Azure.\n");
    }