You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何部署N个存储账户并遍历输出其连接字符串?

How to Deploy Multiple Storage Accounts and Output Their Connection Strings

Hey there! I’ve tackled this exact scenario a bunch of times when setting up Azure storage accounts at scale, so let me walk you through the most practical approaches depending on your deployment tooling.

If you’re using Bicep (Azure’s modern IaC language) or ARM templates, you can generate and output the connection strings right during deployment—no post-deployment steps needed.

Bicep Example

First, define your storage account names as an array parameter, loop to create them, then map each account to its connection string:

// Define the list of storage account names (customize this!)
param storageAccountNames array = ['sa-prod-001', 'sa-prod-002', 'sa-prod-003']
param location string = resourceGroup().location

// Create storage accounts in a loop
resource storageAccounts 'Microsoft.Storage/storageAccounts@2023-01-01' = [for name in storageAccountNames: {
  name: name
  location: location
  sku: {
    name: 'Standard_LRS'
  }
  kind: 'StorageV2'
}]

// Output as an array of connection strings (with account names for clarity)
output storageConnectionStringsArray array = [for sa in storageAccounts: {
  accountName: sa.name
  connectionString: "DefaultEndpointsProtocol=https;AccountName=${sa.name};AccountKey=${listKeys(sa.id, sa.apiVersion).keys[0].value};EndpointSuffix=${environment().suffixes.storage}"
}]

// Output as a comma-separated string (for easy copy-pasting into configs)
output storageConnectionStringsCommaSeparated string = join(',', [for sa in storageAccounts: "DefaultEndpointsProtocol=https;AccountName=${sa.name};AccountKey=${listKeys(sa.id, sa.apiVersion).keys[0].value};EndpointSuffix=${environment().suffixes.storage}"])

Note: Make sure your deployment identity has the Microsoft.Storage/storageAccounts/listKeys/action permission on the storage accounts or resource group.

ARM Template Example

For ARM templates, use the copy loop to create accounts, then use copy in the outputs section to build your list:

{
  "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {
    "storageAccountNames": {
      "type": "array",
      "defaultValue": ["sa-prod-001", "sa-prod-002", "sa-prod-003"]
    },
    "location": {
      "type": "string",
      "defaultValue": "[resourceGroup().location]"
    }
  },
  "resources": [
    {
      "type": "Microsoft.Storage/storageAccounts",
      "apiVersion": "2023-01-01",
      "name": "[parameters('storageAccountNames')[copyIndex()]]",
      "location": "[parameters('location')]",
      "sku": {
        "name": "Standard_LRS"
      },
      "kind": "StorageV2",
      "copy": {
        "name": "storageAccountCopy",
        "count": "[length(parameters('storageAccountNames'))]"
      }
    }
  ],
  "outputs": {
    "storageConnectionStringsArray": {
      "type": "array",
      "copy": {
        "count": "[length(parameters('storageAccountNames'))]",
        "input": {
          "accountName": "[parameters('storageAccountNames')[copyIndex()]]",
          "connectionString": "[concat('DefaultEndpointsProtocol=https;AccountName=', parameters('storageAccountNames')[copyIndex()], ';AccountKey=', listKeys(resourceId('Microsoft.Storage/storageAccounts', parameters('storageAccountNames')[copyIndex()]), '2023-01-01').keys[0].value, ';EndpointSuffix=', environment().suffixes.storage)]"
        }
      }
    },
    "storageConnectionStringsCommaSeparated": {
      "type": "string",
      "value": "[join(',', copyArray(outputs('storageConnectionStringsArray').value))]"
    }
  }
}

Option 2: Extract Connection Strings Post-Deployment (CLI/PowerShell)

If you already deployed the storage accounts and just need to pull their connection strings, use Azure CLI or PowerShell to iterate through them.

Azure CLI

Run these commands to get a comma-separated string of connection strings for all accounts in a resource group:

# Replace YOUR-RG-NAME with your resource group name
SA_NAMES=$(az storage account list --resource-group YOUR-RG-NAME --query "[].name" -o tsv)

# Collect and join connection strings
CONNECTION_STRINGS=$(for SA in $SA_NAMES; do az storage account show-connection-string --name $SA --resource-group YOUR-RG-NAME --query connectionString -o tsv; done | tr '\n' ',' | sed 's/,$//')

# Print the final result
echo $CONNECTION_STRINGS

PowerShell

For PowerShell users, this will give you both an array and a comma-separated string:

# Replace YOUR-RG-NAME with your resource group name
$storageAccounts = Get-AzStorageAccount -ResourceGroupName YOUR-RG-NAME

# Extract connection strings into an array
$connectionStringsArray = $storageAccounts | ForEach-Object { $_.Context.ConnectionString }

# Convert to a comma-separated string
$connectionStringsCommaSeparated = $connectionStringsArray -join ','

# Output both formats
Write-Host "Array of connection strings:"
$connectionStringsArray
Write-Host "`nComma-separated string:"
$connectionStringsCommaSeparated

Key Notes

  • Permissions: Whichever method you use, your identity needs permissions to read storage account keys—Storage Account Key Operator Service Role is a built-in role that works perfectly for this.
  • Security: Connection strings contain sensitive account keys, so avoid logging them or sharing them publicly. Consider storing them in Azure Key Vault instead of using plaintext outputs.

内容的提问来源于stack exchange,提问作者Andrei

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 07:48:25