Three Ways to Create an Azure Virtual Machine
There are many ways to create an Azure Virtual Machine. We’ll go over three easy ways to programmatically create an Azure VM.
1. Azure CLI
The Azure CLI is a versatile tool for creating and managing Azure resources. It can be downloaded and installed using one of the links on this page.
To authenticate using the Azure CLI, run the following command:
az login
This will open a browser which lets us login to an Azure account. Before we create a VM, we have to create an Azure Resource Group. Azure Resource Groups are collections of Azure resources that can be managed together.
To create a resource group, replace the placeholders in the following command and run it with the Azure CLI.
az group create --location <Location> --name <ResourceGroupName>
Replace the <Location> placeholder with the Azure region the VM will be created in. A complete list of Azure regions can be found here.
Replace the <ResourceGroupName> placeholder with the desired name for the resource group.
For example, to create a resource group with the name ThreeWaysToCreateAzureVM and the region EastUS, we can run the following command:
az group create --location EastUS --name ThreeWaysToCreateAzureVM
We can now create a VM by replacing the placeholders and running the following command using the Azure CLI:
az vm create ^ --resource-group <ResourceGroupName> ^ --location <Location> ^ --name <VMName> ^ --image <ImageName> ^ --size <Size> ^ --admin-username <AdminUserName> ^ --admin-password <AdminUserPassword>
Replace the <ResourceGroupName> placeholder with the name of the resource group we created in the previous command.
Replace the <Location> placeholder with the same region we created the resource group with in the previous command.
Replace the <VMName> placeholder with the desired name for the VM. It is recommended to include in the name, information such as the environment of VM (dev/QA/prod), location (EastUS/CanadaCentral) and the VM role (web/db).
Replace the <ImageName> placeholder with the name of the image which should be used to create the VM. The image will determine the operating system which the VM will run.
Replace the <Size> placeholder with the desired size for the VM. The size will determine how much RAM and CPU the VM will have.
Replace the <AdminUsername> placeholder with the username which will be used for RDP/SSH connections into the VM. Replace the <AdminPassword> with the corresponding password.
To create a VM with the resource group ThreeWaysToCreateAzureVM, the region EastUS, the name EastUSDev, the image win2019datacenter, the size Standard_DS2_v2, the RDP username testuser and password Abcdefg1234!, run the following command:
az vm create ^ --resource-group ThreeWaysToCreateAzureVM ^ --location EastUS ^ --name EastUSDev ^ --image win2019datacenter ^ --size Standard_DS2_v2 ^ --admin-username testuser ^ --admin-password Abcdefg1234!
2. Azure PowerShell
Azure PowerShell has many of the same capabilities as the Azure CLI. On any recent version of PowerShell on Windows 10, Azure PowerShell can be installed by running the following PowerShell command:
Install-Module -Name Az -AllowClobber -Scope AllUser
If running the above command doesn’t work, check here for more detailed instructions on installing Azure Powershell.
We can create an Azure VM by replacing the placeholders in the following PowerShell script and running it:
$VMAdminUsername = "<AdminUserName>" $VMAdminPassword = "<AdminPassword>" $credentials = New-Object System.Management.Automation.PSCredential($VMAdminUsername,$VMAdminPassword) New-AzVm ` -ResourceGroupName "<ResourceGroupName>" ` -Name "<Location>" ` -Location "<EastUSDev>" ` -Image "<Image>" ` -Size "<Size>" ` -Credential $credentials
To create a VM with the same specs as in the Azure CLI example, we could run the following command:
$VMAdminUsername = "testuser" $VMAdminPassword = ConvertTo-SecureString "Abcdefg1234!" -AsPlainText -Force $credentials = New-Object System.Management.Automation.PSCredential($VMAdminUsername,$VMAdminPassword) New-AzVm ` -ResourceGroupName "ThreeWaysToCreateAzureVMPowerShell" ` -Name "EastUSDev" ` -Location "EastUS" ` -Image "win2019datacenter" ` -Size "Standard_DS2_v2" ` -Credential $credentials
3. .NET SDK
If our logic for creating VMs is particularly complicated, then it would be nice to use a fully-featured programming language like C# as opposed to the Azure CLI or Azure PowerShell. We can do this by using the Azure .NET SDK.
Creating an Azure VM using the .NET SDK is requires a more involved setup. We will first create a service principal and then develop a .NET Core console application which creates the VM.
3.1 Create Service Principal
First let’s retrieve some information we will need later. Run the following Azure CLI command and take note of the tenantId and the id(subscription Id) in the response:
az account show
Next, we will create the service principal by running the command below. Take note of the appId and password in the response.
az ad sp create-for-rbac --name CreateAzureVM
By now we should have recorded four values which we will need in the next part, the subscription Id, tenant Id, app Id and password.
3.2 Develop Application
We will need the .NET Core SDK installed, preferably version 3.1.
Run the following commands to create a .NET Core console application:
dotnet new sln -n CreateVM dotnet new console -n "CreateVM" dotnet sln add CreateVM/CreateVM.csproj
After opening the solution in Visual Studio, we must add the Azure SDK to the project. To do so, run the following Nuget Package Manager Console command:
Install-Package Microsoft.Azure.Management.Fluent
Now we must supply our app with the service principal information we previously recorded. Let’s add a text file to the project called azureauth.txt with the following content:
subscription=<subscriptionId> client=<appId> key=<password> tenant=<tenantId> managementURI=https://management.core.windows.net/ baseURL=https://management.azure.com/ authURL=https://login.windows.net/ graphURL=https://graph.microsoft.com/
Replace the placeholders <subscriptionId>, <appId>, <password> and <tenantId> with the values we recorded in the previous part.
We can finally start writing the code to create our VM. Add the below method to the Program class in the program.cs file. It will instantiate the Azure client object which we can use to perform operations on Azure resources.
private static IAzure CreateClient() { var credentials = SdkContext.AzureCredentialsFactory .FromFile(@"<path of azureauth.txt>"); var azure = Azure .Configure() .WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic) .Authenticate(credentials) .WithDefaultSubscription(); return azure; }
Replace the <path of azureauth.txt> placeholder with the path of the azureauth.txt file e.g. C:\Code\Blogs\8-AzureVMs\CreateVM\azureauth.txt
Now, replace the Main method in the Program class with the following:
static void Main(string[] args) { var client = CreateClient(); client.VirtualMachines.Define("EastUSDev") .WithRegion(Region.USEast) .WithNewResourceGroup("ThreeWaysToCreateAzureVM") .WithNewPrimaryNetwork("10.0.0.0/16") .WithPrimaryPrivateIPAddressDynamic() .WithNewPrimaryPublicIPAddress("myipaddress") .WithLatestWindowsImage("MicrosoftWindowsServer", "WindowsServer", "2019-Datacenter") .WithAdminUsername("testuser") .WithAdminPassword("Standard_DS2_v2") .WithComputerName("EastUSDev") .WithSize("Standard_DS2_v2") .Create() ; }
If you run the console app now, it should create a VM with the same specs as the ones created in the Azure CLI and Azure PowerShell examples.