Archive

Posts Tagged ‘Windows Azure PowerShell CmdLets’

Windows Azure PowerShell Cmdlets 2.2.2 Release

March 12, 2012 1 comment


Windows Azure PowerShell Cmdlets (v2.2.2)

We have a brand new release of the Windows Azure PowerShell cmdlets that we hope
will make getting started and scripting with the cmdlets a much easier task.

The new release can be downloaded from its CodePlex project site 
here.

Getting Started Improvements

In 2.2.2 we have added a start menu link that starts a PowerShell session with
the Windows Azure cmdlets already loaded. We have also added a Start Here link
that shows how to complete the setup and a short tour about the capabilities of
the Windows Azure PowerShell cmdlets and release changes.

Subscription Management Improvements

We have taken the
subscription management improvements from the 2.2 release and made them much
better.
Specifically, we have added the ability to persist your subscription settings
into your user profile. This functionality allows you to set the subscription
data once and then in new scripts or PowerShell sessions just select the
subscription you want to use without the need to specify the subscription ID,
Certificate and storage accounts each time.

Code Snippet One: Setting Subscription Data

      $subid = "{subscription id}"
     $cert = Get-Item cert:\CurrentUser\My\CERTTHUMBPRINTUPPERCASE

     # Persisting Subscription Setings
     Set-Subscription -SubscriptionName org-sub1 -Certificate $cert -SubscriptionId $subid

     # Setting the current subscription to use 
     Select-Subscription -SubscriptionName org-sub1 
    

Calling the Set-Subscription cmdlet with your certificate
and subscription ID. Set-Subscription will persist the certificate thumbprint
and subscription id to (C:\Users\{username}\AppData\Roaming\Windows Azure
PowerShell Cmdlets\DefaultSubscriptionData.xml) associated with the subscription name.

This functionality supports adding multiple subscriptions to your configuration
so you can manage each individually within the same script simply by calling
Select-Subscription with the subscription name.

Code Snippet Two: Setting the Default Subscription

        Set-Subscription -DefaultSubscription org-sub1
    

Snippet two demonstrates setting the default subscription to use if you do not set one with Select-Subscription.

Code Snippet Three: Associating Storage Accounts with your Subscription

     # Save the cert and subscriptio id for two subscriptions
     Set-Subscription -SubscriptionName org-sub1 -StorageAccountName mystoragename1 -StorageAccountKey mystoragekey1
     Set-Subscription -SubscriptionName org-sub1 -StorageAccountName mystoragename2 -StorageAccountKey mystoragekey2

     # Specify the default storage account to use for the subscription
     Set-Subscription -SubscriptionName org-sub1 -DefaultStorageAccount mystoragename1
    

Snippet three shows that you can associate multiple storage accounts with a single subscription. All it takes to use the correct storage account is to set the default before calling a cmdlet that requires a storage account.

Code Snippet Four: Specifying the Subscription Data File Location

       # Overriding the default location to save subscription settings
       Set-Subscription -SubscriptionName org-sub1 -Certificate $cert -SubscriptionId $subid -SubscriptionDataFile c:\mysubs.xml

       # Retrieving a list of subscriptions from an alternate location
       Get-Subscription -SubscriptionDataFile c:\mysubs.xml
    

Each of th subscription cmdlets take a -SubscriptionDataFile parameter that allows you to specify which XML file to use for operations.

Code Snippet Five: MISC Subscription Management

        # Returns all persisted settings 
       Get-Subscription

       # Removes mysub2 from persisted settings
       Remove-Subscription -SubscriptionName org-sub2

       # Removing a storage account from your persisted subscription settings
       Set-Subscription -SubscriptionName org-sub1 -RemoveStorageAccount mystoragename1
    

Other Usability Improvements

We have made many of the cmdlets simpler to use by allowing more parameters to
be optional with default values.

  • -Label parameter is now optional in New-AffinityGroup, Set-AffinityGroup, New-HostedService, New-StorageAccount, New-Deployment and Update-Deployment.
  • -Slot parameter is now optional in New-Deployment and Update-Deployment (Production slot is used by default).
  • -Name parameter is now optional in New-Deployment (a Globally Unique Identifier value is used by default).

In addition to the defaults we provided some needed fixes to unblock certain scenarios.

  • Get-Deployment now returns $null if no deployment was found in the specified slot (an error was thrown in previous versions).
  • -Package and -Configuration parameters now accept UNC paths in New-Deployment and Update-Deployment.

Breaking Changes

With improvements like these we did have to make some sacrifices.
Before you download the latest build please review the list below because we have a few breaking changes.

  • -DefaultStorageAccountName and -DefaultStorageAccountKey parameters were removed from Set-Subscription. Instead, when adding multiple accounts to a subscription, each one needs to be added with -StorageAccountName and -StorageAccountKey or -ConnectionString. To set a default storage account, use Set-Subscription –DefaultStorageAccount {account name}.
  • -SubscriptionName is now mandatory in Set-Subscription.
  • In previous releases, the subscription data was not persisted between PowerShell sessions. When importing subscription settings from a publishsettings file downloaded from the management portal, the Import-Subscription cmdlet optionally saved the subscription information to a file that could then be restored using Set-Subscription thereafter. This behavior has changed. Now, imported subscription data is always persisted to the subscription data file and is immediately available in subsequent sessions. Set-Subscription can be used to update these subscription settings or to create additional subscription data sets.
  • Renamed -CertificateToDeploy parameter to -CertToDeploy in Add-Certificate.
  • Renamed -ServiceName parameter to -StorageAccountName in all Storage Service cmdlets (added “ServiceName” as a parameter alias for backward compatibility).

Summary

In the 2.2.2 release we have made a number of fixes such as accepting UNC paths and fixing Get-Deployment to not throw an error on empty slots. We have also substantially improved the getting started experience and how you can manage your Windows Azure subscriptions from PowerShell.

The new release can be downloaded from http://wappowershell.codeplex.com.

Windows Azure PowerShell Cmdlets 2.2 Released

January 16, 2012 Leave a comment


Windows Azure PowerShell Cmdlets (v2.2)

Download the Latest Release

We have a brand new release of the Windows Azure PowerShell cmdlets that we hope will open up new opportunities to automate and manage your Windows Azure deployments along with just making your life easier as a PowerShell user. So what is new? Let’s take a look!

Scripting Usability Improvements

If you have used the cmdlets for any amount of time one thing that has likely annoyed you is the requirement to pass -SubscriptionID, -Certificate, -StorageAccountName and -StorageAccountKey around to almost every cmdlet. This design made it almost impossible to use from a command shell and only lended itself to easily being used from a script.

We have introduced three new cmdlets to make your life easier in this respect:

  • Import-Subscription
  • Set-Subscription
  • Select-Subscription

Set-Subscription and Select-Subscription

Set/Select Subscription allows you to specify the SubscriptionID, Certificate, DefaultStorageAccountName and DefaultStorageAccountKey and save them in session state. What this means is once you call these cmdlets you do not need to pass those arguments to every cmdlet any more. They will just use the data from session state and save you a  ton of typing. These cmdlets do support multiple subscriptions. Just call Set-Subscription once for each subscription you need to use and then call Select-Subscription to set the current subscription.

One thing that is important is using Set/Select-Subscription should be used mutually exclusive from passing the same data as parameters. In some cases it may work fine and in others you may get strange errors about -SubscriptionID or -Certificate not being known parameters.

Example:

     $cert = Get-Item cert:\CurrentUser\My\{your cert thumbprint}
    Set-Subscription -SubscriptionName "mysub" -SubscriptionId {your subscription id} `
                     -Certificate $cert `
                     -DefaultStorageAccountName "{your storage account}" `
                     -DefaultStorageAccountKey "{your storage key}"

    Select-Subscription -SubscriptionName "mysub"
    Get-HostedService -ServiceName "myService"
    

Import-Subscription

Import-Subscription allows you to import a .publishingsettings file that was previously downloaded from: https://windows.azure.com/download/publishprofile.aspx?wa=wsignin1.0.

This cmdlet adds the embedded management certificate into your local certificate store and saves an xml file that the cmdlets can use to automatically import the subcription information into your PowerShell session.

Used in conjunction with the new Set-Subscription and Select-Subscription cmdlets it makes for an easy way to get setup for the first time without having to deal with manually creating/importing the management certificates.
An example:

     Import-Subscription -PublishSettingsFile "C:\WindowsAzure\Field_ mwasham-1-15-2012-credentials.publishsettings" `
                        -SubscriptionDataFile "c:\WindowsAzure\mysub.xml"

    Set-Subscription -SubscriptionName "mysub" -SubscriptionDataFile "c:\WindowsAzure\mysub.xml" `
                     -DefaultStorageAccountName "{your storage account}" `
                     -DefaultStorageAccountKey "{your storage key}"

    Select-Subscription -SubscriptionName "mysub"
    

Windows Azure Traffic Manager Support

We’ve added the ability to fully manage and customize your deployments that use Windows Azure Traffic Manager.

Windows Azure Traffic Manager Cmdlets

  • New-TrafficManagerProfile
  • Get-TrafficManagerProfile
  • Remove-TrafficManagerProfile
  • Set-TrafficManagerProfile
  • Get-TrafficManagerDefinition
  • New-TrafficManagerDefinition
  • Add-TrafficManagerEndpoint
  • New-TrafficManagerEndpoint
  • Set-TrafficManagerEndpoint
  • Remove-TrafficManagerEndpoint
  • New-TrafficManagerMonitor

Here is an example of how you can use PowerShell to create a new profile and definition:

    # Create new Traffic Manager Profile
    New-TrafficManagerProfile -DomainName "woodgrove.trafficmanager.net" `
                              -ProfileName "ProfileFromPS"

    # Specify the monitor settings
    $monitors = @()
    $monitor = New-TrafficManagerMonitor -RelativePath "/" -Port 80 -Protocol http
    $monitors += $monitor

    # Create an array to hold the Traffic Manager Endpoints
    $endpoints = @()

    # Specify the endpoint for our North Central US application
    $endpoint1 = New-TrafficManagerEndpoint -DomainName "WoodGroveUS.cloudapp.net"
    $endpoints += $endpoint1

    # Specify the endpoint for our North Europe application
    $endpoint2 = New-TrafficManagerEndpoint -DomainName "WoodGroveEU.cloudapp.net"
    $endpoints += $endpoint2

    # Create the definition by passing in the monitor, endpoints and other settings.
    # -Status enabled automatically enables the profile with the new definition as the active one.
    $newDef = New-TrafficManagerDefinition -ProfileName "ProfilefromPS" `
					    -TimeToLiveInSeconds 300 -LoadBalancingMethod Performance `
					    -Monitors $monitors -Endpoints $endpoints -Status Enabled
    # Set the active profile version & enable
    Set-TrafficManagerProfile -ProfileName "ProfilefromPS" -Enable `
   		           -DefinitionVersion $newDef.Version
    

New-SqlAzureFirewallRule -UseIpAddressDetection

This cmdlet is not new however the -UseIpAddressDetection parameter is. It was actually released in a 2.1 release that wasn’t highly publicized. The -UseIpAddressDetection parameter allows you to add a firewall rule whether you know your external IP address or not. Perfect for getting up and running quickly in a new environment.

Here is an example of using -UseIpAddressDetection:

    New-SqlAzureFirewallRule -ServerName "{server name}" `
			    -UseIpAddressDetection `
			    -RuleName "testautodetect"
    

Set-RoleInstanceCount

This cmdlet is new and allows you to specify the number of instances for a given role. We’ve always had the ability to increment or decrement the number of instances but it wasn’t nearly as easy.

Here is an example that sets the instance count for myWebRole to 4.

    Get-HostedService -ServiceName "WoodGroveUS" | `
				  Get-Deployment -Slot Production | `
				  Set-RoleInstanceCount -Count 4 -RoleName "myWebRole"
    

New-PerformanceCounter

This cmdlet is new and just wraps the creation of perfmon counters for setting diagnostics. It makes your life easier when dealing with logging :)

Here is an example of adding some perfmon counters:

    function GetDiagRoles {
         Get-HostedService -ServiceName $serviceName | `
                         Get-Deployment -Slot $deploymentslot | `
                         Get-DiagnosticAwareRoles
    }
    $counters = @()
    $counters += New-PerformanceCounter -SampleRateSeconds 10 `
			    -CounterSpecifier "\Processor(_Total)\% Processor Time"

    $counters += New-PerformanceCounter -SampleRateSeconds 10 `
			    -CounterSpecifier "\Memory\Available MBytes"

    GetDiagRoles | foreach {
	    $_ | Set-PerformanceCounter -PerformanceCounters $counters -TransferPeriod 15
    }
    

Get-PerfmonLog <breaking change>

This cmdlet was introduced in the 2.0 release of the cmdlets. Some of our awesome field folks determined that it was not capturing perfmon counters correctly when there were multiple instances of a role being monitored. We have fixed this bug and it now appears to be capturing all of the relevant data. The problem is this is a breaking change. So if you are currently using this cmdlet your script will need to be updated. Thankfully, the script change is a minor one. Instead of taking a file name for -LocalPath it now takes a directory. Each instance being monitored will now get its own .blg or .csv file.

Example that uses a helper function called GetDiagRoles to download the perfmon logs.

    function GetDiagRoles {
         Get-HostedService -ServiceName $serviceName | `
                         Get-Deployment -Slot $deploymentslot | `
                         Get-DiagnosticAwareRoles
    }
    GetDiagRoles | foreach {
	$_ | Get-PerfmonLog -LocalPath "c:\DiagData" -Format CSV
    }
    

In addition to these improvements we have actually made quite a few other more minor improvements. One key request is to make a binary installation so you aren’t required to build the cmdlets before using them. That was a key priority for us and we made this happen in 2.2. Additionally, take a look at the Readme.docx in the new release for further details about other improvements.

Windows Azure Storage Analytics with PowerShell

September 28, 2011 Leave a comment

Windows Azure Storage Analytics allows you to log very detailed information about how a storage account is being used. Each service (Blob/Table/Queues) has independant settings allowing you to have granular control over what data is collected. To enable/disable each setting just add or omit the argument (-LoggingDelete as an example). One of the great things about this service is the ability to set a retention policy so the data can be automatically deleted after a set number of days.

Enabling Storage Analytics per Service

Set-StorageServicePropertiesForAnalytics -ServiceName "Table" `
		-StorageAccountName $storageAccount -StorageAccountKey $storagekey `
		-LoggingDelete -LoggingRead -LoggingWrite -MetricsEnabled -MetricsIncludeApis `
		-MetricsRetentionPolicyDays 5 -LoggingRetentionPolicyEnabled -LoggingRetentionPolicyDays 5 `
		-MetricsRetentionPolicyEnabled 
									
Set-StorageServicePropertiesForAnalytics -ServiceName "Queue" `
		-StorageAccountName $storageAccount -StorageAccountKey $storagekey `
		-LoggingDelete -LoggingRead -LoggingWrite -MetricsEnabled -MetricsIncludeApis `
		-MetricsRetentionPolicyDays 5 -LoggingRetentionPolicyEnabled -LoggingRetentionPolicyDays 5 `
		-MetricsRetentionPolicyEnabled 
									
Set-StorageServicePropertiesForAnalytics -ServiceName "Blob" `
		-StorageAccountName $storageAccount -StorageAccountKey $storagekey `
		-LoggingDelete -LoggingRead -LoggingWrite -MetricsEnabled -MetricsIncludeApis `
		-MetricsRetentionPolicyDays 5 -LoggingRetentionPolicyEnabled -LoggingRetentionPolicyDays 5 `
		-MetricsRetentionPolicyEnabled 		

Retrieving the Current Storage Analytics Settings

	Get-StorageServicePropertiesForAnalytics -ServiceName "Table" `
		-StorageAccountName $storageAccount -StorageAccountKey $storagekey | Format-List
	
	Get-StorageServicePropertiesForAnalytics -ServiceName "Blob" `
		-StorageAccountName $storageAccount -StorageAccountKey $storagekey | Format-List
		
	Get-StorageServicePropertiesForAnalytics -ServiceName "Queue" `
		-StorageAccountName $storageAccount -StorageAccountKey $storagekey | Format-List

Downloading the storage analytics data requires a bit more explanation. Each service has two fundamental types of data (except blob storage which has 3). The two are log data which contains all of the requests for that service (depending on which settings you have enabled) and transactions. Transactions contains numerous metrics that give you a deep understanding of how the storage service is performing. Metrics such as % Success or Avg E2E Latency are extremely useful for understanding your application. Blob storage also has a “Capacity” set of data that will tell you how much storage space blob storage is using broken down by analytics and application data.

Downloading Storage Analytics Data

Get-StorageAnalyticsLogs -ServiceName "Blob" `
	-LocalPath "c:\DiagData\SALogsBlob.log"  `
	-StorageAccountName $storageAccount -StorageAccountKey $storagekey  

Get-StorageAnalyticsMetrics -DataType "Capacity" -ServiceName "Blob" `
    -LocalPath "c:\DiagData\SAMetricsBlob-Capacity.log" `
    -StorageAccountName $storageAccount -StorageAccountKey $storagekey 
						 
Get-StorageAnalyticsMetrics -DataType "Transactions" -ServiceName "Blob" `
	-LocalPath "c:\DiagData\SAMetricsBlob-Transactions.log" `
	-StorageAccountName $storageAccount -StorageAccountKey $storagekey 

Get-StorageAnalyticsLogs -ServiceName "Table" `
	-LocalPath "c:\DiagData\SALogsTable.log"  `
	-StorageAccountName $storageAccount -StorageAccountKey $storagekey  
						 
Get-StorageAnalyticsMetrics -DataType "Transactions" -ServiceName "Table" `
	-LocalPath "c:\DiagData\SAMetricsTable-Transactions.log" `
	-StorageAccountName $storageAccount -StorageAccountKey $storagekey 

Get-StorageAnalyticsLogs -ServiceName "Queue" `
	-LocalPath "c:\DiagData\SALogsQueue.log" `
	-StorageAccountName $storageAccount -StorageAccountKey $storagekey  
						 
Get-StorageAnalyticsMetrics -DataType "Transactions" -ServiceName "Queue" `
	-LocalPath "c:\DiagData\SAMetricsQueue-Transactions.log" `
	-StorageAccountName $storageAccount -StorageAccountKey $storagekey 

For more information on storage analytics and details on understanding the metrics you can use see the following:
http://msdn.microsoft.com/en-us/library/windowsazure/hh343268.aspx

Resetting the Passwords on all of Your SQL Azure Servers

September 28, 2011 Leave a comment

Managing the passwords of your SQL Azure servers is now 100% scriptable. It’s so easy to reset them it’s almost like magic :)
The code below takes your subscription id and your management certificate and returns all of the SQL Azure servers in your subscription. It takes that collection and passes them to the Set-SqlAzurePassword Cmdlet along with the new password.

Resetting the Passwords of all SQL Azure Servers in your Subscription

$subscriptionId = "Your-ID-Goes-Here"
$cert = Get-Item cert:\CurrentUser\My\YOURCERTTHUMBPRINTGOESHERE
Get-SqlAzureServer -Certificate $cert -SubscriptionId $subscriptionid | `
	Set-SqlAzurePassword -NewPassword "abracadabra0!"

Windows Azure PowerShell Cmdlets 2.0 Update Web Cast Now Available

September 27, 2011 Leave a comment

Windows Azure PowerShell Cmdlets 2.0 Update Web Cast Now Available

Image

Creating a new SQL Azure Server and Firewall Rule with PowerShell

September 27, 2011 Leave a comment

Creating SQL Azure Servers and Configuring firewall rules is surprisingly easy with the new Windows Azure PowerShell Cmdlets 2.0.

Step 1: Add the WAPPSCmdlets Snapin or Module

Add-PsSnapin WAPPSCmdlets

Step 2: Create a Few Needed Variables

$subscriptionid = "your subscription id"
$cert = Get-Item cert:\CurrentUser\My\yourcertthumbprint
$adminLogin = "sqlAzureLogin"
$adminPassword = "sqlAzurePassword"

Step 3: Call the Cmdlets With Your Variables

$newServer = New-SqlAzureServer -AdministratorLogin $adminLogin -AdministratorLoginPassword $adminPassword `
			       -Location "North Central US" -Certificate $cert `
				   -SubscriptionId $subscriptionid

$newServer | New-SqlAzureFirewallRule -RuleName "EveryBody" `
			-StartIpAddress "0.0.0.0" -EndIpAddress "255.255.255.255"

Obviously, you would want to change the firewall rule if you did not want EVERY IP address to be able to connect to your server but you get the idea.

Updating SQL Azure Firewall Rules with Windows Azure PowerShell Cmdlets 2.0

September 27, 2011 2 comments

You’ve deployed a few Sql Azure servers and through no fault of your own the requirement comes up to update all of the firewall rules for each of the Sql Azure Servers.

No Problem!

Adding new SQL Azure Firewall Rules

Get-SqlAzureServer -Certificate $cert -SubscriptionId $subscriptionid | foreach {
  $_ | New-SqlAzureFirewallRule -RuleName "NewRule1" -StartIpAddress "0.0.0.0" -EndIpAddress "1.1.2.2"
  $_ | New-SqlAzureFirewallRule -RuleName "NewRule2" -StartIpAddress "100.1.0.0" -EndIpAddress "100.15.0.0"
}

Removing Rules is Just as Easy

Get-SqlAzureServer -Certificate $cert -SubscriptionId $subscriptionid | foreach {
  $_ | Remove-SqlAzureFirewallRule -RuleName "OldRule1"
  $_ | Remove-SqlAzureFirewallRule -RuleName "OldRule2"
}

This of course requires the Windows Azure PowerShell Cmdlets 2.0

Automate It! Deploying a Windows Azure Service Package from PowerShell.

September 21, 2011 Leave a comment

With the new version of Windows Azure PowerShell Cmdlets 2.0 we have made it possible to script the deployment of an entire hosted service directly from PowerShell!

As a proof of concept we have put together a sample script that reads settings from a configuration file and deploys a service package to your Windows Azure Account. What is new about this is if the hosted service or storage account do not exist yet we will create them using the settings you specify!

To get started ensure you have downloaded and installed the Windows Azure PowerShell Cmdlets 2.0.

Next download the sample script from here: https://mlwpublic.blob.core.windows.net/downloads/e2e-ps-deployment.zip

Once the file is unzipped you will need to modify the configuration.xml file with your own settings:

Image

Once configured copy your .cspkg file and .cscfg file to the \deploymentPackage folder beneath the script.

Finally, run the deploy.cmd file which will launch your PowerShell script and deploy the service!

Image

Operations demonstrated in this sample include:

  • New-HostedService / Get-HostedService
  • New-StorageAccount / Get-StorageAccount
  • New-Deployment / Get-Deployment
  • Add-Certificate
  • Move-Deployment (VIP Swap)

Managing Log Files with Windows Azure PowerShell Cmdlets 2.0

September 20, 2011 Leave a comment

This is part 5 of a series:

In this example I’m going to show you how you can manage log data from your Windows Azure Application using new functionality in the Windows Azure PowerShell Cmdlets 2.0.

Just as in the other articles you will need to add the PowerShell Snapin (or module):

 
  Add-PsSnapin WAPPSCmdlets 

Ditto, I have this handy initialization block and helper function GetDiagRoles:

Initialization and Helper Function

 

 $storageAccountName = "YourStorageAccountName" 
 $storageAccountKey = "YourStorageAccountKey" 
 $deploymentSlot = "Production" 
 $serviceName = "YourHostedService" 
 $subscriptionId = "YourSubscriptionId" 
 # Thumbprint for your cert goes below
 $mgmtCert = Get-Item cert:\CurrentUser\My\D7BECD4D63EBAF86023BB4F1A5FBF5C2C924902A 
 

 function GetDiagRoles { 
   Get-HostedService -ServiceName $serviceName -SubscriptionId $subscriptionId -Certificate $cert | ` 
   Get-Deployment -Slot $deploymentslot | ` 
   Get-DiagnosticAwareRoles -StorageAccountName $storageAccount -StorageAccountKey $storageKey 
 }
 

What is distinct about managing log files remotely in Windows Azure is determining where on the file system the log files actually are.

I’ve written some samples that show some techniques you can use from PowerShell for determining file locations.

When determining the local path for a named local resource I’m using guidance from MSDN: http://msdn.microsoft.com/en-us/library/ee758708.aspx.

For the rest of the log paths I am essentially just using observations of how the paths are constructed. At this point there is no guarantee this format will change but for the time being it doesn’t look too likely.

Returns the Local Path for IIS Logs

 
function GetIISLogsPath()
{
 $input | foreach { 
  $path = "C:\Resources\Directory\" + $_.DeploymentId + "." + $_.RoleName + ".DiagnosticStore\LogFiles"
  return $path
 }
}

Returns the Local Path for IIS Failed Request Logs

 
function GetIISFailedRequestPath()
{
 $input | foreach {
  $path = "C:\Resources\Directory\" + $_.DeploymentId + "." + $_.RoleName + ".DiagnosticStore\FailedReqLogFiles"
  return $path
 }
}

Returns the Local Path for Crash Dumps

 
function GetCrashDumpsPath($rolename, $deploymentid)
{
 $input | foreach {
  $path = "C:\Resources\Directory\" + $_ + "." + $_ + ".DiagnosticStore\Crashdumps"
  return $path
 }
}

Returns the Local Path for a Named Local Resource

 
function GetLocalResourcePath($localResource)
{
 $input | foreach {
  $path = "C:\Resources\directory\" + $_.DeploymentId + "." + $_.RoleName + "." + $localResource
  return $path
 }
}

Now that we have some helper functions to figure out where are logs are in our Windows Azure Deployment we need a method of modifying the logging data sources in Windows Azure Diagnostics.
The long function below does just that. It takes the local path of the files you want to transfer, what container in Windows Azure Storage to transfer the files to, a quota (can be set to 0) and how often to transfer that directory to storage in minutes.

Configures a local directory in a Windows Azure role to be transferred into Windows Azure Storage.

 
function SetDirectory($path, $container, $quota, $transferAllInMinutes)
{
  $input | foreach { 
    $role = $_ 
    $role | Get-DiagnosticAwareRoleInstances  |
      foreach {
          $roleinstance = $_
          $diagConfig = $role | Get-DiagnosticConfiguration -InstanceId $roleinstance -BufferName Directories
          $existingDirectory = $false
          $newDirectoryConfig = $null
          for($i=0;$i -lt $diagConfig.DataSources.Count; $i++)
          {
             $tmpDiag = $diagConfig.DataSources[$i]
             if($tmpDiag.Path -eq $path)
             {
                $existingDirectory = $true
                $newDirectoryConfig = $diagConfig.DataSources[$i]
                break
             }
          }

          # doesn't already exist in the collection so create a new one
          if($existingDirectory -eq $false) 
          {
            $newDirectoryConfig = New-Object -TypeName Microsoft.WindowsAzure.Diagnostics.DirectoryConfiguration
          }
          $newDirectoryConfig.Container = $container
          $newDirectoryConfig.Path = $path
          $newDirectoryConfig.DirectoryQuotaInMB = $quota
          if($existingDirectory -eq $false)
          {
            $diagConfig.DataSources.Add($newDirectoryConfig)
          }
          
          $role | Set-FileBasedLog -DirectoriesConfiguration $diagConfig.DataSources -BufferQuotaInMB $quota -TransferPeriod $transferAllInMinutes
        }
    }
}

Now the step of actually configuring your role using all of this code.

The snippet below configures IIS logs, IIS failed request logs and a local resource named “customLogging” to be transferred to storage every 15 minutes.

Configuring Logs to be Transferred

 
GetDiagRoles | foreach {
  $CurrentRole = $_
  
  if($CurrentRole.RoleName -eq "MyWebRole")
  {
   # Retrieve the local paths in the role
   $iislogs = $CurrentRole | GetIISLogsPath
   $iisFailedLogs = $CurrentRole  | GetIISFailedRequestPath
   $customLogs = $CurrentRole | GetLocalResourcePath "customLogging"
   
   # Configure diagnostics to transfer log data to storage
   $CurrentRole | SetDirectory $iisFailedLogs "wad-iis-failedreqlogfiles"  0 15
   $CurrentRole | SetDirectory $iislogs "wad-iis-logfiles"  0 15
   $CurrentRole | SetDirectory $customLogs  "wad-customlogging"  0 15 
  }
}

The snippet below downloads the files from each container to the local file system.

Downloading the Data from Storage

 
Save-Container -ContainerName "wad-iis-logfiles" -LocalPath "c:\diagdata" `
			-StorageAccountKey $storagekey -StorageAccountName $storageAccount
			
Save-Container -ContainerName "wad-iis-failedreqlogfiles" -LocalPath "c:\diagdata" `
			-StorageAccountKey $storagekey -StorageAccountName $storageAccount
			
Save-Container -ContainerName "wad-customlogging" -LocalPath "c:\diagdata" `
			-StorageAccountKey $storagekey -StorageAccountName $storageAccount

Finally, to clean up storage from each container we provide you with the Clear-Container cmdlet.

Note: Currently, we do not provide a -From or -To parameter to Clear-Container. To ensure that you do not delete data that may currently be being logged
you will need to ensure your scheduled transfers do not overlap during the same time period of a deletion. Yes, we are looking into improving this scenario.

Cleaning up a Container

 
Clear-Container -ContainerName "wad-iis-logfiles"  `
			-StorageAccountKey $storagekey -StorageAccountName $storageAccount
			
Clear-Container -ContainerName "wad-iis-failedreqlogfiles" `
			-StorageAccountKey $storagekey -StorageAccountName $storageAccount
			
Clear-Container -ContainerName "wad-customlogging" `
			-StorageAccountKey $storagekey -StorageAccountName $storageAccount

Print Current Windows Azure Diagnostic Settings

September 20, 2011 Leave a comment

This is part 3 of a series.

Here is a handy helper function to help you view what diagnostics settings are currently configured for your Windows Azure service.

(Tip: I add all of these helper functions to a PowerShell Module (.psm1) script, export functions and variables and include it in my other scripts)

Just as in the other articles you will need to add the PowerShell Snapin (or module):

 
  Add-PsSnapin WAPPSCmdlets 

Ditto, I have this handy initialization block and helper function GetDiagRoles:

Initialization and Helper Function

 
  $storageAccountName = "YourStorageAccountName" 
  $storageAccountKey = "YourStorageAccountKey" 
  $deploymentSlot = "Production" 
  $serviceName = "YourHostedService" 
  $subscriptionId = "YourSubscriptionId" 
  # Thumbprint for your cert goes below 
  $mgmtCert = Get-Item cert:\CurrentUser\My\D7BECD4D63EBAF86023BB4F1A5FBF5C2C924902A 

  function GetDiagRoles { 
    Get-HostedService -ServiceName $serviceName -SubscriptionId $subscriptionId -Certificate $mgmtCert | ` 
        Get-Deployment -Slot $deploymentslot | ` 
        Get-DiagnosticAwareRoles -StorageAccountName $storageAccountName -StorageAccountKey $storageAccountKey 
   } 

PrintDiagnosticSettings Helper Function

 
function PrintDiagnosticSettings
{
      $input | foreach {
      $RoleObject = $_
      $RoleObject | Get-DiagnosticAwareRoleInstances | 
      foreach {
          $roleinstance = $_
          write-host ""
          write-host -BackgroundColor DarkBlue -ForegroundColor White "Retrieving Diagnostic Settings for RoleInstance: " $roleinstance
          
          # Diagnostics Configuration for Logs
          $diagConfig = $RoleObject | Get-DiagnosticConfiguration -BufferName Logs -InstanceId $roleinstance
          write-host -BackgroundColor DarkGreen -ForegroundColor White "Windows Azure Logs - BufferQuota (MB): " $diagConfig.BufferQuotaInMB " LogLevel:" $diagConfig.ScheduledTransferLogLevelFilter " Scheduled Transfer to Storage: " $diagConfig.ScheduledTransferPeriod.ToString()
          write-host ""
          
          # Diagnostics Configuration for Diagnostic Infrastructure Logs
          $diagConfig = $RoleObject | Get-DiagnosticConfiguration -BufferName DiagnosticInfrastructureLogs -InstanceId $roleinstance
          write-host -BackgroundColor DarkGreen -ForegroundColor White "Diagnostic Infrastructure Logs - BufferQuota (MB): " $diagConfig.BufferQuotaInMB " LogLevel:" $diagConfig.ScheduledTransferLogLevelFilter " Scheduled Transfer to Storage: " $diagConfig.ScheduledTransferPeriod.ToString()
          write-host ""
          
          # Diagnostics Configuration for Performance Counters          
          $diagConfig = $RoleObject | Get-DiagnosticConfiguration -BufferName PerformanceCounters -InstanceId $roleinstance
          write-host -BackgroundColor DarkGreen -ForegroundColor White "Performance Counters - BufferQuota (MB): " $diagConfig.BufferQuotaInMB " Scheduled Transfer to Storage: " $diagConfig.ScheduledTransferPeriod.ToString()
          $diagConfig.DataSources | foreach {
            $CounterSpecifier = $_.CounterSpecifier
            $SampleRate = $_.SampleRate
            write-host "  Counter: " $CounterSpecifier " SampleRate: " $SampleRate
          }
          write-host ""
          
          # Diagnostics Configuration for Windows Event Logs          
          $diagConfig = $RoleObject | Get-DiagnosticConfiguration -BufferName WindowsEventLogs -InstanceId $roleinstance
          write-host -BackgroundColor DarkGreen -ForegroundColor White "Windows Event Logs - BufferQuota (MB): " $diagConfig.BufferQuotaInMB " LogLevel:" $diagConfig.ScheduledTransferLogLevelFilter  " Scheduled Transfer to Storage: " $diagConfig.ScheduledTransferPeriod.ToString()
          $diagConfig.DataSources | foreach {
            $logName = $_.ToString()
            write-host " Log Name: " $logName
          }
          write-host ""
          
          # Diagnostics Configuration for Directories          
          $diagConfig = $RoleObject | Get-DiagnosticConfiguration -BufferName Directories -InstanceId $roleinstance
          write-host -BackgroundColor DarkGreen -ForegroundColor White "Directories - BufferQuota (MB): " $diagConfig.BufferQuotaInMB " Scheduled Transfer to Storage: " $diagConfig.ScheduledTransferPeriod.ToString()
          $diagConfig.DataSources | foreach {
            $container = $_.Container
            $path = $_.Path
            write-host "  Path: " $path " Container: " $container " Quota (MB): " $diagConfig.BufferQuotaInMB 
          }
      }
    }
}

Usage

 
  GetDiagRoles | PrintDiagnosticSettings

Output Example

Follow

Get every new post delivered to your Inbox.