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

Azure Storage Accounts: Create an Account and Monitor Provisioning

See more Azure Storage Accounts Examples

Creates a general-purpose v2 account using direct Chilkat.Http calls and API version 2026-09-01, then monitors provisioning. This operation can create billable resources and can update an existing account at the same resource ID. Review the target and body before running it.

Set the subscription, an existing resource group, a globally unique account name (3-24 lowercase letters or digits), and a supported region. Register Microsoft.Storage for the subscription if necessary. The caller needs account write/read permissions and permission to monitor the operation at resource-group scope. Azure policy, quota, resource locks, and SKU availability can also affect the request.

The sample selects StorageV2, Standard_LRS, and the Hot tier. It requires HTTPS, sets the account's minimum TLS version to 1.2, and disables anonymous blob access. This does not configure private networking or disable Shared Key authentication; choose those policies separately for the intended clients. The minimum-TLS property controls storage clients, not the TLS protocol negotiated by Chilkat.Http.

HTTP 202 means accepted, not ready. The code prefers Azure-AsyncOperation when present, otherwise uses Location, honors integer Retry-After delays, and verifies the final resource state. Polling is bounded. Long or non-integer delays pause the sample for later resumption. Save the printed URL, monitor type, and retry interval; set operationUrl and operationUsesStatus to resume without another PUT. In production, persist this state and schedule polling without blocking the UI.

A timeout after submitting the PUT does not prove that Azure rejected it. Inspect the target resource before submitting again. On polling failures or time limits, resume monitoring instead of creating another request. See tracking asynchronous Azure operations.

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")

local stringCompare = chilkat.StringBuilder.new()
-- 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()

-- Choose an EXISTING resource group and a globally unique 3-24 character name
-- containing only lowercase letters and digits. Choose a supported Azure region.
local resourceGroupName = "my-resource-group"
local accountName = "youruniquestorageaccount"
local location = "eastus"
success = http:set_url_var("resourceGroupName", resourceGroupName)
if not success then
    print("Could not encode resource group.")
    return
end

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"

-- To resume monitoring, paste the operation URL printed by an earlier run here.
-- Also set operationUsesStatus to the printed value (Azure-AsyncOperation=true,
-- Location=false). A nonempty operationUrl skips the PUT completely.
local operationUrl = ""
local operationUsesStatus = false
-- When resuming, first wait for the Retry-After interval from the prior response.
local retryAfter = ""

stringCompare:set_string(operationUrl)
local stringMatch1 = stringCompare:contents_equal("", true)
if stringMatch1 then
    local request = chilkat.JsonObject.new()
    request:update_string("location", location)
    request:update_string("kind", "StorageV2")
    request:update_string("sku.name", "Standard_LRS")
    request:update_string("properties.accessTier", "Hot")
    request:update_bool("properties.supportsHttpsTrafficOnly", true)
    request:update_string("properties.minimumTlsVersion", "TLS1_2")
    request:update_bool("properties.allowBlobPublicAccess", false)

    -- This PUT can UPDATE an existing account at this resource ID.
    -- Review the target and settings first. Creating storage can incur charges.
    success = http:http_json("PUT", resourceUrl, request, "application/json", response)
    -- If transport fails, inspect this resource before deciding to submit again;
    -- Azure may already have accepted the PUT.
    if response.status_code == 0 then
        print("No HTTP response. Inspect LastErrorText privately; it may contain credentials.")
        return
    end

    if (response.status_code ~= 200) and (response.status_code ~= 202) 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

    if response.status_code == 202 then
        -- An accepted operation can have an EMPTY body. Do not try to parse it.
        operationUrl = response:get_header_field("Azure-AsyncOperation")
        stringCompare:set_string(operationUrl)
        local stringMatch2 = stringCompare:contents_equal("", true)
        if not stringMatch2 then
            operationUsesStatus = true
        else
            operationUrl = response:get_header_field("Location")
        end

        stringCompare:set_string(operationUrl)
        local stringMatch3 = stringCompare:contents_equal("", true)
        if stringMatch3 then
            print("Accepted, but no monitor URL was returned. Check the resource; do not assume success.")
            return
        end

        retryAfter = response:get_header_field("Retry-After")
    end
end

stringCompare:set_string(operationUrl)
local stringMatch4 = stringCompare:contents_equal("", true)
if not stringMatch4 then
    success = parsed:parse_url(operationUrl)
    if not success then
        print("Missing or invalid continuation URL.")
        return
    end

    stringCompare:set_string(parsed.scheme)
    local stringMatch5 = stringCompare:contents_equal("https", true)
    stringCompare:set_string(parsed.host)
    local stringMatch6 = stringCompare:contents_equal("management.azure.com", true)
    stringCompare:set_string(parsed.login)
    local stringMatch7 = stringCompare:contents_equal("", true)
    stringCompare:set_string(parsed.password)
    local stringMatch8 = stringCompare:contents_equal("", true)
    stringCompare:set_string(parsed.frag)
    local stringMatch9 = stringCompare:contents_equal("", true)
    if (not stringMatch5) or ((not stringMatch6) or ((parsed.port ~= 443) or ((not stringMatch7) or ((not stringMatch8) or (not stringMatch9))))) then
        print("Unexpected continuation URL; refusing to send the access token.")
        return
    end

    print("Operation URL (save for resuming): " .. operationUrl)
    print("operationUsesStatus: " .. tostring(operationUsesStatus))
    local retryText = chilkat.StringBuilder.new()
    local retryNumber = chilkat.StringBuilder.new()
    local attempt = 0
    local complete = false
    while (attempt < 30) and (not complete) do
        -- Bound the example's polling. A desktop UI should schedule this work in
        -- the background. A production worker should persist the URL and next poll time.
        local waitSeconds = 5
        stringCompare:set_string(retryAfter)
        local stringMatch10 = stringCompare:contents_equal("", true)
        if not stringMatch10 then
            retryText:set_string(retryAfter)
            retryText:trim()
            waitSeconds = retryText.int_value
            retryNumber:clear()
            retryNumber:append_int(waitSeconds)
            if (not retryText:contents_equal(retryNumber:get_as_string(), true)) or ((waitSeconds < 0) or (waitSeconds > 60)) then
                -- Do not shorten a long server-requested delay. Save the operation
                -- URL above and resume later; an HTTP-date needs a scheduler too.
                print("Polling paused. Resume after Retry-After: " .. retryAfter)
                return
            end
        end

        if waitSeconds == 0 then
            waitSeconds = 1
        end

        http:sleep_ms(waitSeconds * 1000)
        success = http:http_no_body("GET", operationUrl, 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) and ((response.status_code ~= 202) and (response.status_code ~= 204)) 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

        attempt = attempt + 1
        retryAfter = response:get_header_field("Retry-After")
        if operationUsesStatus 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("status") ~= 1) or (result:string_of_equals("status", "", true)) then
                print("Expected a nonempty operation status.")
                return
            end

            if (result:string_of_equals("status", "Failed", true)) or (result:string_of_equals("status", "Canceled", true)) then
                print("Provisioning did not succeed: " .. result:string_of("status"))
                print("Error code: " .. result:string_of("error.code"))
                return
            end

            complete = result:string_of_equals("status", "Succeeded", true)
        else
            -- Location: 202 is still pending; 200/204 completes the monitor request.
            -- Get the resource below to confirm its provisioningState.
            complete = response.status_code ~= 202
        end
    end

    if not complete then
        print("Polling limit reached; provisioning may still be running.")
        print("Resume using the saved operation URL. Retry-After: " .. retryAfter)
        return
    end
end

-- Read the final resource for both immediate and asynchronous completion.
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

if not result:string_of_equals("properties.provisioningState", "Succeeded", true) then
    print("Account is not confirmed ready. Provisioning state: " .. result:string_of("properties.provisioningState"))
    -- If pending, GET this resource later; do not repeat PUT just to check status.
    return
end

if (result:json_type_of("id") ~= 1) or (result:string_of_equals("id", "", true)) then
    print("Expected the provisioned account's resource ID.")
    return
end

print("Storage account provisioning succeeded.")
print("Resource ID: " .. result:string_of("id"))
print("Name: " .. result:string_of("name"))
print("Blob endpoint: " .. result:string_of("properties.primaryEndpoints.blob"))
-- Provisioning success does not grant blob/file data access. Configure data-plane
-- roles and the account's network policy separately for the application that uses it.