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

Lua
local chilkat = require("chilkat")

-- 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.
local token = chilkat.JsonObject.new()
token.strict = true
local success = token:load_file("qa_data/tokens/azureToken.json")
if not success then
    print("Could not load the private Azure Resource Manager token file.")
    return
end

if (token:json_type_of("access_token") ~= 1) or (token:string_of_equals("access_token", "", true)) then
    print("A nonempty access_token string is required.")
    return
end

-- Use your subscription ID as a string. The all-zero value is only a placeholder.
local subscriptionId = "00000000-0000-0000-0000-000000000000"
local http = chilkat.Http.new()
http.auth_token = token:string_of("access_token")
http.accept = "application/json"
http.require_ssl_cert_verify = true
http.follow_redirects = false
http.connect_timeout = 30
http.read_timeout = 60
success = http:set_url_var("subscriptionId", subscriptionId)
if not success then
    print("Could not encode subscription ID.")
    return
end

local response = chilkat.HttpResponse.new()
local result = chilkat.JsonObject.new()
result.strict = true
local parsed = chilkat.Url.new()
local resourceGroupName = "my-resource-group"
success = http:set_url_var("resourceGroupName", resourceGroupName)
if not success then
    print("Could not encode resource group.")
    return
end

local accountName = "youruniquestorageaccount"
success = http:set_url_var("accountName", accountName)
if not success then
    print("Could not encode account name.")
    return
end

local resourceUrl = "https://management.azure.com/subscriptions/{$subscriptionId}/resourceGroups/{$resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{$accountName}?api-version=2026-09-01"
success = http:http_no_body("GET", resourceUrl, response)
if response.status_code == 0 then
    print("No HTTP response. Inspect LastErrorText privately; it may contain credentials.")
    return
end

if response.status_code ~= 200 then
    print("HTTP status: " .. response.status_code)
    print("Request ID: " .. response:get_header_field("x-ms-request-id"))
    print("Retry-After: " .. response:get_header_field("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
end

if not success then
    print("The HTTP response could not be read completely.")
    return
end

success = result:load(response.body_str)
if not success then
    print("Expected a well-formed JSON response.")
    return
end

local 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.
local createMissingPolicy = false
success = http:http_no_body("GET", policyUrl, response)
if (response.status_code ~= 200) and (response.status_code ~= 404) then
    print("Could not read policy. HTTP status: " .. response.status_code)
    print("Retry-After: " .. response:get_header_field("Retry-After"))
    return
end

if (response.status_code == 200) and (not success) then
    print("Incomplete policy response.")
    return
end

local request = chilkat.JsonObject.new()
request:update_new_array("properties.policy.rules")
local mergedRules = chilkat.JsonArray.new()
success = request:array_of2("properties.policy.rules", mergedRules)
if not success then
    print("Could not prepare rule array.")
    return
end

-- Only this named rule belongs to this example. Other rules are copied unchanged.
local ruleName = "CoolSelectedBlobsAfter30Days"
if response.status_code == 200 then
    success = result:load(response.body_str)
    if not success then
        print("Expected a well-formed JSON response.")
        return
    end

    if result:json_type_of("properties.policy.rules") ~= 4 then
        print("Missing or invalid properties.policy.rules.")
        return
    end

    local existingRules = chilkat.JsonArray.new()
    success = result:array_of2("properties.policy.rules", existingRules)
    if not success then
        print("Could not read existing rules.")
        return
    end

    local oldRule = chilkat.JsonObject.new()
    local i = 0
    while i < existingRules.size do
        success = existingRules:object_at2(i, oldRule)
        if not success then
            print("Invalid existing rule.")
            return
        end

        if oldRule:json_type_of("name") ~= 1 then
            print("Missing or invalid name.")
            return
        end

        if not oldRule:string_of_equals("name", ruleName, true) then
            success = mergedRules:add_object_copy_at(-1, oldRule)
            if not success then
                print("Could not preserve rule.")
                return
            end
        end

        i = i + 1
    end
elseif not createMissingPolicy then
    print("No policy returned (404). Verify the target, then set createMissingPolicy to true to create one.")
    return
end

local rule = chilkat.JsonObject.new()
success = mergedRules:add_object_at2(-1, rule)
if not success then
    print("Could not add lifecycle rule.")
    return
end

rule:update_string("name", ruleName)
rule:update_string("type", "Lifecycle")
rule:update_bool("enabled", true)
rule:update_string("definition.filters.blobTypes[0]", "blockBlob")
-- Prefix begins with a container name; it is not a URL or wildcard expression.
rule:update_string("definition.filters.prefixMatch[0]", "my-container/archive/")
rule:update_int("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:http_json("PUT", policyUrl, request, "application/json", response)
if response.status_code == 0 then
    print("No HTTP response. Inspect LastErrorText privately; it may contain credentials.")
    return
end

if response.status_code ~= 200 then
    print("HTTP status: " .. response.status_code)
    print("Request ID: " .. response:get_header_field("x-ms-request-id"))
    print("Retry-After: " .. response:get_header_field("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
end

if not success then
    print("The HTTP response could not be read completely.")
    return
end

success = result:load(response.body_str)
if not success then
    print("Expected a well-formed JSON response.")
    return
end

print("Lifecycle policy updated. Matching blobs are processed asynchronously by Azure.")