4 Managing Windows Azure Web Sites from the Console

IN THIS CHAPTER:

  • Tuning up your system to execute the Azure cmdlets
  • Managing site state and application settings
  • Getting comfortable with building more complex scripts

She checks her watch; there are only minutes to spare. It's dark, and it's getting darker. The guards are closing in, but their weapons are the least of her worries. The clock seems to run faster and faster, and it won't be long until the good guys, nay, the whole planet, will have all but run out of time. The music crescendos as time appears certain to favor the antagonists, and the only hope left for all of humanity is to connect to a distant satellite and override the nuclear launch control codes. And what does our heroine do? Browse to a website? Open Visual Studio? No! She opens a command-line shell!

There is something uber-geeky and smart-looking about anyone who seems to have good control of their systems from a command line. If you're a touch typist and know your command set well, you can move very quickly inside of a shell and, better yet, write scripts to help automate anything that exposes a compatible interface.

Your typical day at the office may not be quite as compelling as the heroine above, but there are many practical applications for having a handle on what you're able to do and knowing the fastest way to do it. With Azure, it may very well be from within PowerShell, and the Windows Azure cmdlets (pronounced “command-lets”) are the way to get there.

In addition, if you don't use PowerShell but instead prefer a different shell or operating system altogether, all the features described in this chapter are available to you in the Azure Cross-Platform CLI tools with minor syntax changes here and there. Use what you're comfortable using!

PREPARING YOUR ENVIRONMENT

If you haven't used any third-party external cmdlets on your system you need to first grant the proper permissions for scripts to execute in PowerShell. The default policy is the most secure, allowing only individual commands to run, but no scripts and certainly no unsigned scripts or configuration files.

The Windows Azure cmdlets are signed and thus require the execution policy called RemoteSigned. This permission level allows you to write your own scripts and will only run scripts and configuration files downloaded from the Internet that are digitally signed. Here's how to do that:

  1. Open PowerShell as an administrator by right-clicking on the PowerShell icon and selecting Run as Administrator if you are running in least privilege mode. You won't always need to run as admin, but it is required for setting the execution policy.
  2. Set the execution policy to RemoteSigned. Type the following command:
    Set-ExecutionPolicy RemoteSigned

You can close PowerShell at this point and your execution policy settings will be saved for future sessions, even when running as a standard user.

Next, it's time to download the cmdlet installer and get them on your machine:

  1. Navigate to http://go.microsoft.com/?linkid=9811175&clcid=0x409 in your web browser.
  2. Select the download for Windows Azure PowerShell.
  3. When the download is complete, run the installer.

The installer is just a quick download of less than 100KB that launches the Web Platform Installer with the Windows Azure PowerShell cmdlets selected for download. You will encounter a licensing agreement that, while you're free to consent or not as you wish, only after acceptance will the installation finish successfully. Congratulations! You're now one step closer to saving the world from thermonuclear warfare or, more likely, scripting some Windows Azure operations.

NOTE The Web Platform Installer (WebPI) should be your preferred method of download and installation, if given the option when working with web development tools and Windows Azure tools in particular. Most applications served through WebPI have the capability to check for compatibility, install dependencies, and generally help you avoid any headaches getting your tools to run. Once installed, related downloads, applications, and tooling are often recommended to complement your installation.

CONFIGURING YOUR ACCOUNT

Even if you only work with one Windows Azure subscription throughout the course of your daily responsibilities, the PowerShell scripts need to have correct information on hand in order to manage your subscription and its assets. To provide this information you can download a single file representing the authority to manipulate your websites and any other Windows Azure pieces you've created, installing it once.

The file you'll download is simply an XML document similar to the following:

<?xml version=“1.0” encoding=“utf-8”?>
<PublishData>
  <PublishProfile
    PublishMethod=“AzureServiceManagementAPI”
    Url=“https://management.core.windows.net/”
    ManagementCertificate=“WsVKB6VrZtmwG6…OFtFwrUk5g==”>
    <Subscription
      Id=“111111a1-b22b-333c3-d444-e5e555ee55e5”
      Name=“Subscription Name” />
  </PublishProfile>
</PublishData>

This document contains a root PublishData node. And contained within is the PublishProfile node, with its attributes — PublishMethod, Url, and ManagementCertificate — along with all of the subscriptions you have tied to your Microsoft Account, including those subscriptions delegated to you by others. The subscription IDs and names are stored with your management certificate when you import the file. You can import multiple files and easily switch between subscriptions, and the Windows Azure PowerShell cmdlets will keep track of them for you behind the scenes.

NOTE Your settings file contains critical publishing information and your account management certificate. It is all that anyone needs to be able to command your Windows Azure properties. After downloading this file, be sure to store it in a secure location or to delete it after you have imported the file to the Windows Azure PowerShell tools.

Windows Azure keeps track of all the management certificates that are part of the publishing profiles that have been downloaded for your account. As shown in Figure 4-1, the list of management certificates is viewable from the Settings menu item in the portal. Note that issued certificates do expire, so you'll have to keep that in mind if you intend to use the PowerShell cmdlets as part of an automated process.

image

FIGURE 4-1

Downloading Your Publishing Profile

While the mechanics of downloading your profile is a straightforward operation, the process is a little more difficult if you have multiple subscriptions to work with. The basic flow is as follows:

  1. Open a PowerShell console.
  2. Type the following command:
    Get-AzurePublishSettingsFile
  3. Sign into your Windows Azure account, if prompted, in the browser page that was opened in your default browser.
  4. Save the file to a known location.

Step number 3 that can become a little convoluted, especially if you have saved your credentials in your browser or you're using an operating system (such as Windows 8) that has the ability to pass on the credentials of the currently signed-in user account through Internet Explorer. To get around this, you can take advantage of the fact that Windows will try to open the requested link in an existing browser session, if available. To sign in using an account other than the cached credentials, you can do the following:

  1. Close any open instances of Internet Explorer. This ensures that the browser you're opening will be the one targeted when you try to download your settings file.
  2. Start InPrivate browsing in Internet Explorer by right-clicking on the Internet Explorer icon and selecting the InPrivate option.
  3. Follow the steps listed in the previous section as described. When you get to step 3, the browser opened in InPrivate mode will not have any cached credentials, thus allowing you to sign in with an alternate account.

NOTE It's a good idea to save your settings file to a directory that is easy to navigate to from a command line, such as c:azure. Later, when you go to import the settings, you'll save some keystrokes moving around the file system!

If you want to work with multiple Microsoft Accounts from PowerShell, you can repeat the preceding steps for each account; just remember to close all your open browser windows at the start of each cycle.

Importing Settings

With your settings downloaded you can now import the profile of each account.

  1. Open PowerShell.
  2. Navigate to the directory where you saved your publishing profiles.
  3. Execute the following command:
    Import-AzurePublishSettingsFile .your_file_name.publishsettings

Remember that you can use tab completion in PowerShell, so if you're in the directory where the file is created, you simply need to press Tab to complete the filename of your publish settings file.

The utility will import the data for you and cache the information in the roaming data folder of your account, located at C:Users\%UserProfile%AppDataRoamingWindows Azure PowerShell, where a number of different files are created to store the information:

  • Config.json — A JSON representation of your account information
  • DefaultSubscriptionData.xml — Contains the complete list of imported account profiles
  • publishSettings.xml — The cache used to represent the account currently in context for Windows Azure PowerShell cmdlets

If, for any reason, you want to clear the settings for your Azure accounts in PowerShell, navigate to the preceding directory and delete all the files. This doesn't affect your account, it just removes all the certificates and subscription IDs that are required to publish to your Azure properties from your local computer. You can download and import the settings again at any time.

NOTE Deleting the files in your roaming folder for Windows Azure PowerShell will not have an immediate effect on any open PowerShell consoles. Some of the settings information is loaded when you start to use the Azure cmdlets, and this information is cached for as long as you leave the console open. You need to restart PowerShell if you want to fully clear the cache.

Switching between Subscriptions

The first publishing profile that you import will be saved as the default on your machine, but you can switch between different profiles if you know the name. If you have already imported the settings, you can also get the name of the subscription locally, either by examining the import file or from the Windows Azure PowerShell tools themselves. To get the names from a PowerShell console type the following command:

Get-AzureSubscription

This will return a listing of all the subscriptions that you've imported. For each subscription there is a field in this listing called SubscriptionName. For the purposes of this example, that field contains the value “3-Month Free Trial”; therefore, to switch to that account and start using it in the context of the Azure cmdlets, you need to type the following:

Select-AzureSubscription “3-Month Free Trial”

Now, any of the scripts that need to use the context of a subscription will operate in the context of this subscription. The cache files will be updated to reflect your current context; and as you use the scripts, other files will be created in this folder. It's interesting to watch this directory as you use the cmdlets to see what the scripts are doing behind the scenes!

MANAGING YOUR SUBSCRIPTION AND WEB SITES

With your publishing profile imported and your default subscription set, you're ready to begin using the cmdlets and flexing your shell might. Go, you superhero, go! Start with a basic command that enables you to see the websites you've already created in your account:

Get-AzureWebsite

Like many other PowerShell commands, the “naked” get command returns the full list of objects for all of the Azure Web Sites in the current subscription. If you run the same command again and pass in the name of a specific site, the script will return many of the configuration points, site-specific publishing information, and more, as shown in Figure 4-2. Try the same command but pass in the name of a site:

Get-AzureWebsite -Name YourSiteName

image

FIGURE 4-2

This is a good script to keep in your back pocket, as it is easy to survey the state of your websites or the properties of a specific site. When using the command as part of a more complex script, you could do more interesting things by filtering and piping the results of the command to other operations. For example, you could restart all your websites that have “acceptancetest” in their name with the following script:

Get-AzureWebsite |
    Where-Object { $_.Name -like “*acceptancetest*” } |
    ForEach-Object { Restart-AzureWebsite $_.Name }

Therefore, while you're working through the following cmdlets, keep in mind that though their premise is often simple, you can actually work them into more interesting scripts to orchestrate operations of much greater complexity.

NOTE When you are trying out commands in this section, be aware that Azure hostnames must be unique. If I have already created the site “MyNothingSite,” I will have reserved the hostname “mynothingsite.azurewebsites.net” and you, understanding reader, won't be able to reuse it. If you get an error indicating that a site name has been snatched up by a previous Windows Azure Web Site Customer, just pick a new one and keep rolling.

Creating Sites

Some things are kept cleverly simple. Take, for instance, creating a new Web Site in your Azure portal:

New-AzureWebsite MyNothingSite

Your site won't do anything, but it will be created for you and left running with the standard “This web site has been successfully created” message on a default page, and you can manage it from PowerShell (or the portal) as you would any other site.

Creating sites from the command line isn't always going to be practical, but you may find reason for it throughout the course of your development adventures; for example, if you need to replicate a Web Site across different regions to improve the overall performance for your users or if you want to perform a Web Site deployment as part of a build process.

Consider the following script, which accepts the full path of a local directory in a GitHub repository. It spins up the website for you in your Azure account, creates a deployment based on your last GitHub check-in, and displays the site in your browser:

param(
 [string] $SiteName=[guid]::NewGuid().ToString(),
 [parameter(Mandatory=$true)] [string] $FullPath
)

# save the current location and switch to the path provided
Push-Location
cd $FullPath

# create the website and store the script result
$createData = New-AzureWebsite $siteName -GitHub

# output the host name of the created website
$createData.HostNames[0]

# switch back to the orginal directory
Pop-Location
Set-Location

# pause for dramatic suspense (…and git deployment)
Start-Sleep 30

# launch the site in a local browser
Show-AzureWebsite $SiteName

Return

A word of caution when running the script: The directory indicated by the $FullPath parameter must be a valid GitHub repository. If not, then the script receives an error suggesting that the data at the root level is invalid.

This little bit of code will start to give you an idea of some of the power you have with the PowerShell cmdlets. The script enables you to create a site with a random GUID if you don't pass in the name of a site, so it also outputs the first (and only) hostname of your newly created site. If you want to give it a try, perform the following steps:

  1. Open the PowerShell ISE.
  2. Save the preceding script into a file called CreateSite.ps1.
  3. Navigate to the directory in which the script is located.
  4. From the PowerShell console, call the script and pass in the name of a folder with a GitHub repository. You could, for example, use the simple site that you deployed in Chapter 3. Had you saved that repository in a directory called “c:azuresimplesite” you could execute the script as follows:
    .CreateAndLaunchSite.ps1 -FullPath c:azuresimplesite

Controlling Site State

These are the bread-and-butter commands of any web developer. You've likely worked from the command line before to restart IIS, or perhaps you've even used WMI in PowerShell to start, stop, or recycle a website or app pool. To do the same to your Windows Azure Web Sites, you just follow the standard verb-noun syntax of PowerShell and pass in the name of your site. For example, use the following to stop your site:

Stop-AzureWebsite YourSiteName

To restart it, use this:

Start-AzureWebsite YourSiteName

Or, if you want to do it all in one fell swoop:

Restart-AzureWebsite YourSiteName

Here are some suggestions for how you may be able to use these as part of your scripts:

  • Your site exposes an API and you have a secondary website or application that consumes the API. You want to introduce some instability in the back-end application to test fault tolerance in the consuming application.
  • You are penny-pinching and want to turn off sites when you reach certain usage levels to avoid charges, and automatically turn them back on when your billing cycle starts anew.
  • You are testing cold-start (the traditional IIS kind, not the deactivated Azure Web Site kind) performance for your website.
  • You need to reset the cached values associated with your website.

Removing Sites from Your Account

When you are done with a site, for whatever reason, you can always remove it using the same syntax format and a straightforward command from PowerShell or within a script:

Remove-AzureWebsite YourSiteName

The Remove-AzureWebsite cmdlet will, by default, give you a confirmation prompt before it carries out the operation. If you wish to suppress this, simply add the -Force parameter like so:

Remove-AzureWebsite YourSiteName -Force

Confirming Your Account and Site Status

If you've had your Windows Azure Portal open through this last set of exercises, you likely noticed that the portal tends to get a little behind, particularly when you're issuing a higher volume of commands. This is primarily due to caching for performance of the web portal, but it can lead to short-lived discrepancies between the actual state of a particular site or the number of websites active on your account.

At any time, you can fetch a complete listing of all your sites, with a glimpse of the current state, by running the Get-AzureWebsite command. The results will be similar to what is shown in Figure 4-3, where you can see the GUID-named site is in a stopped state.

image

FIGURE 4-3

CONFIGURING YOUR SITE

Chances are pretty good that you'll be using web.config transforms or publishing profiles to bake changes into your configuration as you push to the cloud. But you may find on occasion that modifying its details needs to be done outside of the deployment process. Perhaps you might find a value in your web.config file might be used to determine which part of a script is to be executed. In this section, you learn about the different commands that are available for you to perform basic functionality on the web.config file.

Listing Application Configuration Elements

The Windows Azure Portal provides a clean interface to create, view, and modify your app settings, as shown in Figure 4-4. These values are loaded at start-up and available to your application when it runs. When you fetch the details of your website with the Get-AzureWebsite command, similar to the call illustrated in Figure 4-2, you will only be able to see the names of existing keys, but not the values. Examining the list of keys for the same set of app settings, you might see something similar to the following:

AppSettings                  : {good-fruit, best-fruit, better-fruit}

image

FIGURE 4-4

The Get-AzureWebsite command returns an object with properties on it, and the results are displayed in a table of key-value pairs. As you get more comfortable working with PowerShell, you'll notice that this is a common representation of an object, and properties are often condensed and displayed with very little meat on the bone. In other words, if you have a property with a value that is another object, you won't see many of the details.

In the case of our app settings, the property value is another set of key-value pairs. To coerce the values of those keys out of the cmdlet, you need to instead return the property itself. The shorthand version of this command is as follows:

(Get-AzureWebsite YourSiteName).AppSettings

When I issued this command against my fantastically fruity website, I got the following output:

Name                            Value
----                            -----
good-fruit                      kiwi
best-fruit                      bananas
better-fruit                    grapes

Of course, you're in PowerShell, so you're required to do something more interesting, right? The names and values you see here are actually part of a HashTable object, so you can manipulate the collection by getting the enumerator and piping the results into additional commands. The following command sorts the collection of app settings by the value — largest value first — and outputs as part of a string:

(Get-AzureWebsite YourSiteName).AppSettings.GetEnumerator() |
   Sort-Object Value -Descending |
   ForEach-Object { Write-Host $_.Key ‘is set to’ $_.Value }

You can use this technique to extract the data you are looking for out of other properties on the object returned from Get-AzureWebste, such as for installed SSL certificates or your site's connection strings.

Adding, Updating, and Deleting Keys

In the preceding section you were working with values that already existed, either from a previous shell session or perhaps as a result of what you configured in the Azure Portal. But what if you wanted to create the app settings from scratch? No problem, but you're going to have to wire up the hashtable by hand in PowerShell first, then pass that object in to the Set-AzureWebsite cmdlet:

$settings = @{
  “best-fruit” = “bananas”;
  “better-fruit” = “grapes”;
  “good-fruit” = “kiwi”
}
Set-AzureWebsite YourWebSite -AppSettings $settings

Now the base keys are there, but there is one additional step that still needs to be performed (but was left out of your first go-round); for this example, imagine you had meant to include a property defining the worst fruit but forgot it. The AppSettings property on the Get-AzureWebsite cmdlet result is a hashtable. To add your worst-fruit property, start by getting a reference to the hashtable and then add your new property to the collection. Finally, you would push the resulting set of data back to your site:


$settings = (Get-AzureWebsite YourWebSite).AppSettings
$settings.Add(“worst-fruit”, “tomatoes”)
Set-AzureWebsite YourWebSite -AppSettings $settings

But what if, in your haste to get that key-value pair up in the cloud, you accidentally added the wrong value (in other words, tomatoes really aren't the worst fruit) and need to rectify the value of your setting. You don't want to modify any of the previous values, so again you start by grabbing your settings from the portal, then adjust the value in the hashtable before shipping it back up into the sky.

$settings = (Get-AzureWebsite YourWebSite).AppSettings
$settings.Set_Item(“worst-fruit”, “dried prunes”)
Set-AzureWebsite YourWebSite -AppSettings $settings

While the property types vary on the different objects, this fetch-update-store pattern is very applicable to other settings as well. If you wanted to update a specific connection string you would do the following:

  1. Fetch the list of connection strings on your site.
  2. Update the connection string you need to modify in the collection.
  3. Push the collection of connection strings back up to the site.

To translate that back into PowerShell, you might end up with something like this:

# fetch the current collection of strings
$connectionStrings = (Get-AzureWebsite YourWebSite).ConnectionStrings
# select the specific string you're updating
$connectionStrings |
    Where-Object { $_.Name -eq “DefaultConnection” } |
    ForEach-Object { $_.ConnectionString = “Details-Go-Here” }

# store the details back in the cloud
Set-AzureWebsite YourWebSite -ConnectionStrings $connectionStrings

If you ever need to remove a setting or connection string from the site, you would follow a similar set of steps, downloading the details, modifying the collection, and then pushing it back to your account. For example, consider the following script, which would remove the connection string named ExtraConnection from the config file.

$connectionStrings = (Get-AzureWebsite YourWebSite).ConnectionStrings
$connectionStrings |
    Where-Object { $_.Name -eq “ExtraConnection” } |
    ForEach-Object { $_.Remove }

Set-AzureWebsite YourWebSite -ConnectionStrings $connectionStrings

SUMMARY

For most purposes you'll find that working in the Windows Azure Management Portal is a pleasant experience. You will be able to manage the bulk of your work without much grief, and nearly all of the requisite functionality will only be a click away.

When it comes time to automate some of that functionality, you're now better equipped to tackle the chore and create reusable scripts to help with initial creation and deployment, configuration, and state management. You've explored the basic commands and know how to control various aspects of your site through the Windows Azure PowerShell cmdlets, updating existing values or removing them from your website.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset