normalian blog

Let's talk about Microsoft Azure, ASP.NET and Java!

Windows Azure SDK for .NET の Management Library を利用して Webサイト を動的に作成してみる

Windows Azure SDK も日々進化しており、管理ポータルで操作している内容を SDK 越しでも実現可能になるようだ。今回は Preview 機能(2014年1月時点)となるが、Windows Azure SDK for .NET の Management Library 機能を利用して C# で動的に Webサイトを構築するまでの流れを紹介する。

準備と疎通

Windows Azure SDK for .NET の Preview 機能を利用するためには以下を実行する必要がある。

  • Windows SDK for Windows 8.1 をインストールする(makecert, certmgr コマンドを利用するため)
  • 自己証明書(*.cer)を作成し、管理ポータルにアップロードする
  • 新規にC#プロジェクト作成し、自己証明書から作成する秘密鍵(*.pfx)を配置する
  • NuGet を利用して、Microsoft.WindowsAzure.Management.Libraries のプレビューリリースを取得する。
  • 疎通用のコードを書く
自己証明書(*.cer)を作成し、管理ポータルにアップロードする

事前に Windows SDK for Windows 8.1 をインストールしてもらっているとして、さっそく証明書の作成にはいる。

まず、cmd.exe 直でなく VS2012 ARM Cross Tools Command Prompt 等の makecert.exe や certmgr.exe 実行ファイルが格納されたフォルダ(例:C:\Program Files (x86)\Windows Kits\8.1\bin\x64)にパスを通してくれるコマンドプロンプトを実行する。更に、コマンドプロンプトから以下のコマンドを実行し、ManagementTestCert.cer という名前の自己証明書を作成する。

c:\temp>makecert -r -pe -a sha1 -n "CN=NORMALIAN" -ss my -len 2048 -sp "Microsoft Enhanced RSA and AES Cryptographic Provider" -sy 24 ManagementTestCert.cer

自己証明書を作成した後、Windows Azure の管理ポータルにアクセスし、以下の画面を参考に自己証明書をアップロードする。
f:id:waritohutsu:20140103022939p:plain

新規にC#プロジェクト作成し、自己証明書から作成する秘密鍵(*.pfx)を配置する

自己証明書から秘密鍵を作成する。コマンドプロンプトから certmgr.exe を実行し、作成した自己証明書を選択して[エクスポート]ボタンを押下する(名前は makecert.exe の引数で設定した "CN=NORMALIAN" で表示される)。[証明書エクスポートウィザードの開始]が起動するため、[はい、秘密鍵をエクスポートします]にチェックをし、パスワードを設定して *.pfx ファイルを作成する。この際設定したパスワードは後ほど利用するので注意してほしい。

次に、Visual Studio を起動して新規にアプリケーションを作成する(今回はコンソールアプリケーションとする)。作成したソリューションに *.pfx ファイルを以下のように配置し、プロジェクトの含めた後、[ビルドアクション] を「コンテンツ」に、[出力ディレクトリにコピー]を「新しい場合はコピーする」に設定する。
f:id:waritohutsu:20140103022943p:plain

最後に NuGet のコンソールを起動し、以下のコマンドを実行することで Windows Azure SDK の Preview がインストールできる。

Install-Package Microsoft.WindowsAzure.Management.Libraries -IncludePrerelease
疎通用のコードを書く

以下の疎通用コードを作成することで、実際の疎通が取れる。

using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Management;
using Microsoft.WindowsAzure.Management.WebSites.Models;
using System;
using System.Collections.Generic;
using System.Security.Cryptography.X509Certificates;
using System.Threading;

namespace AzureManagementConsoleApp
{
    public class Program
    {
        static void Main()
        {
            ListLocationServices();
            Console.ReadLine();
        }

        public static async void ListLocationServices()
        {
            var cert = new X509Certificate2(@"Assets\ManagementTestCert.pfx", "<秘密鍵のパスワード>");
            var credentials = new CertificateCloudCredentials("<サブスクリプションID>", cert);

            using (ManagementClient client = CloudContext.Clients.CreateManagementClient(credentials))
            {
                var result = await client.Locations.ListAsync();
                var locations = result.Locations;
                foreach (var location in locations)
                {
                    Console.WriteLine("Location: {0}", location.Name);

                    foreach (var feature in location.AvailableServices)
                    {
                        Console.WriteLine("\t{0}", feature);
                    }
                }
            }
        }
    }
}

実行結果は以下になる。

Location: East Asia
        Compute
        Storage
        PersistentVMRole
        HighMemory
Location: Southeast Asia
        Compute
        Storage
        PersistentVMRole
        HighMemory
Location: North Europe
        Compute
        Storage
        PersistentVMRole
        HighMemory
Location: West Europe
        Compute
        Storage
        PersistentVMRole
        HighMemory
(中略)

C# のコードで Webサイトを作成してみる

上記の環境まで作成していれば、あとは以下のコードを実行することで East Asia に Web サイトが作成可能だ。

using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Management;
using Microsoft.WindowsAzure.Management.WebSites.Models;
using System;
using System.Collections.Generic;
using System.Security.Cryptography.X509Certificates;
using System.Threading;

namespace AzureManagementConsoleApp
{
    public class Program
    {
        static void Main()
        {
            CreateNewWebSite();
            Console.ReadLine();
        }

        public static async void CreateNewWebSite()
        {
            const string sitename = "createfromcode";
            const string webSpaceName = "eastasiawebspace";
            const string regionName = "East Asia";

            var cert = new X509Certificate2(@"Assets\ManagementTestCert.pfx", "<秘密鍵のパスワード>");
            var credentials = new CertificateCloudCredentials("<サブスクリプションID>", cert);

            using (var client = CloudContext.Clients.CreateWebSiteManagementClient(credentials))
            {
                // WebSiteCreateParameters が null でもエラー
                // WebSpace が null だとエラー
                // eastasiawebspace 等、WebSpace の名前はある程度決まっている
                var parameters = new WebSiteCreateParameters
                {
                    WebSpace = new WebSiteCreateParameters.WebSpaceDetails
                    {
                        Name = webSpaceName,
                        GeoRegion = regionName,
                        Plan = "VirtualDedicatedPlan",
                    },
                    // カスタムドメイン名を指定できる場所だが、無料モードだと
                    // azurewebsite.net じゃないとバリデーションがかかるっぽい
                    HostNames = new List<string>
                    { 
                        sitename + ".azurewebsites.net",
                    },
                    Name = sitename,
                    WebSpaceName = webSpaceName,
                };
                await client.WebSites.CreateAsync(webSpaceName, parameters, CancellationToken.None);
            }
        }
    }
}