Following these two posts AZ-204 - Provisioning and Configuring Azure Virtual Machines and Az-204: Creating a VM programatically using Azure CLI this article will focus on how to create a VM in Azure using Azure Powershell.
Prerequisites
- Azure Subscription: Ensure you have an active Azure subscription. If you don't have one, you can sign up for a free Azure account.
- Install Azure Powershell: Install the Azure Powershell on your local machine. You can download and install it from here.
Steps to create a VM
Login to Azure
Open a command prompt or terminal and run the following command to log in to your Azure account. Connect-AzAccount is a cmdlet in the Azure PowerShell module that is used to authenticate and establish a connection to your Azure account. This cmdlet prompts you for your Azure credentials and then connects your PowerShell session to your Azure subscription. Once connected, you can manage your Azure resources using PowerShell commands. More about the cmdlet here.
Connect-AzAccount
Create a Resource Group
Create a resource group to logically group and manage your Azure resources. The New-AzResourceGroup cmdlet creates an Azure resource group. You can create a resource group by using just a name and location. More about on how to manage resource groups here.
New-AzResourceGroup -Name "demo-rg" -Location "centralus"
Define variables
In the step where variables are defined, you are essentially setting up parameters and values that will be used throughout your PowerShell script to configure and create an Azure virtual machine (VM).
# Replace 'YourUsername' and 'YourPassword' with the actual username and password
$username = 'YourUsername'
$password = 'YourStrongPassword' | ConvertTo-SecureString -AsPlainText -Force
$credentials = New-Object System.Management.Automation.PSCredential($username, $password)
This approach is suitable for scripts where you want to include the credentials directly in the script. However, keep in mind the security implications of storing passwords in scripts, especially in production scenarios. If possible, consider using Azure Key Vault to securely store and retrieve secrets.
Create a virtual machine
New-AzVM -ResourceGroupName "demo=rg" -Name "demo-win-az" -Image "Win2019Datacenter" -Credential $credentials
This script creates a basic Windows VM in a new resource group, but additionally yo can add a virtual network, subnet, public IP address, network security group, and a network interface card. You can adjust it according to your specific needs. More about this cmdlet here.
Top comments (0)