Sample code for 30+ languages & platforms
Objective-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 Objective-C Downloads

Objective-C
#import <CkoJsonObject.h>
#import <NSString.h>
#import <CkoHttp.h>
#import <CkoHttpResponse.h>
#import <CkoUrl.h>
#import <CkoJsonArray.h>

BOOL success = NO;

//  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.
CkoJsonObject *token = [[CkoJsonObject alloc] init];
token.Strict = YES;
success = [token LoadFile: @"qa_data/tokens/azureToken.json"];
if (success != YES) {
    NSLog(@"%@",@"Could not load the private Azure Resource Manager token file.");
    return;
}

if (([[token JsonTypeOf: @"access_token"] intValue] != 1) || ([token StringOfEquals: @"access_token" value: @"" caseSensitive: YES] == YES)) {
    NSLog(@"%@",@"A nonempty access_token string is required.");
    return;
}

//  Use your subscription ID as a string. The all-zero value is only a placeholder.
NSString *subscriptionId = @"00000000-0000-0000-0000-000000000000";
CkoHttp *http = [[CkoHttp alloc] init];
http.AuthToken = [token StringOf: @"access_token"];
http.Accept = @"application/json";
http.RequireSslCertVerify = YES;
http.FollowRedirects = NO;
http.ConnectTimeout = [NSNumber numberWithInt:30];
http.ReadTimeout = [NSNumber numberWithInt:60];
success = [http SetUrlVar: @"subscriptionId" value: subscriptionId];
if (success != YES) {
    NSLog(@"%@",@"Could not encode subscription ID.");
    return;
}

CkoHttpResponse *response = [[CkoHttpResponse alloc] init];
CkoJsonObject *result = [[CkoJsonObject alloc] init];
result.Strict = YES;
CkoUrl *parsed = [[CkoUrl alloc] init];
NSString *resourceGroupName = @"my-resource-group";
success = [http SetUrlVar: @"resourceGroupName" value: resourceGroupName];
if (success != YES) {
    NSLog(@"%@",@"Could not encode resource group.");
    return;
}

NSString *accountName = @"youruniquestorageaccount";
success = [http SetUrlVar: @"accountName" value: accountName];
if (success != YES) {
    NSLog(@"%@",@"Could not encode account name.");
    return;
}

NSString *resourceUrl = @"https://management.azure.com/subscriptions/{$subscriptionId}/resourceGroups/{$resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{$accountName}?api-version=2026-09-01";
success = [http HttpNoBody: @"GET" url: resourceUrl response: response];
if ([response.StatusCode intValue] == 0) {
    NSLog(@"%@",@"No HTTP response. Inspect LastErrorText privately; it may contain credentials.");
    return;
}

if (([response.StatusCode intValue] != 200)) {
    NSLog(@"%@%d",@"HTTP status: ",[response.StatusCode intValue]);
    NSLog(@"%@%@",@"Request ID: ",[response GetHeaderField: @"x-ms-request-id"]);
    NSLog(@"%@%@",@"Retry-After: ",[response GetHeaderField: @"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 != YES) {
    NSLog(@"%@",@"The HTTP response could not be read completely.");
    return;
}

success = [result Load: response.BodyStr];
if (success != YES) {
    NSLog(@"%@",@"Expected a well-formed JSON response.");
    return;
}

NSString *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.
BOOL createMissingPolicy = NO;
success = [http HttpNoBody: @"GET" url: policyUrl response: response];
if (([response.StatusCode intValue] != 200) && ([response.StatusCode intValue] != 404)) {
    NSLog(@"%@%d",@"Could not read policy. HTTP status: ",[response.StatusCode intValue]);
    NSLog(@"%@%@",@"Retry-After: ",[response GetHeaderField: @"Retry-After"]);
    return;
}

if (([response.StatusCode intValue] == 200) && (success != YES)) {
    NSLog(@"%@",@"Incomplete policy response.");
    return;
}

CkoJsonObject *request = [[CkoJsonObject alloc] init];
[request UpdateNewArray: @"properties.policy.rules"];
CkoJsonArray *mergedRules = [[CkoJsonArray alloc] init];
success = [request ArrayOf2: @"properties.policy.rules" jarr: mergedRules];
if (success != YES) {
    NSLog(@"%@",@"Could not prepare rule array.");
    return;
}

//  Only this named rule belongs to this example. Other rules are copied unchanged.
NSString *ruleName = @"CoolSelectedBlobsAfter30Days";
if ([response.StatusCode intValue] == 200) {
    success = [result Load: response.BodyStr];
    if (success != YES) {
        NSLog(@"%@",@"Expected a well-formed JSON response.");
        return;
    }

    if ([[result JsonTypeOf: @"properties.policy.rules"] intValue] != 4) {
        NSLog(@"%@",@"Missing or invalid properties.policy.rules.");
        return;
    }

    CkoJsonArray *existingRules = [[CkoJsonArray alloc] init];
    success = [result ArrayOf2: @"properties.policy.rules" jarr: existingRules];
    if (success != YES) {
        NSLog(@"%@",@"Could not read existing rules.");
        return;
    }

    CkoJsonObject *oldRule = [[CkoJsonObject alloc] init];
    int i = 0;
    while ((i < [existingRules.Size intValue])) {
        success = [existingRules ObjectAt2: [NSNumber numberWithInt: i] jsonObj: oldRule];
        if (success != YES) {
            NSLog(@"%@",@"Invalid existing rule.");
            return;
        }

        if ([[oldRule JsonTypeOf: @"name"] intValue] != 1) {
            NSLog(@"%@",@"Missing or invalid name.");
            return;
        }

        if ([oldRule StringOfEquals: @"name" value: ruleName caseSensitive: YES] != YES) {
            success = [mergedRules AddObjectCopyAt: [NSNumber numberWithInt: -1] jsonObj: oldRule];
            if (success != YES) {
                NSLog(@"%@",@"Could not preserve rule.");
                return;
            }

        }

        i = i + 1;
    }

}
else {
    if (createMissingPolicy != YES) {
        NSLog(@"%@",@"No policy returned (404). Verify the target, then set createMissingPolicy to true to create one.");
        return;
    }

}

CkoJsonObject *rule = [[CkoJsonObject alloc] init];
success = [mergedRules AddObjectAt2: [NSNumber numberWithInt: -1] json: rule];
if (success != YES) {
    NSLog(@"%@",@"Could not add lifecycle rule.");
    return;
}

[rule UpdateString: @"name" value: ruleName];
[rule UpdateString: @"type" value: @"Lifecycle"];
[rule UpdateBool: @"enabled" value: YES];
[rule UpdateString: @"definition.filters.blobTypes[0]" value: @"blockBlob"];
//  Prefix begins with a container name; it is not a URL or wildcard expression.
[rule UpdateString: @"definition.filters.prefixMatch[0]" value: @"my-container/archive/"];
[rule UpdateInt: @"definition.actions.baseBlob.tierToCool.daysAfterModificationGreaterThan" value: [NSNumber numberWithInt: 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: @"PUT" url: policyUrl json: request contentType: @"application/json" response: response];
if ([response.StatusCode intValue] == 0) {
    NSLog(@"%@",@"No HTTP response. Inspect LastErrorText privately; it may contain credentials.");
    return;
}

if (([response.StatusCode intValue] != 200)) {
    NSLog(@"%@%d",@"HTTP status: ",[response.StatusCode intValue]);
    NSLog(@"%@%@",@"Request ID: ",[response GetHeaderField: @"x-ms-request-id"]);
    NSLog(@"%@%@",@"Retry-After: ",[response GetHeaderField: @"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 != YES) {
    NSLog(@"%@",@"The HTTP response could not be read completely.");
    return;
}

success = [result Load: response.BodyStr];
if (success != YES) {
    NSLog(@"%@",@"Expected a well-formed JSON response.");
    return;
}

NSLog(@"%@",@"Lifecycle policy updated. Matching blobs are processed asynchronously by Azure.");