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

Azure Storage Accounts: Retrieve and Optionally Rotate a Storage Account Key

See more Azure Storage Accounts Examples

Uses List Keys to retrieve an account key, or regenerates only key1 when rotateKey=true. Saves only the selected secret to a private file and never prints it. The caller needs List Keys permission and, for rotation, Regenerate Key permission.

Regeneration immediately invalidates the old key and SAS signatures derived from it. First migrate all dependent clients to the other key; regenerate the unused key, distribute its new value securely, and only later consider rotating the other key. Do not regenerate both together. A failed local save does not undo rotation; recover using List Keys. Prefer Entra authentication where supported. See account key management.

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 keysUrl = "https://management.azure.com/subscriptions/{$subscriptionId}/resourceGroups/{$resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{$accountName}/listKeys?api-version=2026-09-01"

success = http:http_no_body("POST", keysUrl, 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 result:json_type_of("keys") ~= 4 then
    print("Missing or invalid keys.")
    return
end

-- Move all clients and key-signed SAS dependencies away from key1 BEFORE rotating it.
-- This example retrieves key1, then optionally regenerates key1 only.
local keyName = "key1"
local rotateKey = false
if rotateKey then
    local request = chilkat.JsonObject.new()
    request:update_string("keyName", keyName)
    success = http:http_json("POST", "https://management.azure.com/subscriptions/{$subscriptionId}/resourceGroups/{$resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{$accountName}/regenerateKey?api-version=2026-09-01", request, "application/json", response)

    -- Do not retry regeneration after an uncertain transport result: list keys
    -- to recover the current value. Repeating regeneration invalidates it again.
    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 result:json_type_of("keys") ~= 4 then
        print("Missing or invalid keys.")
        return
    end
end

local keys = chilkat.JsonArray.new()
success = result:array_of2("keys", keys)
if not success then
    print("Could not read returned keys.")
    return
end

local key = chilkat.JsonObject.new()
local privateKey = chilkat.JsonObject.new()
local found = false
local i = 0
while i < keys.size do
    success = keys:object_at2(i, key)
    if not success then
        print("Invalid key entry.")
        return
    end

    if key:string_of_equals("keyName", keyName, true) then
        if (key:json_type_of("value") ~= 1) or (key:string_of_equals("value", "", true)) then
            print("Selected key has no value. Inspect permissions privately.")
            return
        end

        privateKey:update_string("account_name", accountName)
        privateKey:update_string("key_name", keyName)
        privateKey:update_string("access_key", key:string_of("value"))
        found = true
    end

    i = i + 1
end

if not found then
    print("Selected key was not returned.")
    return
end

-- Pre-create this private directory with restrictive OS permissions. This file
-- contains an account-wide secret; never commit it or put it in web content.
success = privateKey:write_file("qa_data/azure/storage-key.json")
if not success then
    print("Could not save key privately. If rotated, use List Keys to recover; do not regenerate again.")
    return
end

print("Selected key saved privately. Key name: " .. keyName)
print("Key regeneration requested: " .. tostring(rotateKey))
-- Distribute the current key through your application's secret-management process.
-- Rotate the other key in a separate maintenance step after clients are migrated.