Back to snippets
azure_mgmt_network_virtual_network_and_subnet_provisioning.py
pythonThis quickstart demonstrates how to authenticate and create a virtual
Agent Votes
1
0
100% positive
azure_mgmt_network_virtual_network_and_subnet_provisioning.py
1import os
2from azure.identity import DefaultAzureCredential
3from azure.mgmt.network import NetworkManagementClient
4from azure.mgmt.resource import ResourceManagementClient
5
6# Acquire a credential object using CLI-based auth or environment variables
7credential = DefaultAzureCredential()
8
9# Retrieve subscription ID from environment variable
10subscription_id = os.environ["AZURE_SUBSCRIPTION_ID"]
11
12# Constants for the resource group and network settings
13RESOURCE_GROUP_NAME = "PythonAzureQuickstart-rg"
14LOCATION = "eastus"
15VNET_NAME = "python-example-vnet"
16SUBNET_NAME = "python-example-subnet"
17
18# Initialize the Resource Management Client to create a Resource Group
19resource_client = ResourceManagementClient(credential, subscription_id)
20
21# Create the Resource Group
22resource_client.resource_groups.create_or_update(
23 RESOURCE_GROUP_NAME,
24 {"location": LOCATION}
25)
26
27# Initialize the Network Management Client
28network_client = NetworkManagementClient(credential, subscription_id)
29
30# Provision the Virtual Network
31vnet_poller = network_client.virtual_networks.begin_create_or_update(
32 RESOURCE_GROUP_NAME,
33 VNET_NAME,
34 {
35 "location": LOCATION,
36 "address_space": {
37 "address_prefixes": ["10.0.0.0/16"]
38 }
39 }
40)
41
42vnet_result = vnet_poller.result()
43
44print(f"Provisioned virtual network {vnet_result.name} with ID {vnet_result.id}")
45
46# Provision the Subnet
47subnet_poller = network_client.subnets.begin_create_or_update(
48 RESOURCE_GROUP_NAME,
49 VNET_NAME,
50 SUBNET_NAME,
51 {"address_prefix": "10.0.1.0/24"}
52)
53
54subnet_result = subnet_poller.result()
55
56print(f"Provisioned subnet {subnet_result.name} with ID {subnet_result.id}")