I needed to create a bunch of connection strings to use in my code. But this can be error prone and painful, especially if you have many data centers. In addition, you may decide to regenerate the primary storage key, in which case the whole nightmare would need to be repeated.

In my previous post, I illustrated how to provision a bunch of Azure storage accounts. So this post is a continuation from there to retrieve the primary storage keys. PowerShell syntax is really simple so it really doesn't require much explanation.

image001

Figure 1: Powershell output showing my connection strings

Now I can just past into my app.config file for my Visual Studio project.

image002

Figure 2: The Visual Studio solution that will use my connection string

image003

Figure 3: Updated App.config file

Getting Storage Account Keys
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

# A list of storage account names
$DataCenterList = @(
            ,@("terkalysoutheastasia", "Southeast Asia")
            ,@("terkalyenortheurope", "North Europe")
            ,@("terkalyeastus", "East US")
            ,@("terkalywestus", "West US")
            ,@("terkalyjapaneast", "Japan East")
            ,@("terkalycentralus", "Central US")
        )

# Loop through the storage accounts and get the primary storage key
ForEach($DC in $DataCenterList) {


    Start-Sleep -s 1

    # get the storage key using the storage account name
     $myStoreKey = (Get-AzureStorageKey –StorageAccountName $DC[0]).Primary
    $part1 = """;
    $part2 = """"
    $part3 = " value=""DefaultEndpointsProtocol=https;AccountName=";
    $part4 = ";AccountKey=";
    $part5 = """/>";
    # the connection string name is the same as the storage account anem
    Write-Host($part1 + $DC[0] + $part2 + $part3 + $DC[0] + $part4 + $myStoreKey + $part5);
  
}