Search code examples
azureazure-resource-manager

azure python library equivalent of aws boto3


I have a sample code to create an EC2 instance using boto3 in python. Is there an equivalent for creating the same for azure VM ?

I understand there is pip install azure-mgmt-resource - but is this all that's required to get the task (creation of VM with the respective networking tasks) done ?


Solution

  • I understand there is pip install azure-mgmt-resource - but is this all that's required to get the task (creation of VM with the respective networking tasks) done ?

    To create a VM using a Python script, you may need the following module along with azure-mgmt-resource

    azure.identity 
    azure.mgmt.compute 
    azure.mgmt.network 
    

    I created a virtual machine using Python. Here is the updated code

        import os
        import random
        import string
        
        from azure.identity import DefaultAzureCredential
        from azure.mgmt.compute import ComputeManagementClient
        from azure.mgmt.network import NetworkManagementClient
        from azure.mgmt.resource import ResourceManagementClient
        
        
        def main():
        
            SUBSCRIPTION_ID = "<SUB_ID>"
            GROUP_NAME = "vm-RG"
            VIRTUAL_MACHINE_NAME = "venkatvm"
            SUBNET_NAME = "vmsubnet"
            INTERFACE_NAME = "vminterface"
            NETWORK_NAME = "vmnetwork"
            # VIRTUAL_MACHINE_EXTENSION_NAME = "virtualmachineextension"
        
            your_password = 'A1_' + ''.join(random.choice(string.ascii_lowercase) for i in range(8))
        
            # Create client
            # For other authentication approaches, please see: https://pypi.org/project/azure-identity/
            resource_client = ResourceManagementClient(
                credential=DefaultAzureCredential(),
                subscription_id=SUBSCRIPTION_ID
            )
            network_client = NetworkManagementClient(
                credential=DefaultAzureCredential(),
                subscription_id=SUBSCRIPTION_ID
            )
            compute_client = ComputeManagementClient(
                credential=DefaultAzureCredential(),
                subscription_id=SUBSCRIPTION_ID
            )
        
            # Create resource group
            resource_client.resource_groups.create_or_update(
                GROUP_NAME,
                {"location": "eastus"}
            )
        
            # Create virtual network
            network_client.virtual_networks.begin_create_or_update(
                GROUP_NAME,
                NETWORK_NAME,
                {
                    'location': "eastus",
                    'address_space': {
                        'address_prefixes': ['10.0.0.0/16']
                    }
                }
            ).result()
        
            subnet = network_client.subnets.begin_create_or_update(
                GROUP_NAME,
                NETWORK_NAME,
                SUBNET_NAME,
                {'address_prefix': '10.0.0.0/24'}
            ).result()
        
            # Create network interface
            network_client.network_interfaces.begin_create_or_update(
                GROUP_NAME,
                INTERFACE_NAME,
                {
                    'location': "eastus",
                    'ip_configurations': [{
                        'name': 'MyIpConfig',
                        'subnet': {
                            'id': subnet.id
                        }
                    }]
                } 
            ).result()
        
            # Create virtual machine
            vm = compute_client.virtual_machines.begin_create_or_update(
                GROUP_NAME,
                VIRTUAL_MACHINE_NAME,
                {
                  "location": "eastus",
                  "hardware_profile": {
                    "vm_size": "Standard_B8ms"
                  },
                  "storage_profile": {
                    "image_reference": {
                      "sku": "2016-Datacenter",
                      "publisher": "MicrosoftWindowsServer",
                      "version": "latest",
                      "offer": "WindowsServer"
                    },
                    "os_disk": {
                      "caching": "ReadWrite",
                      "managed_disk": {
                        "storage_account_type": "Standard_LRS"
                      },
                      "name": "myVMosdisk",
                      "create_option": "FromImage"
                    },
                    "data_disks": [
                      {
                        "disk_size_gb": "1023",
                        "create_option": "Empty",
                        "lun": "0"
                      },
                      {
                        "disk_size_gb": "1023",
                        "create_option": "Empty",
                        "lun": "1"
                      }
                    ]
                  },
                  "os_profile": {
                    "admin_username": "testuser",
                    "computer_name": "myVM",
                    "admin_password": your_password,
                    "windows_configuration": {
                      "enable_automatic_updates": True  # need automatic update for reimage
                    }
                  },
                  "network_profile": {
                    "network_interfaces": [
                      {
                        "id": "/subscriptions/" + SUBSCRIPTION_ID + "/resourceGroups/" + GROUP_NAME + "/providers/Microsoft.Network/networkInterfaces/" + INTERFACE_NAME + "",
                        # "id": NIC_ID,
                        "properties": {
                          "primary": True
                        }
                      }
                    ]
                  }
                }
            ).result()
            print("Create virtual machine:\n{}".format(vm))
        
        if __name__ == "__main__":
            main()
    

    enter image description here

    After running the code, the virtual machine has been created in the Azure Portal.

    enter image description here

    Reference : azure-samples-python-management