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.
az login.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
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.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.
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.
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.
DefaultAzureCredential attempts to authenticate using various methods, including environment variables, managed identity, and Azure CLI. This makes it flexible for different deployment scenarios.StorageManagementClient is created, which will be used to interact with Azure Storage resource management APIs.sku: Specifies the performance tier and replication strategy (e.g., Standard_LRS for Standard performance with Locally Redundant Storage).kind: The type of storage account (e.g., StorageV2 for general-purpose v2, which supports blobs, files, queues, and tables).location: The Azure region where the storage account will be created.tags: Metadata to help organize your Azure resources.client.storageAccounts.beginCreate initiates the creation process. This is an asynchronous operation that returns a poller object. poller.pollUntilDone() waits for the creation to complete.sku and kind options based on your application's performance and availability needs.listKeys).az group delete --name myResourceGroup --yes.