Python を使用して Azure で Windows VM を作成および管理する

Azure 仮想マシン (VM) には、複数のサポート Azure リソースが必要です。 この記事では、Python を使用した VM リソースの作成、管理、削除について説明します。 次の方法について学習します。

  • Visual Studio プロジェクトを作成する
  • パッケージをインストールする
  • 資格情報を作成する
  • リソースの作成
  • 管理タスクの実行
  • リソースを削除する
  • アプリケーションを実行する

これらの手順を実行するには、約 20 分かかります。

Visual Studio プロジェクトを作成する

  1. まだインストールしていない場合は、Visual Studio をインストールしてください。 [ワークロード] ページで [Python 開発 ] を選択し、[ インストール] をクリックします。 概要では、 Python 3 64 ビット (3.6.0) が自動的に選択されていることがわかります。 Visual Studio を既にインストールしている場合は、Visual Studio Launcher を使用して Python ワークロードを追加できます。
  2. Visual Studio をインストールして起動したら、[ファイル]、[新規作成>プロジェクト] の順>クリックします。
  3. [ テンプレート>Python>Python アプリケーション] をクリックし、プロジェクトの名前として myPythonProject を入力し、プロジェクトの場所を選択して、[ OK] をクリックします。

パッケージをインストールする

  1. ソリューション エクスプローラーの myPythonProject で、[ Python 環境] を右クリックし、[ 仮想環境の追加] を選択します。
  2. [仮想環境の追加] 画面で、 env の既定の名前をそのまま使用し、基本インタープリターに Python 3.6 (64 ビット) が選択されていることを確認し、[ 作成] をクリックします。
  3. 作成した env 環境を右クリックし、[ Python パッケージのインストール] をクリックし、検索ボックスに 「azure 」と入力して、Enter キーを押します。

出力ウィンドウに、Azure パッケージが正常にインストールされたことを確認できます。

資格情報を作成する

この手順を開始する前に、 Active Directory サービス プリンシパルがあることを確認します。 また、後の手順で必要なアプリケーション ID、認証キー、テナント ID も記録する必要があります。

  1. 作成 myPythonProject.py ファイルを開き、次のコードを追加して、アプリケーションを実行できるようにします。

    if __name__ == "__main__":
    
  2. 必要なコードをインポートするには、次のステートメントを .py ファイルの先頭に追加します。

    from azure.common.credentials import ServicePrincipalCredentials
    from azure.mgmt.resource import ResourceManagementClient
    from azure.mgmt.compute import ComputeManagementClient
    from azure.mgmt.network import NetworkManagementClient
    from azure.mgmt.compute.models import DiskCreateOption
    
  3. 次に、.py ファイルで、import ステートメントの後に変数を追加して、コードで使用される一般的な値を指定します。

    SUBSCRIPTION_ID = 'subscription-id'
    GROUP_NAME = 'myResourceGroup'
    LOCATION = 'westus'
    VM_NAME = 'myVM'
    

    subscription-id をサブスクリプション識別子に置き換えます。

  4. 要求を行う必要がある Active Directory 資格情報を作成するには、.py ファイル内の変数の後に次の関数を追加します。

    def get_credentials():
        credentials = ServicePrincipalCredentials(
            client_id = 'application-id',
            secret = 'authentication-key',
            tenant = 'tenant-id'
        )
    
        return credentials
    

    アプリケーション ID、認証キー、およびテナント ID を、Azure Active Directory サービス プリンシパルの作成時に以前に収集した値に置き換えます。

  5. 前に追加した関数を呼び出すには、.py ファイルの末尾にある if ステートメントの下に次のコードを追加します。

    credentials = get_credentials()
    

リソースの作成

管理クライアントを初期化する

管理クライアントは、Azure の Python SDK を使用してリソースを作成および管理するために必要です。 管理クライアントを作成するには、.py ファイルの末尾にある if ステートメントの下に次のコードを追加します。

resource_group_client = ResourceManagementClient(
    credentials,
    SUBSCRIPTION_ID
)
network_client = NetworkManagementClient(
    credentials,
    SUBSCRIPTION_ID
)
compute_client = ComputeManagementClient(
    credentials,
    SUBSCRIPTION_ID
)

VM とサポート リソースを作成する

すべてのリソースは、 リソース グループに含まれている必要があります。

  1. リソース グループを作成するには、.py ファイル内の変数の後に次の関数を追加します。

    def create_resource_group(resource_group_client):
        resource_group_params = { 'location':LOCATION }
        resource_group_result = resource_group_client.resource_groups.create_or_update(
            GROUP_NAME, 
            resource_group_params
        )
    
  2. 前に追加した関数を呼び出すには、.py ファイルの末尾にある if ステートメントの下に次のコードを追加します。

    create_resource_group(resource_group_client)
    input('Resource group created. Press enter to continue...')
    

可用性セット を使用すると、アプリケーションで使用される仮想マシンの保守が容易になります。

  1. 可用性セットを作成するには、.py ファイル内の変数の後に次の関数を追加します。

    def create_availability_set(compute_client):
        avset_params = {
            'location': LOCATION,
            'sku': { 'name': 'Aligned' },
            'platform_fault_domain_count': 3
        }
        availability_set_result = compute_client.availability_sets.create_or_update(
            GROUP_NAME,
            'myAVSet',
            avset_params
        )
    
  2. 前に追加した関数を呼び出すには、.py ファイルの末尾にある if ステートメントの下に次のコードを追加します。

    create_availability_set(compute_client)
    print("------------------------------------------------------")
    input('Availability set created. Press enter to continue...')
    

仮想マシンと通信するには、 パブリック IP アドレス が必要です。

  1. 仮想マシンのパブリック IP アドレスを作成するには、.py ファイル内の変数の後に次の関数を追加します。

    def create_public_ip_address(network_client):
        public_ip_addess_params = {
            'location': LOCATION,
            'public_ip_allocation_method': 'Dynamic'
        }
        creation_result = network_client.public_ip_addresses.create_or_update(
            GROUP_NAME,
            'myIPAddress',
            public_ip_addess_params
        )
    
        return creation_result.result()
    
  2. 前に追加した関数を呼び出すには、.py ファイルの末尾にある if ステートメントの下に次のコードを追加します。

    creation_result = create_public_ip_address(network_client)
    print("------------------------------------------------------")
    print(creation_result)
    input('Press enter to continue...')
    

仮想マシンは、 仮想ネットワークのサブネット内にある必要があります。

  1. 仮想ネットワークを作成するには、.py ファイル内の変数の後に次の関数を追加します。

    def create_vnet(network_client):
        vnet_params = {
            'location': LOCATION,
            'address_space': {
                'address_prefixes': ['10.0.0.0/16']
            }
        }
        creation_result = network_client.virtual_networks.create_or_update(
            GROUP_NAME,
            'myVNet',
            vnet_params
        )
        return creation_result.result()
    
  2. 前に追加した関数を呼び出すには、.py ファイルの末尾にある if ステートメントの下に次のコードを追加します。

    creation_result = create_vnet(network_client)
    print("------------------------------------------------------")
    print(creation_result)
    input('Press enter to continue...')
    
  3. 仮想ネットワークにサブネットを追加するには、.py ファイル内の変数の後に次の関数を追加します。

    def create_subnet(network_client):
        subnet_params = {
            'address_prefix': '10.0.0.0/24'
        }
        creation_result = network_client.subnets.create_or_update(
            GROUP_NAME,
            'myVNet',
            'mySubnet',
            subnet_params
        )
    
        return creation_result.result()
    
  4. 前に追加した関数を呼び出すには、.py ファイルの末尾にある if ステートメントの下に次のコードを追加します。

    creation_result = create_subnet(network_client)
    print("------------------------------------------------------")
    print(creation_result)
    input('Press enter to continue...')
    

仮想マシンには、仮想ネットワーク上で通信するためのネットワーク インターフェイスが必要です。

  1. ネットワーク インターフェイスを作成するには、.py ファイル内の変数の後に次の関数を追加します。

    def create_nic(network_client):
        subnet_info = network_client.subnets.get(
            GROUP_NAME, 
            'myVNet', 
            'mySubnet'
        )
        publicIPAddress = network_client.public_ip_addresses.get(
            GROUP_NAME,
            'myIPAddress'
        )
        nic_params = {
            'location': LOCATION,
            'ip_configurations': [{
                'name': 'myIPConfig',
                'public_ip_address': publicIPAddress,
                'subnet': {
                    'id': subnet_info.id
                }
            }]
        }
        creation_result = network_client.network_interfaces.create_or_update(
            GROUP_NAME,
            'myNic',
            nic_params
        )
    
        return creation_result.result()
    
  2. 前に追加した関数を呼び出すには、.py ファイルの末尾にある if ステートメントの下に次のコードを追加します。

    creation_result = create_nic(network_client)
    print("------------------------------------------------------")
    print(creation_result)
    input('Press enter to continue...')
    

すべてのサポート リソースを作成したので、仮想マシンを作成できます。

  1. 仮想マシンを作成するには、.py ファイル内の変数の後に次の関数を追加します。

    def create_vm(network_client, compute_client):  
        nic = network_client.network_interfaces.get(
            GROUP_NAME, 
            'myNic'
        )
        avset = compute_client.availability_sets.get(
            GROUP_NAME,
            'myAVSet'
        )
        vm_parameters = {
            'location': LOCATION,
            'os_profile': {
                'computer_name': VM_NAME,
                'admin_username': 'azureuser',
                'admin_password': 'Azure12345678'
            },
            'hardware_profile': {
                'vm_size': 'Standard_DS1'
            },
            'storage_profile': {
                'image_reference': {
                    'publisher': 'MicrosoftWindowsServer',
                    'offer': 'WindowsServer',
                    'sku': '2012-R2-Datacenter',
                    'version': 'latest'
                }
            },
            'network_profile': {
                'network_interfaces': [{
                    'id': nic.id
                }]
            },
            'availability_set': {
                'id': avset.id
            }
        }
        creation_result = compute_client.virtual_machines.create_or_update(
            GROUP_NAME, 
            VM_NAME, 
            vm_parameters
        )
    
        return creation_result.result()
    

    注

    このチュートリアルでは、Windows Server オペレーティング システムのバージョンを実行する仮想マシンを作成します。 他のイメージの選択の詳細については、 Windows PowerShell と Azure CLI を使用した Azure 仮想マシン イメージの移動と選択に関するページを参照してください。

  2. 前に追加した関数を呼び出すには、.py ファイルの末尾にある if ステートメントの下に次のコードを追加します。

    creation_result = create_vm(network_client, compute_client)
    print("------------------------------------------------------")
    print(creation_result)
    input('Press enter to continue...')
    

管理タスクの実行

仮想マシンのライフサイクル中に、仮想マシンの開始、停止、削除などの管理タスクを実行できます。 また、繰り返しまたは複雑なタスクを自動化するコードを作成することもできます。

VM に関する情報を取得する

  1. 仮想マシンに関する情報を取得するには、.py ファイル内の変数の後に次の関数を追加します。

    def get_vm(compute_client):
        vm = compute_client.virtual_machines.get(GROUP_NAME, VM_NAME, expand='instanceView')
        print("hardwareProfile")
        print("   vmSize: ", vm.hardware_profile.vm_size)
        print("\nstorageProfile")
        print("  imageReference")
        print("    publisher: ", vm.storage_profile.image_reference.publisher)
        print("    offer: ", vm.storage_profile.image_reference.offer)
        print("    sku: ", vm.storage_profile.image_reference.sku)
        print("    version: ", vm.storage_profile.image_reference.version)
        print("  osDisk")
        print("    osType: ", vm.storage_profile.os_disk.os_type.value)
        print("    name: ", vm.storage_profile.os_disk.name)
        print("    createOption: ", vm.storage_profile.os_disk.create_option.value)
        print("    caching: ", vm.storage_profile.os_disk.caching.value)
        print("\nosProfile")
        print("  computerName: ", vm.os_profile.computer_name)
        print("  adminUsername: ", vm.os_profile.admin_username)
        print("  provisionVMAgent: {0}".format(vm.os_profile.windows_configuration.provision_vm_agent))
        print("  enableAutomaticUpdates: {0}".format(vm.os_profile.windows_configuration.enable_automatic_updates))
        print("\nnetworkProfile")
        for nic in vm.network_profile.network_interfaces:
            print("  networkInterface id: ", nic.id)
        print("\nvmAgent")
        print("  vmAgentVersion", vm.instance_view.vm_agent.vm_agent_version)
        print("    statuses")
        for stat in vm_result.instance_view.vm_agent.statuses:
            print("    code: ", stat.code)
            print("    displayStatus: ", stat.display_status)
            print("    message: ", stat.message)
            print("    time: ", stat.time)
        print("\ndisks");
        for disk in vm.instance_view.disks:
            print("  name: ", disk.name)
            print("  statuses")
            for stat in disk.statuses:
                print("    code: ", stat.code)
                print("    displayStatus: ", stat.display_status)
                print("    time: ", stat.time)
        print("\nVM general status")
        print("  provisioningStatus: ", vm.provisioning_state)
        print("  id: ", vm.id)
        print("  name: ", vm.name)
        print("  type: ", vm.type)
        print("  location: ", vm.location)
        print("\nVM instance status")
        for stat in vm.instance_view.statuses:
            print("  code: ", stat.code)
            print("  displayStatus: ", stat.display_status)
    
  2. 前に追加した関数を呼び出すには、.py ファイルの末尾にある if ステートメントの下に次のコードを追加します。

    get_vm(compute_client)
    print("------------------------------------------------------")
    input('Press enter to continue...')
    

VM を停止する

仮想マシンを停止し、すべての設定を保持することはできますが、引き続き課金されます。または、仮想マシンを停止して割り当てを解除することもできます。 仮想マシンの割り当てが解除されると、それに関連付けられているすべてのリソースも割り当てが解除され、課金が終了します。

  1. 割り当てを解除せずに仮想マシンを停止するには、.py ファイル内の変数の後に次の関数を追加します。

    def stop_vm(compute_client):
        compute_client.virtual_machines.power_off(GROUP_NAME, VM_NAME)
    

    仮想マシンの割り当てを解除する場合は、power_off呼び出しを次のコードに変更します。

    compute_client.virtual_machines.deallocate(GROUP_NAME, VM_NAME)
    
  2. 前に追加した関数を呼び出すには、.py ファイルの末尾にある if ステートメントの下に次のコードを追加します。

    stop_vm(compute_client)
    input('Press enter to continue...')
    

VM を起動する

  1. 仮想マシンを起動するには、.py ファイル内の変数の後に次の関数を追加します。

    def start_vm(compute_client):
        compute_client.virtual_machines.start(GROUP_NAME, VM_NAME)
    
  2. 前に追加した関数を呼び出すには、.py ファイルの末尾にある if ステートメントの下に次のコードを追加します。

    start_vm(compute_client)
    input('Press enter to continue...')
    

VM のサイズを変更する

仮想マシンのサイズを決定するときは、デプロイの多くの側面を考慮する必要があります。 詳細については、「 VM のサイズ」を参照してください。

  1. 仮想マシンのサイズを変更するには、.py ファイル内の変数の後に次の関数を追加します。

    def update_vm(compute_client):
        vm = compute_client.virtual_machines.get(GROUP_NAME, VM_NAME)
        vm.hardware_profile.vm_size = 'Standard_DS3'
        update_result = compute_client.virtual_machines.create_or_update(
            GROUP_NAME, 
            VM_NAME, 
            vm
        )
    
    return update_result.result()
    
  2. 前に追加した関数を呼び出すには、.py ファイルの末尾にある if ステートメントの下に次のコードを追加します。

    update_result = update_vm(compute_client)
    print("------------------------------------------------------")
    print(update_result)
    input('Press enter to continue...')
    

データ ディスクを VM に追加する

仮想マシンには、VHD として格納されている 1 つ以上の データ ディスク を含めることができます。

  1. 仮想マシンにデータ ディスクを追加するには、.py ファイル内の変数の後に次の関数を追加します。

    def add_datadisk(compute_client):
        disk_creation = compute_client.disks.create_or_update(
            GROUP_NAME,
            'myDataDisk1',
            {
                'location': LOCATION,
                'disk_size_gb': 1,
                'creation_data': {
                    'create_option': DiskCreateOption.empty
                }
            }
        )
        data_disk = disk_creation.result()
        vm = compute_client.virtual_machines.get(GROUP_NAME, VM_NAME)
        add_result = vm.storage_profile.data_disks.append({
            'lun': 1,
            'name': 'myDataDisk1',
            'create_option': DiskCreateOption.attach,
            'managed_disk': {
                'id': data_disk.id
            }
        })
        add_result = compute_client.virtual_machines.create_or_update(
            GROUP_NAME,
            VM_NAME,
            vm)
    
        return add_result.result()
    
  2. 前に追加した関数を呼び出すには、.py ファイルの末尾にある if ステートメントの下に次のコードを追加します。

    add_result = add_datadisk(compute_client)
    print("------------------------------------------------------")
    print(add_result)
    input('Press enter to continue...')
    

リソースを削除する

Azure で使用されるリソースには課金されるため、不要になったリソースを削除することをお勧めします。 仮想マシンとすべてのサポート リソースを削除する場合は、リソース グループを削除する必要があります。

  1. リソース グループとすべてのリソースを削除するには、.py ファイル内の変数の後に次の関数を追加します。

    def delete_resources(resource_group_client):
        resource_group_client.resource_groups.delete(GROUP_NAME)
    
  2. 前に追加した関数を呼び出すには、.py ファイルの末尾にある if ステートメントの下に次のコードを追加します。

    delete_resources(resource_group_client)
    
  3. myPythonProject.py 保存します。

アプリケーションを実行する

  1. コンソール アプリケーションを実行するには、Visual Studio で [スタート] をクリックします。

  2. 各リソースの状態が返されたら、 Enter キー を押します。 状態情報に、 成功した プロビジョニングの状態が表示されます。 仮想マシンが作成されたら、作成したすべてのリソースを削除できます。 Enter キーを押してリソースの削除を開始する前に、Azure portal での作成の確認に数分かかることがあります。 Azure portal を開いている場合は、ブレードを更新して新しいリソースを表示する必要がある場合があります。

    このコンソール アプリケーションが最初から最後まで完全に実行されるまでに約 5 分かかります。 アプリケーションが完了してからすべてのリソースとリソース グループが削除されるまでに数分かかる場合があります。

次のステップ