ローカル開発環境で Azure SDK for Python を利用する

ローカル開発環境で Azure SDK for Python を利用するサンプルソースコードです。

## この記事の目的

ローカル開発環境で Azure SDK for Python を利用して下記操作を実施するサンプルコードです。  

- VM及び関連リソースの作成
- VM及び関連リソースの削除

## 👇これより先は下記記事の内容を前提とします

- [ローカル開発環境でAzure SDK for Pythonを利用するための認証設定](https://docusaurus.plant11.com/cloud/azure_sdk_python_certificate)
- [Azure ライブラリを使用して仮想マシンを作成する](https://learn.microsoft.com/ja-jp/azure/developer/python/sdk/examples/azure-sdk-example-virtual-machines?tabs=cmd)

## **azure python sdk モジュール**のインストール

**azure sdk**をPythonから利用するため、下記コマンドでモジュールをインストールします。  

```text
pip install azure.identity
pip install azure.mgmt.compute
pip install azure.mgmt.network
pip install azure.mgmt.resource
```

## VM及び関連リソースの作成(サンプルソース)

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

from azure.mgmt.network.models import SecurityRule
from azure.mgmt.network.models import NetworkSecurityGroup
from azure.mgmt.compute.models import VirtualMachineNetworkInterfaceConfiguration

# credential object
credential = DefaultAzureCredential()

SUBSCRIPTION_ID = "****-****-****-****-****"
RESOURCE_GROUP_NAME = "resource_group_for_python"
LOCATION = "japaneast"

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"

# https://learn.microsoft.com/ja-jp/python/api/azure-mgmt-network/azure.mgmt.network.networkmanagementclient?view=azure-python
network_client = NetworkManagementClient(credential, SUBSCRIPTION_ID)

# https://learn.microsoft.com/ja-jp/python/api/azure-mgmt-network/azure.mgmt.network.operations.virtualnetworksoperations?view=azure-python
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}")

# https://learn.microsoft.com/ja-jp/python/api/azure-mgmt-network/azure.mgmt.network.operations.subnetsoperations?view=azure-python
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} ")

# https://learn.microsoft.com/ja-jp/python/api/azure-mgmt-network/azure.mgmt.network.operations.publicipaddressesoperations?view=azure-python
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} ")
print(f"ip address : {ip_address_result.ip_address}")

# https://learn.microsoft.com/ja-jp/python/api/azure-mgmt-network/azure.mgmt.network.models.securityrule?view=azure-python
nsg_rule = SecurityRule(
    name="AllowSSH",
    access="Allow",
    protocol="Tcp",
    destination_port_range="22",
    destination_address_prefix="*",
    direction="Inbound",
    source_port_range="*",
    source_address_prefix="*",
    priority=100
)

# https://learn.microsoft.com/ja-jp/python/api/azure-mgmt-network/azure.mgmt.network.models.networksecuritygroup?view=azure-python
nsg = NetworkSecurityGroup(
    location=LOCATION,
    security_rules=[nsg_rule],
)

NSG_NAME = "python-example-nsg"

# https://learn.microsoft.com/ja-jp/python/api/azure-mgmt-network/azure.mgmt.network.operations.networksecuritygroupsoperations?view=azure-python#azure-mgmt-network-operations-networksecuritygroupsoperations-begin-create-or-update
poller = network_client.network_security_groups.begin_create_or_update(
    RESOURCE_GROUP_NAME,
    NSG_NAME,
    nsg,    
)
nsg_result = poller.result()
print(f"Provisioned network security group {nsg_result} ")

# https://learn.microsoft.com/ja-jp/python/api/azure-mgmt-network/azure.mgmt.network.operations.networkinterfacesoperations?view=azure-python
poller = network_client.network_interfaces.begin_create_or_update(
    RESOURCE_GROUP_NAME,
    NIC_NAME,
    {
        "location": LOCATION,
        "network_security_group": nsg_result,
        "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}")

VM_NAME = "ExampleVM"
USERNAME = "azureuser"
PASSWORD = "admin!12345"
DISK_NAME = "python-example-disk"

# https://learn.microsoft.com/ja-jp/python/api/azure-mgmt-compute/azure.mgmt.compute.computemanagementclient?view=azure-python
compute_client = ComputeManagementClient(credential, SUBSCRIPTION_ID)

# https://learn.microsoft.com/ja-jp/python/api/azure-mgmt-compute/azure.mgmt.compute.v2023_07_01.operations.virtualmachinesoperations?view=azure-python
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",
            },
            "os_disk": {
                "create_option": "FromImage",
                "name": DISK_NAME
            }
        },
        "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}")
```

## VM及び関連リソースの削除(サンプルソース)

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

# credential object
credential = DefaultAzureCredential()

SUBSCRIPTION_ID = "****-****-****-****-****"
RESOURCE_GROUP_NAME = "resource_group_for_python"
LOCATION = "japaneast"

VM_NAME = "ExampleVM"

# https://learn.microsoft.com/ja-jp/python/api/azure-mgmt-compute/azure.mgmt.compute.computemanagementclient?view=azure-python
compute_client = ComputeManagementClient(credential, SUBSCRIPTION_ID)

# https://learn.microsoft.com/ja-jp/python/api/azure-mgmt-compute/azure.mgmt.compute.v2023_07_01.operations.virtualmachinesoperations?view=azure-python
poller = compute_client.virtual_machines.begin_delete(
    RESOURCE_GROUP_NAME,
    VM_NAME,
)
vm_result = poller.result()
print(f"virtual machine deleted")

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"
DISK_NAME = "python-example-disk"

# https://learn.microsoft.com/ja-jp/python/api/azure-mgmt-network/azure.mgmt.network.networkmanagementclient?view=azure-python
network_client = NetworkManagementClient(credential, SUBSCRIPTION_ID)

# https://learn.microsoft.com/ja-jp/python/api/azure-mgmt-network/azure.mgmt.network.operations.networkinterfacesoperations?view=azure-python
poller = network_client.network_interfaces.begin_delete(
    RESOURCE_GROUP_NAME,
    NIC_NAME,
)
nic_result = poller.result()
print(f"network interface deleted")

# https://learn.microsoft.com/ja-jp/python/api/azure-mgmt-network/azure.mgmt.network.operations.publicipaddressesoperations?view=azure-python
poller = network_client.public_ip_addresses.begin_delete(
    RESOURCE_GROUP_NAME,
    IP_NAME,
)
ip_address_result = poller.result()
print(f"public ip address deleted")

# https://learn.microsoft.com/ja-jp/python/api/azure-mgmt-compute/azure.mgmt.compute.v2023_04_02.operations.disksoperations?view=azure-python
poller = compute_client.disks.begin_delete(
    RESOURCE_GROUP_NAME,
    DISK_NAME,   
)
disk_result = poller.result()
print(f"disk deleted")

# https://learn.microsoft.com/ja-jp/python/api/azure-mgmt-network/azure.mgmt.network.operations.virtualnetworksoperations?view=azure-python
poller = network_client.virtual_networks.begin_delete(
    RESOURCE_GROUP_NAME,
    VNET_NAME,
)
virtual_network_result = poller.result()
print(f"virtual network deleted")

NSG_NAME = "python-example-nsg"

# https://learn.microsoft.com/ja-jp/python/api/azure-mgmt-network/azure.mgmt.network.operations.networksecuritygroupsoperations?view=azure-python#azure-mgmt-network-operations-networksecuritygroupsoperations-begin-create-or-update
poller = network_client.network_security_groups.begin_delete(
    RESOURCE_GROUP_NAME,
    NSG_NAME,
)
network_security_group_result = poller.result()
print(f"network security group deleted")
```

## 👇関連記事

- [ローカル開発環境でAzure SDK for Pythonを利用するための認証設定](https://docusaurus.plant11.com/cloud/azure_sdk_python_certificate)

## 👇参考URL

- [サービス プリンシパルを使用したローカル開発時に Azure サービスに対して Python アプリを認証する](https://learn.microsoft.com/ja-jp/azure/developer/python/sdk/authentication-local-development-service-principal?tabs=azure-portal)
- [NetworkManagementClient](https://learn.microsoft.com/ja-jp/python/api/azure-mgmt-network/azure.mgmt.network.networkmanagementclient?view=azure-python)
- [VirtualNetworksOperations](https://learn.microsoft.com/ja-jp/python/api/azure-mgmt-network/azure.mgmt.network.operations.virtualnetworksoperations?view=azure-python)
- [SubnetsOperations](https://learn.microsoft.com/ja-jp/python/api/azure-mgmt-network/azure.mgmt.network.operations.subnetsoperations?view=azure-python)
- [PublicIPAddressesOperations](https://learn.microsoft.com/ja-jp/python/api/azure-mgmt-network/azure.mgmt.network.operations.publicipaddressesoperations?view=azure-python)
- [NetworkSecurityGroupsOperations](https://learn.microsoft.com/ja-jp/python/api/azure-mgmt-network/azure.mgmt.network.operations.networksecuritygroupsoperations?view=azure-python)
- [NetworkInterfacesOperations](https://learn.microsoft.com/ja-jp/python/api/azure-mgmt-network/azure.mgmt.network.operations.networkinterfacesoperations?view=azure-python)
- [ComputeManagementClient](https://learn.microsoft.com/ja-jp/python/api/azure-mgmt-compute/azure.mgmt.compute.computemanagementclient?view=azure-python)
- [VirtualMachinesOperations](https://learn.microsoft.com/ja-jp/python/api/azure-mgmt-compute/azure.mgmt.compute.v2023_07_01.operations.virtualmachinesoperations?view=azure-python)
- [DisksOperations](https://learn.microsoft.com/ja-jp/python/api/azure-mgmt-compute/azure.mgmt.compute.v2023_04_02.operations.disksoperations?view=azure-python)

[keywords]  
Azure SDK python 認証 アプリケーションサービスプリンシパル

[ローカル開発環境で Azure SDK for Python を利用する](https://docusaurus.plant11.com/python/azure_sdk_python)

更新日:2023/11/07