次の方法で共有


例: Azure ライブラリを使用して仮想マシンを作成する

この記事では、Python スクリプトで Azure SDK 管理ライブラリを使用して、Linux 仮想マシンを含むリソース グループを作成する方法について説明します。

同等の Azure CLI コマンドについては、この記事の後半で説明します。 Azure portal を使用する場合は、 Linux VM の作成 と Windows VM の 作成に関するページを参照してください。

コードを使用して仮想マシンを作成することは、仮想マシンに必要な他のリソースのプロビジョニングを含むマルチステップ プロセスです。 コマンド ラインからこのようなコードを実行するだけの場合は、 az vm create コマンドを使用する方がはるかに簡単です。これにより、省略することを選択した設定の既定値でこれらのセカンダリ リソースが自動的にプロビジョニングされます。 必要な引数は、リソース グループ、VM 名、イメージ名、ログイン資格情報のみです。 詳細については、「 Azure CLI を使用した仮想マシンの簡易作成」を参照してください。

1: ローカル開発環境を設定する

まだ行っていない場合は、このコードを実行できる環境を設定します。 いくつかのオプションを次に示します。

#!/bin/bash
# Create a virtual environment
python -m venv .venv
# Activate the virtual environment
source .venv/Scripts/activate # only required for Windows (Git Bash)

2: 必要な Azure ライブラリ パッケージをインストールする

このスクリプトで必要な Azure SDK 管理パッケージを指定する requirements.txt ファイルを作成します。

azure-mgmt-resource
azure-mgmt-compute
azure-mgmt-network
azure-identity

次に、requirements.txtで指定された管理ライブラリ インストールします。

pip install -r requirements.txt

3: 仮想マシンを作成するコードを記述する

次のコードを 使用して、provision_vm.py という名前の Python ファイルを作成します。 コメントでは、詳細について説明します。

# Import the needed credential and management objects from the libraries.
import os

from azure.identity import DefaultAzureCredential
from azure.mgmt.compute import ComputeManagementClient
from azure.mgmt.network import NetworkManagementClient
from azure.mgmt.resource import ResourceManagementClient

print(
    "Provisioning a virtual machine...some operations might take a \
minute or two."
)

# Acquire a credential object.
credential = DefaultAzureCredential()

# Retrieve subscription ID from environment variable.
subscription_id = os.environ["AZURE_SUBSCRIPTION_ID"]


# Step 1: Provision a resource group

# Obtain the management object for resources.
resource_client = ResourceManagementClient(credential, subscription_id)

# Constants we need in multiple places: the resource group name and
# the region in which we provision resources. You can change these
# values however you want.
RESOURCE_GROUP_NAME = "PythonAzureExample-VM-rg"
LOCATION = "westus2"

# Provision the resource group.
rg_result = resource_client.resource_groups.create_or_update(
    RESOURCE_GROUP_NAME, {"___location": LOCATION}
)

print(
    f"Provisioned resource group {rg_result.name} in the \
{rg_result.___location} region"
)

# For details on the previous code, see Example: Provision a resource
# group at https://learn.microsoft.com/azure/developer/python/
# azure-sdk-example-resource-group

# Step 2: provision a virtual network

# A virtual machine requires a network interface client (NIC). A NIC
# requires a virtual network and subnet along with an IP address.
# Therefore we must provision these downstream components first, then
# provision the NIC, after which we can provision the VM.

# Network and IP address names
VNET_NAME = "python-example-vnet"
SUBNET_NAME = "python-example-subnet"
IP_NAME = "python-example-ip"
IP_CONFIG_NAME = "python-example-ip-config"
NIC_NAME = "python-example-nic"

# Obtain the management object for networks
network_client = NetworkManagementClient(credential, subscription_id)

# Provision the virtual network and wait for completion
poller = network_client.virtual_networks.begin_create_or_update(
    RESOURCE_GROUP_NAME,
    VNET_NAME,
    {
        "___location": LOCATION,
        "address_space": {"address_prefixes": ["10.0.0.0/16"]},
    },
)

vnet_result = poller.result()

print(
    f"Provisioned virtual network {vnet_result.name} with address \
prefixes {vnet_result.address_space.address_prefixes}"
)

# Step 3: Provision the subnet and wait for completion
poller = network_client.subnets.begin_create_or_update(
    RESOURCE_GROUP_NAME,
    VNET_NAME,
    SUBNET_NAME,
    {"address_prefix": "10.0.0.0/24"},
)
subnet_result = poller.result()

print(
    f"Provisioned virtual subnet {subnet_result.name} with address \
prefix {subnet_result.address_prefix}"
)

# Step 4: Provision an IP address and wait for completion
poller = network_client.public_ip_addresses.begin_create_or_update(
    RESOURCE_GROUP_NAME,
    IP_NAME,
    {
        "___location": LOCATION,
        "sku": {"name": "Standard"},
        "public_ip_allocation_method": "Static",
        "public_ip_address_version": "IPV4",
    },
)

ip_address_result = poller.result()

print(
    f"Provisioned public IP address {ip_address_result.name} \
with address {ip_address_result.ip_address}"
)

# Step 5: Provision the network interface client
poller = network_client.network_interfaces.begin_create_or_update(
    RESOURCE_GROUP_NAME,
    NIC_NAME,
    {
        "___location": LOCATION,
        "ip_configurations": [
            {
                "name": IP_CONFIG_NAME,
                "subnet": {"id": subnet_result.id},
                "public_ip_address": {"id": ip_address_result.id},
            }
        ],
    },
)

nic_result = poller.result()

print(f"Provisioned network interface client {nic_result.name}")

# Step 6: Provision the virtual machine

# Obtain the management object for virtual machines
compute_client = ComputeManagementClient(credential, subscription_id)

VM_NAME = "ExampleVM"
USERNAME = "azureuser"
PASSWORD = "ChangePa$$w0rd24"

print(
    f"Provisioning virtual machine {VM_NAME}; this operation might \
take a few minutes."
)

# Provision the VM specifying only minimal arguments, which defaults
# to an Ubuntu 18.04 VM on a Standard DS1 v2 plan with a public IP address
# and a default virtual network/subnet.

poller = compute_client.virtual_machines.begin_create_or_update(
    RESOURCE_GROUP_NAME,
    VM_NAME,
    {
        "___location": LOCATION,
        "storage_profile": {
            "image_reference": {
                "publisher": "Canonical",
                "offer": "UbuntuServer",
                "sku": "16.04.0-LTS",
                "version": "latest",
            }
        },
        "hardware_profile": {"vm_size": "Standard_DS1_v2"},
        "os_profile": {
            "computer_name": VM_NAME,
            "admin_username": USERNAME,
            "admin_password": PASSWORD,
        },
        "network_profile": {
            "network_interfaces": [
                {
                    "id": nic_result.id,
                }
            ]
        },
    },
)

vm_result = poller.result()

print(f"Provisioned virtual machine {vm_result.name}")

コード内の認証

この記事の後半では、Azure CLI を使用して Azure にサインインしてサンプル コードを実行します。 アカウントに、Azure サブスクリプションでリソース グループとストレージ リソースを作成するための十分なアクセス許可がある場合、スクリプトは追加の構成なしで正常に実行されます。

運用環境でこのコードを使用するには、環境変数を設定してサービス プリンシパルを使用して認証します。 この方法により、対話型ログインに依存することなく、セキュリティで保護された自動アクセスが可能になります。 詳細なガイダンスについては、 Azure サービスで Python アプリを認証する方法に関するページを参照してください。

リソース グループとストレージ アカウントを作成するための十分なアクセス許可を持つロールがサービス プリンシパルに割り当てられていることを確認します。 たとえば、サブスクリプション レベルで共同作成者ロールを割り当てると、必要なアクセス権が提供されます。 ロールの割り当ての詳細については、 Azure でのロールベースのアクセス制御 (RBAC) に関するページを参照してください。

4. スクリプトを実行する

  1. まだサインインしていない場合は、Azure CLI を使用して Azure にサインインします。

    az login
    
  2. AZURE_SUBSCRIPTION_ID環境変数をサブスクリプション ID に設定します。 ( az account show コマンドを実行し、出力の id プロパティからサブスクリプション ID を取得できます)。

    export AZURE_SUBSCRIPTION_ID=$(az account show --query id -o tsv)
    
  3. 次のスクリプトを実行します。

    python provision_vm.py
    

プロビジョニング プロセスが完了するまでに数分かかります。

5. リソースを確認する

Azure portal を開き、"PythonAzureExample-VM-rg" リソース グループに移動し、仮想マシン、仮想ディスク、ネットワーク セキュリティ グループ、パブリック IP アドレス、ネットワーク インターフェイス、仮想ネットワークをメモします。

仮想マシンと関連リソースを示す新しいリソース グループの Azure portal ページ

Azure CLI を使用して、 az vm list コマンドを使用して VM が存在することを確認することもできます。

az vm list --resource-group PythonAzureExample-VM-rg

同等の Azure CLI コマンド

# Provision the resource group

az group create -n PythonAzureExample-VM-rg -l westus2

# Provision a virtual network and subnet

az network vnet create -g PythonAzureExample-VM-rg -n python-example-vnet \
    --address-prefix 10.0.0.0/16 --subnet-name python-example-subnet \
    --subnet-prefix 10.0.0.0/24

# Provision a public IP address

az network public-ip create -g PythonAzureExample-VM-rg -n python-example-ip \
    --allocation-method Dynamic --version IPv4

# Provision a network interface client

az network nic create -g PythonAzureExample-VM-rg --vnet-name python-example-vnet \
    --subnet python-example-subnet -n python-example-nic \
    --public-ip-address python-example-ip

# Provision the virtual machine

az vm create -g PythonAzureExample-VM-rg -n ExampleVM -l "westus2" \
    --nics python-example-nic --image UbuntuLTS --public-ip-sku Standard \
    --admin-username azureuser --admin-password ChangePa$$w0rd24

容量制限に関するエラーが発生した場合は、別のサイズまたはリージョンを試すことができます。 詳細については、「 使用できない SKU のエラーを解決する」を参照してください

6: リソースをクリーンアップする

この記事で作成した仮想マシンとネットワークを引き続き使用する場合は、リソースをそのまま使用します。 それ以外の場合は、 az group delete コマンドを実行してリソース グループを削除します。

リソース グループではサブスクリプションに継続的な料金は発生しませんが、仮想マシンなどのグループに含まれるリソースには引き続き料金が発生する可能性があります。 アクティブに使用していないグループをクリーンアップすることをお勧めします。 --no-wait引数を使用すると、操作の完了を待たずにコマンドをすぐに返すことができます。

az group delete -n PythonAzureExample-VM-rg --no-wait

ResourceManagementClient.resource_groups.begin_delete メソッドを使用して、コードからリソース グループを削除することもできます。 「例: リソース グループを作成する」のコードは、使用方法を示しています。

こちらも参照ください

次のリソースには、Python を使用して仮想マシンを作成する包括的な例が含まれています。

  • Azure Virtual Machines 管理サンプル - Python (GitHub)。 このサンプルでは、VM の開始と再起動、VM の停止と削除、ディスク サイズの増加、データ ディスクの管理など、より多くの管理操作を示します。