Create an Azure Storage Account with JavaScript SDK

This guide will walk you through the process of programmatically creating an Azure Storage Account using the Azure SDK for JavaScript. This is a fundamental step for many cloud applications that require storage for blobs, queues, tables, and files.

Prerequisites

Step 1: Set up your Development Environment

1

Create a Project Directory and Initialize Node.js

Create a new directory for your project and initialize a Node.js project within it.

mkdir azure-storage-creator
cd azure-storage-creator
npm init -y
2

Install Azure SDK Packages

Install the necessary Azure SDK packages for managing storage accounts and authentication.

npm install @azure/arm-storage @azure/identity uuid

We're installing:

  • @azure/arm-storage: The Azure Resource Manager client library for managing Storage Accounts.
  • @azure/identity: Provides credential types for authenticating with Azure.
  • uuid: A library to generate unique identifiers for your storage account name.

Step 2: Authenticate with Azure

3

Configure Authentication

For programmatic access, it's recommended to use a Service Principal. You can create one using the Azure CLI:

az ad sp create-for-rbac --name "MyStorageCreatorSP" --role contributor --scopes /subscriptions/--your-subscription-id--

This command will output JSON containing the clientId, clientSecret, and tenantId. You'll need these for authentication. It's best practice to store these as environment variables rather than directly in your code.

Security Note: For production environments, consider using Azure Managed Identities or more secure secret management solutions like Azure Key Vault.

Step 3: Write the JavaScript Code

4

Create the Storage Account Creation Script

Create a file named createStorageAccount.js and add the following code. Remember to replace the placeholder environment variable names if you choose different ones.


import { StorageManagementClient } from "@azure/arm-storage";
import { DefaultAzureCredential } from "@azure/identity";
import { v4 as uuidv4 } from 'uuid';

async function createStorageAccount() {
    const subscriptionId = process.env.AZURE_SUBSCRIPTION_ID;
    if (!subscriptionId) {
        throw new Error("AZURE_SUBSCRIPTION_ID environment variable is not set.");
    }

    // Authenticate using environment variables for Service Principal or Managed Identity
    // The DefaultAzureCredential will automatically look for credentials in the environment
    // including AZURE_CLIENT_ID, AZURE_CLIENT_SECRET, AZURE_TENANT_ID
    const credential = new DefaultAzureCredential();

    const client = new StorageManagementClient(credential, subscriptionId);

    const resourceGroupName = "myResourceGroup"; // Replace with your desired resource group name
    const storageAccountName = `mystorageaccount${uuidv4().substring(0, 10)}`; // Unique storage account name
    const location = "eastus"; // Replace with your desired Azure region

    console.log(`Creating resource group: ${resourceGroupName}...`);
    try {
        await client.resourceGroups.createOrUpdate(resourceGroupName, { location: location });
        console.log(`Resource group "${resourceGroupName}" created or already exists.`);
    } catch (error) {
        console.error(`Error creating/updating resource group: ${error.message}`);
        // Decide if you want to stop or continue if RG creation fails
        throw error;
    }

    console.log(`Creating storage account: ${storageAccountName}...`);

    const createParams = {
        sku: {
            name: "Standard_LRS", // Options: Standard_LRS, Standard_GRS, Standard_RAGRS, Premium_LRS
            tier: "Standard" // Options: Standard, Premium
        },
        kind: "StorageV2", // Options: StorageV2, BlobStorage, Storage
        location: location,
        tags: {
            environment: "development",
            created_by: "javascript-sdk"
        }
    };

    try {
        const poller = await client.storageAccounts.beginCreate(resourceGroupName, storageAccountName, createParams);
        const result = await poller.pollUntilDone();
        console.log("Storage account created successfully:");
        console.log(`Name: ${result.name}`);
        console.log(`ID: ${result.id}`);
        console.log(`Primary Location: ${result.primaryLocation}`);
        console.log(`Provisioning State: ${result.provisioningState}`);
    } catch (error) {
        console.error(`Error creating storage account: ${error.message}`);
        throw error;
    }
}

createStorageAccount().catch(err => {
    console.error("An unexpected error occurred:", err);
    process.exit(1);
});
                    

Before running, set the following environment variables in your terminal:


export AZURE_SUBSCRIPTION_ID="YOUR_AZURE_SUBSCRIPTION_ID"
export AZURE_TENANT_ID="YOUR_AZURE_TENANT_ID"
export AZURE_CLIENT_ID="YOUR_CLIENT_ID"
export AZURE_CLIENT_SECRET="YOUR_CLIENT_SECRET"

Replace the placeholder values with your actual Azure subscription ID and the Service Principal credentials you obtained earlier.

Step 4: Run the Script

5

Execute the Node.js Script

Run the script from your terminal:

node createStorageAccount.js

If successful, you will see output indicating the resource group creation and then the successful creation of your Azure Storage Account, along with its details.

Understanding the Code

Customization and Next Steps

Remember to delete the created resources when they are no longer needed to avoid incurring costs. You can do this via the Azure Portal or using the Azure CLI: az group delete --name myResourceGroup --yes.