0% found this document useful (0 votes)
622 views1,159 pages

winPS createManageVMs PDF

Uploaded by

mohanar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
622 views1,159 pages

winPS createManageVMs PDF

Uploaded by

mohanar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1159

Contents

Windows VMs Documentation


Overview
About Virtual Machines
Quickstarts
Create VM - Portal
Create VM - PowerShell
Create VM - Azure CLI
Tutorials
1 - Create / manage a VM
2 - Create / manage disks
3 - Automate configuration
4 - Create VM images
5 - Highly available VMs
6 - Create a scale set
7 - Load balance VMs
8 - Manage networking
9 - Backup virtual machines
10 - Manage VMs
11 - Track and update VMs
12 - Monitor VMs
13 - Manage VM security
14 - Install a SQL\IIS\.NET stack
15 - Secure web server with SSL
Samples
PowerShell index
PowerShell
Create
Quick
Fully configured VM
Highly available VM
Custom script example
Use DSC
VM from VHD upload
Attach an OS disk
VM from snapshot
Manage storage
Create a managed disk from a VHD
Create a managed disk from a snapshot
Copy a managed disk
Export a snapshot as a VHD to a storage account
Export the VHD of a managed disk to a storage account
Create a snapshot from a VHD
Copy a snapshot
Secure
Encrypt a VM and its data disks
Monitor
Azure Monitor
Collect details about all VMs in a subscription
Azure CLI index
CLI
Create
Quick
Fully configured VM
Highly available VM
Custom script example
Use DSC configuration
Manage storage
Create managed disk from a VHD
Create a managed disk from a snapshot
Copy managed disk
Export a snapshot as VHD to a storage account
Export the VHD of a managed disk to a storage account
Copy snapshot
Network
Secure network traffic between VMs
Secure
Encrypt a VM and data disks
Monitor
Azure Monitor
Concepts
Azure Resource Manager
Regions
Availability and performance
Availability
Co-location
Network performance
VM types and sizes
VM sizes
Generation 2 VMs
General purpose
Overview
Av2-series
B-series burstable
DCv2-series
Dv2 and DSv2-series
Dv3 and Dsv3-series
Dav4 and Dasv4-series
Compute optimized
Overview
Fsv2-series
Memory optimized
Overview
Dv2 and DSv2-series 11-15
Ev3 and Esv3-series
Eav4 and Easv4-series
M-series
Mv2-series
Constrained vCPUs
Storage optimized
Overview
Lsv2-series
Optimize performance
Accelerated compute
GPU optimized
Overview
NC-series
NCv2-series
NCv3-series
ND-series
NDv2-series
NV-series
NVv3-series
NVv4-series
Setup GPU drivers
Setup AMD GPU drivers
High performance compute
Overview
H-series
HB-series
HBv2-series
HC-series
Reserved instances
Prepay for VMs
What are Azure reservations?
VM instance size flexibility
Spot VMs
Previous generations
Isolated sizes
Azure compute units (ACU)
Benchmark scores
vCPU quotas
Reserved instances
Prepay for VMs
What are Azure reservations?
VM instance size flexibility
Dedicated hosts
Maintenance and updates
Disk storage
Introduction to managed disks
Select a disk type for IaaS VMs
Encryption
Disk Storage reservations
Designing for high performance
Disk bursting
Scalability targets for disks
Backup and disaster recovery for disks
Shared disks
Ephemeral OS disks
Networking
Scale sets
Infrastructure automation
Security
Security and policy
Azure Disk Encryption
Built-in security controls
States and lifecycle
Monitoring
Backup and recovery
Infrastructure example
How-to guides
Create VMs
Use dedicated hosts
PowerShell
Portal
Deploy spot VMs
Portal
PowerShell
Template
Error codes
Use C#
Use specialized disk
Portal
PowerShell
Use a template with C#
Create VM with Chef
Use Java
Use Python
Use a template
Connect to a VM
Use Azure Hybrid Benefit license
Use Multitenant Hosting Rights for Windows 10
Secure VMs
Recommendations
Just-in-time access
Encrypt
Disk encryption scenarios for Windows
VM encryption with Azure CLI
VM encryption with Azure PowerShell
VM encryption with Azure portal
Key vault for Azure Disk Encryption
Disk encryption sample scripts
Disk encryption troubleshooting
Disk encryption FAQ
Disk encryption - previous version (AAD)
Overview
Key vault for Azure Disk Encryption
Disk encryption scenarios for Windows
Use WinRM
Use access controls
Use policies
Create a Key Vault
Protect VMs
Disaster recovery
Back up VMs
Back up a single VM
Back up multiple VMs
Restore a disk
Restore individual files
Set up disaster recovery for VMs
Enable disaster recovery for a VM
Run a disaster recovery drill for a VM
Fail over a VM to another region
Manage VMs
VM usage
Common PowerShell tasks
Change VM size
Swap the OS disk
Tag a VM
Time sync
Run scripts on a VM
Custom Script Extension
Run Command
Change temp drive letter
Change availability set
Download template
Azure VM agent
Mitigating speculative execution
Monitor metadata
Enable nested virtualization
Platform maintenance
Maintenance notifications
Overview
CLI
Portal
PowerShell
Maintenance control
PowerShell
CLI
Scheduled events
Windows scheduled event service
Monitor VMs
Azure Monitor for VMs
Create metric alerts
Create log alerts
Use Images
Shared images
Overview
PowerShell
Portal
CLI
App registration for sharing
Troubleshoot shared images
Image builder (preview)
Overview
Use Azure CLI
Build for image galleries
Update an existing image
Store scripts
Template reference
Troubleshoot
Find and use images
Prepare VM for upload
Capture VM to image
Use generalized image
Build image with Packer
Use Windows client images
Download existing disk
Availability and scale
Virtual Machine Scale Sets
High availability
Create a proximity placement group
Portal
PowerShell
Vertically scale
PowerShell
Portal
Use automation tools
Chef
Publish Web App from Visual Studio
Run applications
SQL Server
MongoDB
SAP on Azure
MATLAB cluster
Visual Studio
High Performance Computing (HPC)
HPC Pack 2016 cluster
HPC Pack 2016 Azure Active Directory integration
HPC Pack 2012 R2 head node
Submit on-prem jobs to HPC Pack 2012 R2
Excel on HPC Pack
Manage storage
Add a disk
Azure PowerShell
Azure portal
Detach a disk
Deploy disks with template
Enable shared disks
Upload a vhd to a disk - PowerShell
Resize a disk
Use Storage Explorer to manage disks
Snapshot a disk
Reserve Disk Storage
Create an incremental snapshot
Back up unmanaged disks
Migration and conversion
Convert disk between Standard and Premium
Migrate to Premium storage with Azure Site Recovery
Migrate to Managed Disks
Unmanaged VM to Managed Disks
Performance
Enable write accelerator
Using ultra disks
Benchmark a disk
Find unattached disks
Disks FAQs
Manage networking
Create virtual network
Open ports to a VM
Azure portal
Azure PowerShell
Assign public IP address
Use multiple NICs
Use accelerated networking
Assign public DNS name
DNS resolution
Configure managed identities
Portal
CLI
PowerShell
Azure Resource Manager Template
REST
Azure SDKs
Use VM extensions
Move and migrate VMs
Change subscription or resource group
Move regions
Move to an availability zone
Migrate AWS and on-premises VMs
Upload on-prem VM
From Amazon Web Services (AWS)
Use Azure Site Recovery
Migrate from Classic to Azure Resource Manager
Deep Dive on migration
Plan for migration
Migrate using PowerShell
Common migration errors
Community tools for migration
FAQ
Troubleshoot
Reference
Azure CLI
Azure PowerShell
.NET
Java
Node.js
Python
Compute REST
Managed Disks REST
Resource Manager template
Resources
Author templates
Build your skills with Microsoft Learn
Azure Roadmap
Community templates
Pricing
Regional availability
Stack Overflow
Videos
FAQ
Windows virtual machines in Azure
1/10/2020 • 5 minutes to read • Edit Online

Azure Virtual Machines (VM ) is one of several types of on-demand, scalable computing resources that Azure
offers. Typically, you choose a VM when you need more control over the computing environment than the other
choices offer. This article gives you information about what you should consider before you create a VM, how you
create it, and how you manage it.
An Azure VM gives you the flexibility of virtualization without having to buy and maintain the physical hardware
that runs it. However, you still need to maintain the VM by performing tasks, such as configuring, patching, and
installing the software that runs on it.
Azure virtual machines can be used in various ways. Some examples are:
Development and test – Azure VMs offer a quick and easy way to create a computer with specific
configurations required to code and test an application.
Applications in the cloud – Because demand for your application can fluctuate, it might make economic
sense to run it on a VM in Azure. You pay for extra VMs when you need them and shut them down when you
don’t.
Extended datacenter – Virtual machines in an Azure virtual network can easily be connected to your
organization’s network.
The number of VMs that your application uses can scale up and out to whatever is required to meet your needs.

What do I need to think about before creating a VM?


There are always a multitude of design considerations when you build out an application infrastructure in Azure.
These aspects of a VM are important to think about before you start:
The names of your application resources
The location where the resources are stored
The size of the VM
The maximum number of VMs that can be created
The operating system that the VM runs
The configuration of the VM after it starts
The related resources that the VM needs
Locations
All resources created in Azure are distributed across multiple geographical regions around the world. Usually, the
region is called location when you create a VM. For a VM, the location specifies where the virtual hard disks are
stored.
This table shows some of the ways you can get a list of available locations.

METHOD DESCRIPTION

Azure portal Select a location from the list when you create a VM.

Azure PowerShell Use the Get-AzLocation command.


METHOD DESCRIPTION

REST API Use the List locations operation.

Azure CLI Use the az account list-locations operation.

Availability
Azure announced an industry leading single instance virtual machine Service Level Agreement of 99.9% provided
you deploy the VM with premium storage for all disks. In order for your deployment to qualify for the standard
99.95% VM Service Level Agreement, you still need to deploy two or more VMs running your workload inside of
an availability set. An availability set ensures that your VMs are distributed across multiple fault domains in the
Azure data centers as well as deployed onto hosts with different maintenance windows. The full Azure SLA
explains the guaranteed availability of Azure as a whole.

VM size
The size of the VM that you use is determined by the workload that you want to run. The size that you choose then
determines factors such as processing power, memory, and storage capacity. Azure offers a wide variety of sizes to
support many types of uses.
Azure charges an hourly price based on the VM’s size and operating system. For partial hours, Azure charges only
for the minutes used. Storage is priced and charged separately.

VM Limits
Your subscription has default quota limits in place that could impact the deployment of many VMs for your
project. The current limit on a per subscription basis is 20 VMs per region. Limits can be raised by filing a support
ticket requesting an increase
Operating system disks and images
Virtual machines use virtual hard disks (VHDs) to store their operating system (OS ) and data. VHDs are also used
for the images you can choose from to install an OS.
Azure provides many marketplace images to use with various versions and types of Windows Server operating
systems. Marketplace images are identified by image publisher, offer, sku, and version (typically version is specified
as latest). Only 64-bit operating systems are supported. For more information on the supported guest operating
systems, roles, and features, see Microsoft server software support for Microsoft Azure virtual machines .
This table shows some ways that you can find the information for an image.

METHOD DESCRIPTION

Azure portal The values are automatically specified for you when you select
an image to use.

Azure PowerShell Get-AzVMImagePublisher -Location location


Get-AzVMImageOffer -Location location -Publisher
publisherName
Get-AzVMImageSku -Location location -Publisher
publisherName -Offer offerName

REST APIs List image publishers


List image offers
List image skus
METHOD DESCRIPTION

Azure CLI az vm image list-publishers --location location


az vm image list-offers --location location --publisher
publisherName
az vm image list-skus --location location --publisher
publisherName --offer offerName

You can choose to upload and use your own image and when you do, the publisher name, offer, and sku aren’t
used.
Extensions
VM extensions give your VM additional capabilities through post deployment configuration and automated tasks.
These common tasks can be accomplished using extensions:
Run custom scripts – The Custom Script Extension helps you configure workloads on the VM by running
your script when the VM is provisioned.
Deploy and manage configurations – The PowerShell Desired State Configuration (DSC ) Extension helps
you set up DSC on a VM to manage configurations and environments.
Collect diagnostics data – The Azure Diagnostics Extension helps you configure the VM to collect diagnostics
data that can be used to monitor the health of your application.
Related resources
The resources in this table are used by the VM and need to exist or be created when the VM is created.

RESOURCE REQUIRED DESCRIPTION

Resource group Yes The VM must be contained in a


resource group.

Storage account Yes The VM needs the storage account to


store its virtual hard disks.

Virtual network Yes The VM must be a member of a virtual


network.

Public IP address No The VM can have a public IP address


assigned to it to remotely access it.

Network interface Yes The VM needs the network interface to


communicate in the network.

Data disks No The VM can include data disks to


expand storage capabilities.

Next steps
Create your first VM!
Portal
PowerShell
Azure CLI
Quickstart: Create a Windows virtual machine in the
Azure portal
11/6/2019 • 2 minutes to read • Edit Online

Azure virtual machines (VMs) can be created through the Azure portal. This method provides a browser-based
user interface to create VMs and their associated resources. This quickstart shows you how to use the Azure
portal to deploy a virtual machine (VM ) in Azure that runs Windows Server 2019. To see your VM in action, you
then RDP to the VM and install the IIS web server.
If you don't have an Azure subscription, create a free account before you begin.

Sign in to Azure
Sign in to the Azure portal at https://portal.azure.com.

Create virtual machine


1. Type virtual machines in the search.
2. Under Services, select Virtual machines.
3. In the Virtual machines page, select Add.
4. In the Basics tab, under Project details, make sure the correct subscription is selected and then choose to
Create new resource group. Type myResourceGroup for the name.

5. Under Instance details, type myVM for the Virtual machine name and choose East US for your Region,
and then choose Windows Server 2019 Datacenter for the Image. Leave the other defaults.

6. Under Administrator account, provide a username, such as azureuser and a password. The password
must be at least 12 characters long and meet the defined complexity requirements.
7. Under Inbound port rules, choose Allow selected ports and then select RDP (3389) and HTTP (80)
from the drop-down.

8. Leave the remaining defaults and then select the Review + create button at the bottom of the page.

Connect to virtual machine


Create a remote desktop connection to the virtual machine. These directions tell you how to connect to your VM
from a Windows computer. On a Mac, you need an RDP client such as this Remote Desktop Client from the Mac
App Store.
1. Click the Connect button on the overview page for your virtual machine.

2. In the Connect to virtual machine page, keep the default options to connect by IP address, over port
3389, and click Download RDP file.
3. Open the downloaded RDP file and click Connect when prompted.
4. In the Windows Security window, select More choices and then Use a different account. Type the
username as localhost\username, enter password you created for the virtual machine, and then click OK.
5. You may receive a certificate warning during the sign-in process. Click Yes or Continue to create the
connection.

Install web server


To see your VM in action, install the IIS web server. Open a PowerShell prompt on the VM and run the following
command:

Install-WindowsFeature -name Web-Server -IncludeManagementTools

When done, close the RDP connection to the VM.

View the IIS welcome page


In the portal, select the VM and in the overview of the VM, use the Click to copy button to the right of the IP
address to copy it and paste it into a browser tab. The default IIS welcome page will open, and should look like
this:

Clean up resources
When no longer needed, you can delete the resource group, virtual machine, and all related resources.
Select the resource group for the virtual machine, then select Delete. Confirm the name of the resource group to
finish deleting the resources.

Next steps
In this quickstart, you deployed a simple virtual machine, open a network port for web traffic, and installed a basic
web server. To learn more about Azure virtual machines, continue to the tutorial for Windows VMs.
Azure Windows virtual machine tutorials
Quickstart: Create a Windows virtual machine in
Azure with PowerShell
11/13/2019 • 2 minutes to read • Edit Online

The Azure PowerShell module is used to create and manage Azure resources from the PowerShell command line
or in scripts. This quickstart shows you how to use the Azure PowerShell module to deploy a virtual machine
(VM ) in Azure that runs Windows Server 2016. You will also RDP to the VM and install the IIS web server, to
show the VM in action.
If you don't have an Azure subscription, create a free account before you begin.

Launch Azure Cloud Shell


The Azure Cloud Shell is a free interactive shell that you can use to run the steps in this article. It has common
Azure tools preinstalled and configured to use with your account.
To open the Cloud Shell, just select Try it from the upper right corner of a code block. You can also launch Cloud
Shell in a separate browser tab by going to https://shell.azure.com/powershell. Select Copy to copy the blocks of
code, paste it into the Cloud Shell, and press enter to run it.

Create resource group


Create an Azure resource group with New -AzResourceGroup. A resource group is a logical container into which
Azure resources are deployed and managed.

New-AzResourceGroup -Name myResourceGroup -Location EastUS

Create virtual machine


Create a VM with New -AzVM. Provide names for each of the resources and the New-AzVM cmdlet creates if they
don't already exist.
When prompted, provide a username and password to be used as the sign-in credentials for the VM:

New-AzVm `
-ResourceGroupName "myResourceGroup" `
-Name "myVM" `
-Location "East US" `
-VirtualNetworkName "myVnet" `
-SubnetName "mySubnet" `
-SecurityGroupName "myNetworkSecurityGroup" `
-PublicIpAddressName "myPublicIpAddress" `
-OpenPorts 80,3389

Connect to virtual machine


After the deployment has completed, RDP to the VM. To see your VM in action, the IIS web server is then
installed.
To see the public IP address of the VM, use the Get-AzPublicIpAddress cmdlet:
Get-AzPublicIpAddress -ResourceGroupName "myResourceGroup" | Select "IpAddress"

Use the following command to create a remote desktop session from your local computer. Replace the IP address
with the public IP address of your VM.

mstsc /v:publicIpAddress

In the Windows Security window, select More choices, and then select Use a different account. Type the
username as localhost\username, enter password you created for the virtual machine, and then click OK.
You may receive a certificate warning during the sign-in process. Click Yes or Continue to create the connection

Install web server


To see your VM in action, install the IIS web server. Open a PowerShell prompt on the VM and run the following
command:

Install-WindowsFeature -name Web-Server -IncludeManagementTools

When done, close the RDP connection to the VM.

View the web server in action


With IIS installed and port 80 now open on your VM from the Internet, use a web browser of your choice to view
the default IIS welcome page. Use the public IP address of your VM obtained in a previous step. The following
example shows the default IIS web site:
Clean up resources
When no longer needed, you can use the Remove-AzResourceGroup cmdlet to remove the resource group, VM,
and all related resources:

Remove-AzResourceGroup -Name myResourceGroup

Next steps
In this quickstart, you deployed a simple virtual machine, open a network port for web traffic, and installed a basic
web server. To learn more about Azure virtual machines, continue to the tutorial for Windows VMs.
Azure Windows virtual machine tutorials
Quickstart: Create a Windows virtual machine with
the Azure CLI
11/13/2019 • 3 minutes to read • Edit Online

The Azure CLI is used to create and manage Azure resources from the command line or in scripts. This quickstart
shows you how to use the Azure CLI to deploy a virtual machine (VM ) in Azure that runs Windows Server 2016.
To see your VM in action, you then RDP to the VM and install the IIS web server.
If you don't have an Azure subscription, create a free account before you begin.

Launch Azure Cloud Shell


The Azure Cloud Shell is a free interactive shell that you can use to run the steps in this article. It has common
Azure tools preinstalled and configured to use with your account.
To open the Cloud Shell, just select Try it from the upper right corner of a code block. You can also launch Cloud
Shell in a separate browser tab by going to https://shell.azure.com/bash. Select Copy to copy the blocks of code,
paste it into the Cloud Shell, and press Enter to run it.

Create a resource group


Create a resource group with the az group create command. An Azure resource group is a logical container into
which Azure resources are deployed and managed. The following example creates a resource group named
myResourceGroup in the eastus location:

az group create --name myResourceGroup --location eastus

Create virtual machine


Create a VM with az vm create. The following example creates a VM named myVM. This example uses azureuser
for an administrative user name.
You must change the value for --admin-password or it will fail. Change it to a password that meets the password
requirements for Azure VMs. The user name and password will be used later, when you connect to the VM.

az vm create \
--resource-group myResourceGroup \
--name myVM \
--image win2016datacenter \
--admin-username azureuser \
--admin-password myPassword

It takes a few minutes to create the VM and supporting resources. The following example output shows the VM
create operation was successful.
{
"fqdns": "",
"id":
"/subscriptions/<guid>/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM",
"location": "eastus",
"macAddress": "00-0D-3A-23-9A-49",
"powerState": "VM running",
"privateIpAddress": "10.0.0.4",
"publicIpAddress": "52.174.34.95",
"resourceGroup": "myResourceGroup"
}

Note your own publicIpAddress in the output from your VM. This address is used to access the VM in the next
steps.

Open port 80 for web traffic


By default, only RDP connections are opened when you create a Windows VM in Azure. Use az vm open-port to
open TCP port 80 for use with the IIS web server:

az vm open-port --port 80 --resource-group myResourceGroup --name myVM

Connect to virtual machine


Use the following command to create a remote desktop session from your local computer. Replace the IP address
with the public IP address of your VM. When prompted, enter the credentials used when the VM was created:

mstsc /v:publicIpAddress

Install web server


To see your VM in action, install the IIS web server. Open a PowerShell prompt on the VM and run the following
command:

Install-WindowsFeature -name Web-Server -IncludeManagementTools

When done, close the RDP connection to the VM.

View the web server in action


With IIS installed and port 80 now open on your VM from the Internet, use a web browser of your choice to view
the default IIS welcome page. Use the public IP address of your VM obtained in a previous step. The following
example shows the default IIS web site:
Clean up resources
When no longer needed, you can use the az group delete command to remove the resource group, VM, and all
related resources:

az group delete --name myResourceGroup

Next steps
In this quickstart, you deployed a simple virtual machine, open a network port for web traffic, and installed a basic
web server. To learn more about Azure virtual machines, continue to the tutorial for Windows VMs.
Azure Windows virtual machine tutorials
Tutorial: Create and Manage Windows VMs with
Azure PowerShell
11/13/2019 • 7 minutes to read • Edit Online

Azure virtual machines provide a fully configurable and flexible computing environment. This tutorial covers basic
Azure virtual machine (VM ) deployment tasks like selecting a VM size, selecting a VM image, and deploying a
VM. You learn how to:
Create and connect to a VM
Select and use VM images
View and use specific VM sizes
Resize a VM
View and understand VM state

Launch Azure Cloud Shell


The Azure Cloud Shell is a free interactive shell that you can use to run the steps in this article. It has common
Azure tools preinstalled and configured to use with your account.
To open the Cloud Shell, just select Try it from the upper right corner of a code block. You can also launch Cloud
Shell in a separate browser tab by going to https://shell.azure.com/powershell. Select Copy to copy the blocks of
code, paste it into the Cloud Shell, and press enter to run it.

Create resource group


Create a resource group with the New -AzResourceGroup command.
An Azure resource group is a logical container into which Azure resources are deployed and managed. A resource
group must be created before a virtual machine. In the following example, a resource group named
myResourceGroupVM is created in the EastUS region:

New-AzResourceGroup `
-ResourceGroupName "myResourceGroupVM" `
-Location "EastUS"

The resource group is specified when creating or modifying a VM, which can be seen throughout this tutorial.

Create a VM
When creating a VM, several options are available like operating system image, network configuration, and
administrative credentials. This example creates a VM named myVM, running the default version of Windows
Server 2016 Datacenter.
Set the username and password needed for the administrator account on the VM with Get-Credential:

$cred = Get-Credential

Create the VM with New -AzVM.


New-AzVm `
-ResourceGroupName "myResourceGroupVM" `
-Name "myVM" `
-Location "EastUS" `
-VirtualNetworkName "myVnet" `
-SubnetName "mySubnet" `
-SecurityGroupName "myNetworkSecurityGroup" `
-PublicIpAddressName "myPublicIpAddress" `
-Credential $cred

Connect to VM
After the deployment has completed, create a remote desktop connection with the VM.
Run the following commands to return the public IP address of the VM. Take note of this IP Address so you can
connect to it with your browser to test web connectivity in a future step.

Get-AzPublicIpAddress `
-ResourceGroupName "myResourceGroupVM" | Select IpAddress

Use the following command, on your local machine, to create a remote desktop session with the VM. Replace the
IP address with the publicIPAddress of your VM. When prompted, enter the credentials used when creating the
VM.

mstsc /v:<publicIpAddress>

In the Windows Security window, select More choices and then Use a different account. Type the username
and password you created for the VM and then click OK.

Understand marketplace images


The Azure marketplace includes many images that can be used to create a new VM. In the previous steps, a VM
was created using the Windows Server 2016 Datacenter image. In this step, the PowerShell module is used to
search the marketplace for other Windows images, which can also be used as a base for new VMs. This process
consists of finding the publisher, offer, SKU, and optionally a version number to identify the image.
Use the Get-AzVMImagePublisher command to return a list of image publishers:

Get-AzVMImagePublisher -Location "EastUS"

Use the Get-AzVMImageOffer to return a list of image offers. With this command, the returned list is filtered on
the specified publisher named MicrosoftWindowsServer :

Get-AzVMImageOffer `
-Location "EastUS" `
-PublisherName "MicrosoftWindowsServer"

The results will look something like this example:


Offer PublisherName Location
----- ------------- --------
Windows-HUB MicrosoftWindowsServer EastUS
WindowsServer MicrosoftWindowsServer EastUS
WindowsServer-HUB MicrosoftWindowsServer EastUS

The Get-AzVMImageSku command will then filter on the publisher and offer name to return a list of image
names.

Get-AzVMImageSku `
-Location "EastUS" `
-PublisherName "MicrosoftWindowsServer" `
-Offer "WindowsServer"

The results will look something like this example:

Skus Offer PublisherName Location


---- ----- ------------- --------
2008-R2-SP1 WindowsServer MicrosoftWindowsServer EastUS
2008-R2-SP1-smalldisk WindowsServer MicrosoftWindowsServer EastUS
2012-Datacenter WindowsServer MicrosoftWindowsServer EastUS
2012-Datacenter-smalldisk WindowsServer MicrosoftWindowsServer EastUS
2012-R2-Datacenter WindowsServer MicrosoftWindowsServer EastUS
2012-R2-Datacenter-smalldisk WindowsServer MicrosoftWindowsServer EastUS
2016-Datacenter WindowsServer MicrosoftWindowsServer EastUS
2016-Datacenter-Server-Core WindowsServer MicrosoftWindowsServer EastUS
2016-Datacenter-Server-Core-smalldisk WindowsServer MicrosoftWindowsServer EastUS
2016-Datacenter-smalldisk WindowsServer MicrosoftWindowsServer EastUS
2016-Datacenter-with-Containers WindowsServer MicrosoftWindowsServer EastUS
2016-Datacenter-with-Containers-smalldisk WindowsServer MicrosoftWindowsServer EastUS
2016-Datacenter-with-RDSH WindowsServer MicrosoftWindowsServer EastUS
2016-Nano-Server WindowsServer MicrosoftWindowsServer EastUS

This information can be used to deploy a VM with a specific image. This example deploys a VM using the latest
version of a Windows Server 2016 with Containers image.

New-AzVm `
-ResourceGroupName "myResourceGroupVM" `
-Name "myVM2" `
-Location "EastUS" `
-VirtualNetworkName "myVnet" `
-SubnetName "mySubnet" `
-SecurityGroupName "myNetworkSecurityGroup" `
-PublicIpAddressName "myPublicIpAddress2" `
-ImageName "MicrosoftWindowsServer:WindowsServer:2016-Datacenter-with-Containers:latest" `
-Credential $cred `
-AsJob

The -AsJob parameter creates the VM as a background task, so the PowerShell prompts return to you. You can
view details of background jobs with the Get-Job cmdlet.

Understand VM sizes
The VM size determines the amount of compute resources like CPU, GPU, and memory that are made available
to the VM. Virtual machines should be created using a VM size appropriate for the workload. If a workload
increases, an existing virtual machine can also be resized.
VM Sizes
The following table categorizes sizes into use cases.

TYPE COMMON SIZES DESCRIPTION

General purpose B, Dsv3, Dv3, DSv2, Dv2, Av2, DC Balanced CPU-to-memory. Ideal for dev
/ test and small to medium applications
and data solutions.

Compute optimized Fsv2 High CPU-to-memory. Good for


medium traffic applications, network
appliances, and batch processes.

Memory optimized Esv3, Ev3, M, DSv2, Dv2 High memory-to-core. Great for
relational databases, medium to large
caches, and in-memory analytics.

Storage optimized Lsv2, Ls High disk throughput and IO. Ideal for
Big Data, SQL, and NoSQL databases.

GPU NV, NVv2, NC, NCv2, NCv3, ND Specialized VMs targeted for heavy
graphic rendering and video editing.

High performance H Our most powerful CPU VMs with


optional high-throughput network
interfaces (RDMA).

Find available VM sizes


To see a list of VM sizes available in a particular region, use the Get-AzVMSize command.

Get-AzVMSize -Location "EastUS"

Resize a VM
After a VM has been deployed, it can be resized to increase or decrease resource allocation.
Before resizing a VM, check if the size you want is available on the current VM cluster. The Get-AzVMSize
command returns a list of sizes.

Get-AzVMSize -ResourceGroupName "myResourceGroupVM" -VMName "myVM"

If the size is available, the VM can be resized from a powered-on state, however it is rebooted during the
operation.

$vm = Get-AzVM `
-ResourceGroupName "myResourceGroupVM" `
-VMName "myVM"
$vm.HardwareProfile.VmSize = "Standard_DS3_v2"
Update-AzVM `
-VM $vm `
-ResourceGroupName "myResourceGroupVM"

If the size you want isn't available on the current cluster, the VM needs to be deallocated before the resize
operation can occur. Deallocating a VM will remove any data on the temp disk, and the public IP address will
change unless a static IP address is being used.
Stop-AzVM `
-ResourceGroupName "myResourceGroupVM" `
-Name "myVM" -Force
$vm = Get-AzVM `
-ResourceGroupName "myResourceGroupVM" `
-VMName "myVM"
$vm.HardwareProfile.VmSize = "Standard_E2s_v3"
Update-AzVM -VM $vm `
-ResourceGroupName "myResourceGroupVM"
Start-AzVM `
-ResourceGroupName "myResourceGroupVM" `
-Name $vm.name

VM power states
An Azure VM can have one of many power states.

POWER STATE DESCRIPTION

Starting The virtual machine is being started.

Running The virtual machine is running.

Stopping The virtual machine is being stopped.

Stopped The VM is stopped. Virtual machines in the stopped state still


incur compute charges.

Deallocating The VM is being deallocated.

Deallocated Indicates that the VM is removed from the hypervisor but is


still available in the control plane. Virtual machines in the
Deallocated state do not incur compute charges.

- The power state of the VM is unknown.

To get the state of a particular VM, use the Get-AzVM command. Be sure to specify a valid name for a VM and
resource group.

Get-AzVM `
-ResourceGroupName "myResourceGroupVM" `
-Name "myVM" `
-Status | Select @{n="Status"; e={$_.Statuses[1].Code}}

The output will look something like this example:

Status
------
PowerState/running

Management tasks
During the lifecycle of a VM, you may want to run management tasks like starting, stopping, or deleting a VM.
Additionally, you may want to create scripts to automate repetitive or complex tasks. Using Azure PowerShell,
many common management tasks can be run from the command line or in scripts.
Stop a VM
Stop and deallocate a VM with Stop-AzVM:

Stop-AzVM `
-ResourceGroupName "myResourceGroupVM" `
-Name "myVM" -Force

If you want to keep the VM in a provisioned state, use the -StayProvisioned parameter.
Start a VM

Start-AzVM `
-ResourceGroupName "myResourceGroupVM" `
-Name "myVM"

Delete resource group


Everything inside of a resource group is deleted when you delete the resource group.

Remove-AzResourceGroup `
-Name "myResourceGroupVM" `
-Force

Next steps
In this tutorial, you learned about basic VM creation and management such as how to:
Create and connect to a VM
Select and use VM images
View and use specific VM sizes
Resize a VM
View and understand VM state
Advance to the next tutorial to learn about VM disks.
Create and Manage VM disks
Tutorial - Manage Azure disks with Azure PowerShell
1/19/2020 • 5 minutes to read • Edit Online

Azure virtual machines use disks to store the VMs operating system, applications, and data. When creating a VM,
it's important to choose a disk size and configuration appropriate to the expected workload. This tutorial covers
deploying and managing VM disks. You learn about:
OS disks and temporary disks
Data disks
Standard and Premium disks
Disk performance
Attaching and preparing data disks

Launch Azure Cloud Shell


The Azure Cloud Shell is a free interactive shell that you can use to run the steps in this article. It has common
Azure tools preinstalled and configured to use with your account.
To open the Cloud Shell, just select Try it from the upper right corner of a code block. You can also launch Cloud
Shell in a separate browser tab by going to https://shell.azure.com/powershell. Select Copy to copy the blocks of
code, paste it into the Cloud Shell, and press enter to run it.

Default Azure disks


When an Azure virtual machine is created, two disks are automatically attached to the virtual machine.
Operating system disk - Operating system disks can be sized up to 4 terabytes, and hosts the VMs operating
system. If you create a new virtual machine (VM ) from an Azure Marketplace image, the typically 127 GB (but
some images have smaller OS disk sizes). The OS disk is assigned a drive letter of C: by default. The disk caching
configuration of the OS disk is optimized for OS performance. The OS disk should not host applications or data.
For applications and data, use a data disk, which is detailed later in this article.
Temporary disk - Temporary disks use a solid-state drive that is located on the same Azure host as the VM. Temp
disks are highly performant and may be used for operations such as temporary data processing. However, if the
VM is moved to a new host, any data stored on a temporary disk is removed. The size of the temporary disk is
determined by the VM size. Temporary disks are assigned a drive letter of D: by default.

Azure data disks


Additional data disks can be added for installing applications and storing data. Data disks should be used in any
situation where durable and responsive data storage is needed. The size of the virtual machine determines how
many data disks can be attached to a VM.

VM disk types
Azure provides two types of disks.
Standard disks - backed by HDDs, and delivers cost-effective storage while still being performant. Standard disks
are ideal for a cost effective dev and test workload.
Premium disks - backed by SSD -based high-performance, low -latency disk. Perfect for VMs running production
workload. Premium Storage supports DS -series, DSv2-series, GS -series, and FS -series VMs. Premium disks come
in five types (P10, P20, P30, P40, P50), the size of the disk determines the disk type. When selecting, a disk size the
value is rounded up to the next type. For example, if the size is below 128 GB the disk type is P10, or between 129
GB and 512 GB the disk is P20.
Premium disk performance
PRE
MIU
M
SSD
SIZE
S P1* P2* P3* P4 P6 P10 P15 P20 P30 P40 P50 P60 P70 P80

Disk 4 8 16 32 64 128 256 512 1,02 2,04 4,09 8,19 16,3 32,7
size 4 8 6 2 84 67
in
GiB

IOP 120 120 120 120 240 500 1,10 2,30 5,00 7,50 7,50 16,0 18,0 20,0
S 0 0 0 0 0 00 00 00
per
disk

Thr 25 25 25 25 50 100 125 150 200 250 250 500 750 900
oug MiB MiB MiB MiB MiB MiB MiB MiB MiB MiB MiB MiB MiB MiB
hpu /sec /sec /sec /sec /sec /sec /sec /sec /sec /sec /sec /sec /sec /sec
t
per
disk

Max 3,5 3,5 3,5 3,50 3,50 3,50 3,50 3,50


bur 00 00 00 0 0 0 0 0
st
IOP
S
per
disk
**

Max 170 170 170 170 170 170 170 170


bur MiB MiB MiB MiB MiB MiB MiB MiB
st /sec /sec /sec /sec /sec /sec /sec /sec
thro
ugh
put
per
disk
**

Max 30 30 30 30 30 30 30 30
bur min min min min min min min min
st
dur
atio
n**
PRE
MIU
M
SSD
SIZE
S P1* P2* P3* P4 P6 P10 P15 P20 P30 P40 P50 P60 P70 P80

Eligi No No No No No No No No Yes, Yes, Yes, Yes, Yes, Yes,


ble up up up up up up
for to to to to to to
rese one one one one one one
rvat year year year year year year
ion

*Denotes a disk size that is currently in preview, for regional availability information see New disk sizes: Managed
and unmanaged.
**Denotes a feature that is currently in preview, see Disk bursting for more information.
While the above table identifies max IOPS per disk, a higher level of performance can be achieved by striping
multiple data disks. For instance, 64 data disks can be attached to Standard_GS5 VM. If each of these disks is sized
as a P30, a maximum of 80,000 IOPS can be achieved. For detailed information on max IOPS per VM, see VM
types and sizes.

Create and attach disks


To complete the example in this tutorial, you must have an existing virtual machine. If needed, create a virtual
machine with the following commands.
Set the username and password needed for the administrator account on the virtual machine with Get-Credential:
Create the virtual machine with New -AzVM. You'll be prompted to enter a username and password for the
administrators account for the VM.

New-AzVm `
-ResourceGroupName "myResourceGroupDisk" `
-Name "myVM" `
-Location "East US" `
-VirtualNetworkName "myVnet" `
-SubnetName "mySubnet" `
-SecurityGroupName "myNetworkSecurityGroup" `
-PublicIpAddressName "myPublicIpAddress"

Create the initial configuration with New -AzDiskConfig. The following example configures a disk that is 128
gigabytes in size.

$diskConfig = New-AzDiskConfig `
-Location "EastUS" `
-CreateOption Empty `
-DiskSizeGB 128

Create the data disk with the New -AzDisk command.

$dataDisk = New-AzDisk `
-ResourceGroupName "myResourceGroupDisk" `
-DiskName "myDataDisk" `
-Disk $diskConfig

Get the virtual machine that you want to add the data disk to with the Get-AzVM command.
$vm = Get-AzVM -ResourceGroupName "myResourceGroupDisk" -Name "myVM"

Add the data disk to the virtual machine configuration with the Add-AzVMDataDisk command.

$vm = Add-AzVMDataDisk `
-VM $vm `
-Name "myDataDisk" `
-CreateOption Attach `
-ManagedDiskId $dataDisk.Id `
-Lun 1

Update the virtual machine with the Update-AzVM command.

Update-AzVM -ResourceGroupName "myResourceGroupDisk" -VM $vm

Prepare data disks


Once a disk has been attached to the virtual machine, the operating system needs to be configured to use the disk.
The following example shows how to manually configure the first disk added to the VM. This process can also be
automated using the custom script extension.
Manual configuration
Create an RDP connection with the virtual machine. Open up PowerShell and run this script.

Get-Disk | Where partitionstyle -eq 'raw' |


Initialize-Disk -PartitionStyle MBR -PassThru |
New-Partition -AssignDriveLetter -UseMaximumSize |
Format-Volume -FileSystem NTFS -NewFileSystemLabel "myDataDisk" -Confirm:$false

Verify the data disk


To verify that the data disk is attached, view the StorageProfile for the attached DataDisks .

$vm.StorageProfile.DataDisks

The output should look something like this example:

Name : myDataDisk
DiskSizeGB : 128
Lun : 1
Caching : None
CreateOption : Attach
SourceImage :
VirtualHardDisk :

Next steps
In this tutorial, you learned about VM disks topics such as:
OS disks and temporary disks
Data disks
Standard and Premium disks
Disk performance
Attaching and preparing data disks
Advance to the next tutorial to learn about automating VM configuration.
Automate VM configuration
Tutorial - Deploy applications to a Windows virtual
machine in Azure with the Custom Script Extension
11/13/2019 • 2 minutes to read • Edit Online

To configure virtual machines (VMs) in a quick and consistent manner, you can use the Custom Script Extension
for Windows. In this tutorial you learn how to:
Use the Custom Script Extension to install IIS
Create a VM that uses the Custom Script Extension
View a running IIS site after the extension is applied

Launch Azure Cloud Shell


The Azure Cloud Shell is a free interactive shell that you can use to run the steps in this article. It has common
Azure tools preinstalled and configured to use with your account.
To open the Cloud Shell, just select Try it from the upper right corner of a code block. You can also launch Cloud
Shell in a separate browser tab by going to https://shell.azure.com/powershell. Select Copy to copy the blocks of
code, paste it into the Cloud Shell, and press enter to run it.

Custom script extension overview


The Custom Script Extension downloads and executes scripts on Azure VMs. This extension is useful for post
deployment configuration, software installation, or any other configuration / management task. Scripts can be
downloaded from Azure storage or GitHub, or provided to the Azure portal at extension run time.
The Custom Script extension integrates with Azure Resource Manager templates, and can also be run using the
Azure CLI, PowerShell, Azure portal, or the Azure Virtual Machine REST API.
You can use the Custom Script Extension with both Windows and Linux VMs.

Create virtual machine


Set the administrator username and password for the VM with Get-Credential:

$cred = Get-Credential

Now you can create the VM with New -AzVM. The following example creates a VM named myVM in the EastUS
location. If they do not already exist, the resource group myResourceGroupAutomate and supporting network
resources are created. To allow web traffic, the cmdlet also opens port 80.
New-AzVm `
-ResourceGroupName "myResourceGroupAutomate" `
-Name "myVM" `
-Location "East US" `
-VirtualNetworkName "myVnet" `
-SubnetName "mySubnet" `
-SecurityGroupName "myNetworkSecurityGroup" `
-PublicIpAddressName "myPublicIpAddress" `
-OpenPorts 80 `
-Credential $cred

It takes a few minutes for the resources and VM to be created.

Automate IIS install


Use Set-AzVMExtension to install the Custom Script Extension. The extension runs
powershell Add-WindowsFeature Web-Server to install the IIS webserver and then updates the Default.htm page to
show the hostname of the VM:

Set-AzVMExtension -ResourceGroupName "myResourceGroupAutomate" `


-ExtensionName "IIS" `
-VMName "myVM" `
-Location "EastUS" `
-Publisher Microsoft.Compute `
-ExtensionType CustomScriptExtension `
-TypeHandlerVersion 1.8 `
-SettingString '{"commandToExecute":"powershell Add-WindowsFeature Web-Server; powershell Add-Content -
Path \"C:\\inetpub\\wwwroot\\Default.htm\" -Value $($env:computername)"}'

Test web site


Obtain the public IP address of your load balancer with Get-AzPublicIPAddress. The following example obtains
the IP address for myPublicIPAddress created earlier:

Get-AzPublicIPAddress `
-ResourceGroupName "myResourceGroupAutomate" `
-Name "myPublicIPAddress" | select IpAddress

You can then enter the public IP address in to a web browser. The website is displayed, including the hostname of
the VM that the load balancer distributed traffic to as in the following example:

Next steps
In this tutorial, you automated the IIS install on a VM. You learned how to:
Use the Custom Script Extension to install IIS
Create a VM that uses the Custom Script Extension
View a running IIS site after the extension is applied
Advance to the next tutorial to learn how to create custom VM images.
Create custom VM images
Tutorial: Create a custom image of an Azure VM with
Azure PowerShell
1/19/2020 • 4 minutes to read • Edit Online

Custom images are like marketplace images, but you create them yourself. Custom images can be used to
bootstrap deployments and ensure consistency across multiple VMs. In this tutorial, you create your own custom
image of an Azure virtual machine using PowerShell. You learn how to:
Sysprep and generalize VMs
Create a custom image
Create a VM from a custom image
List all the images in your subscription
Delete an image
In public preview, we have the Azure VM Image Builder service. Simply describe your customizations in a
template, and it will handle the image creation steps in this article. Try Azure Image Builder (preview ).

Before you begin


The steps below detail how to take an existing VM and turn it into a re-usable custom image that you can use to
create new VM instances.
To complete the example in this tutorial, you must have an existing virtual machine. If needed, this script sample
can create one for you. When working through the tutorial, replace the resource group and VM names where
needed.

Launch Azure Cloud Shell


The Azure Cloud Shell is a free interactive shell that you can use to run the steps in this article. It has common
Azure tools preinstalled and configured to use with your account.
To open the Cloud Shell, just select Try it from the upper right corner of a code block. You can also launch Cloud
Shell in a separate browser tab by going to https://shell.azure.com/powershell. Select Copy to copy the blocks of
code, paste it into the Cloud Shell, and press enter to run it.

Prepare VM
To create an image of a virtual machine, you need to prepare the source VM by generalizing it, deallocating, and
then marking it as generalized with Azure.
Generalize the Windows VM using Sysprep
Sysprep removes all your personal account information, among other things, and prepares the machine to be used
as an image. For details about Sysprep, see How to Use Sysprep: An Introduction.
1. Connect to the virtual machine.
2. Open the Command Prompt window as an administrator. Change the directory to
%windir%\system32\sysprep, and then run sysprep.exe .
3. In the System Preparation Tool dialog box, select Enter System Out-of-Box Experience (OOBE ), and
make sure that the Generalize check box is selected.
4. In Shutdown Options, select Shutdown and then click OK.
5. When Sysprep completes, it shuts down the virtual machine. Do not restart the VM.
Deallocate and mark the VM as generalized
To create an image, the VM needs to be deallocated and marked as generalized in Azure.
Deallocate the VM using Stop-AzVM.

Stop-AzVM `
-ResourceGroupName myResourceGroup `
-Name myVM -Force

Set the status of the virtual machine to -Generalized using Set-AzVm.

Set-AzVM `
-ResourceGroupName myResourceGroup `
-Name myVM -Generalized

Create the image


Now you can create an image of the VM by using New -AzImageConfig and New -AzImage. The following
example creates an image named myImage from a VM named myVM.
Get the virtual machine.

$vm = Get-AzVM `
-Name myVM `
-ResourceGroupName myResourceGroup

Create the image configuration.

$image = New-AzImageConfig `
-Location EastUS `
-SourceVirtualMachineId $vm.ID

Create the image.

New-AzImage `
-Image $image `
-ImageName myImage `
-ResourceGroupName myResourceGroup

Create VMs from the image


Now that you have an image, you can create one or more new VMs from the image. Creating a VM from a
custom image is similar to creating a VM using a Marketplace image. When you use a Marketplace image, you
have to provide the information about the image, image provider, offer, SKU, and version. Using the simplified
parameter set for the New -AzVM cmdlet, you just need to provide the name of the custom image as long as it is
in the same resource group.
This example creates a VM named myVMfromImage from the myImage image, in myResourceGroup.
New-AzVm `
-ResourceGroupName "myResourceGroup" `
-Name "myVMfromImage" `
-ImageName "myImage" `
-Location "East US" `
-VirtualNetworkName "myImageVnet" `
-SubnetName "myImageSubnet" `
-SecurityGroupName "myImageNSG" `
-PublicIpAddressName "myImagePIP" `
-OpenPorts 3389

We recommend that you limit the number of concurrent deployments to 20 VMs from a single image. If you are
planning large-scale, concurrent deployments of over 20 VMs from the same custom image, you should use a
Shared Image Gallery with multiple image replicas.

Image management
Here are some examples of common managed image tasks and how to complete them using PowerShell.
List all images by name.

$images = Get-AzResource -ResourceType Microsoft.Compute/images


$images.name

Delete an image. This example deletes the image named myImage from the myResourceGroup.

Remove-AzImage `
-ImageName myImage `
-ResourceGroupName myResourceGroup

Next steps
In this tutorial, you created a custom VM image. You learned how to:
Sysprep and generalize VMs
Create a custom image
Create a VM from a custom image
List all the images in your subscription
Delete an image
Advance to the next tutorial to learn about how to create highly available virtual machines.
Create highly available VMs
Tutorial: Create and deploy highly available virtual
machines with Azure PowerShell
11/13/2019 • 4 minutes to read • Edit Online

In this tutorial, you learn how to increase the availability and reliability of your Virtual Machines (VMs) using
Availability Sets. Availability Sets make sure the VMs you deploy on Azure are distributed across multiple, isolated
hardware nodes, in a cluster.
In this tutorial, you learn how to:
Create an availability set
Create a VM in an availability set
Check available VM sizes
Check Azure Advisor

Availability set overview


An Availability Set is a logical grouping capability for isolating VM resources from each other when they're
deployed. Azure makes sure that the VMs you place within an Availability Set run across multiple physical servers,
compute racks, storage units, and network switches. If a hardware or software failure happens, only a subset of
your VMs are impacted and your overall solution stays operational. Availability Sets are essential for building
reliable cloud solutions.
Let’s consider a typical VM -based solution where you might have four front-end web servers and 2 back-end
VMs. With Azure, you’d want to define two availability sets before you deploy your VMs: one for the web tier and
one for the back tier. When you create a new VM, you specify the availability set as a parameter. Azure makes sure
the VMs are isolated across multiple physical hardware resources. If the physical hardware that one of your
servers is running on has a problem, you know the other instances of your servers will keep running because
they're on different hardware.
Use Availability Sets when you want to deploy reliable VM -based solutions in Azure.

Launch Azure Cloud Shell


The Azure Cloud Shell is a free interactive shell that you can use to run the steps in this article. It has common
Azure tools preinstalled and configured to use with your account.
To open the Cloud Shell, just select Try it from the upper right corner of a code block. You can also launch Cloud
Shell in a separate browser tab by going to https://shell.azure.com/powershell. Select Copy to copy the blocks of
code, paste it into the Cloud Shell, and press enter to run it.

Create an availability set


The hardware in a location is divided in to multiple update domains and fault domains. An update domain is a
group of VMs and underlying physical hardware that can be rebooted at the same time. VMs in the same fault
domain share common storage as well as a common power source and network switch.
You can create an availability set using New -AzAvailabilitySet. In this example, the number of both update and
fault domains is 2 and the availability set is named myAvailabilitySet.
Create a resource group.
New-AzResourceGroup `
-Name myResourceGroupAvailability `
-Location EastUS

Create a managed availability set using New -AzAvailabilitySet with the -sku aligned parameter.

New-AzAvailabilitySet `
-Location "EastUS" `
-Name "myAvailabilitySet" `
-ResourceGroupName "myResourceGroupAvailability" `
-Sku aligned `
-PlatformFaultDomainCount 2 `
-PlatformUpdateDomainCount 2

Create VMs inside an availability set


VMs must be created within the availability set to make sure they're correctly distributed across the hardware. You
can't add an existing VM to an availability set after it's created.
When you create a VM with New -AzVM, you use the -AvailabilitySetName parameter to specify the name of the
availability set.
First, set an administrator username and password for the VM with Get-Credential:

$cred = Get-Credential

Now create two VMs with New -AzVM in the availability set.

for ($i=1; $i -le 2; $i++)


{
New-AzVm `
-ResourceGroupName "myResourceGroupAvailability" `
-Name "myVM$i" `
-Location "East US" `
-VirtualNetworkName "myVnet" `
-SubnetName "mySubnet" `
-SecurityGroupName "myNetworkSecurityGroup" `
-PublicIpAddressName "myPublicIpAddress$i" `
-AvailabilitySetName "myAvailabilitySet" `
-Credential $cred
}

It takes a few minutes to create and configure both VMs. When finished, you have two virtual machines
distributed across the underlying hardware.
If you look at the availability set in the portal by going to Resource Groups > myResourceGroupAvailability >
myAvailabilitySet, you should see how the VMs are distributed across the two fault and update domains.
Check for available VM sizes
You can add more VMs to the availability set later, but you need to know what VM sizes are available on the
hardware. Use Get-AzVMSize to list all the available sizes on the hardware cluster for the availability set.

Get-AzVMSize `
-ResourceGroupName "myResourceGroupAvailability" `
-AvailabilitySetName "myAvailabilitySet"

Check Azure Advisor


You can also use Azure Advisor to get more information on how to improve the availability of your VMs. Azure
Advisor analyzes your configuration and usage telemetry, then recommends solutions that can help you improve
the cost effectiveness, performance, availability, and security of your Azure resources.
Sign in to the Azure portal, select All services, and type Advisor. The Advisor dashboard shows personalized
recommendations for the selected subscription. For more information, see Get started with Azure Advisor.

Next steps
In this tutorial, you learned how to:
Create an availability set
Create a VM in an availability set
Check available VM sizes
Check Azure Advisor
Advance to the next tutorial to learn about virtual machine scale sets.
Create a VM scale set
Tutorial: Create a virtual machine scale set and
deploy a highly available app on Windows with
Azure PowerShell
12/12/2019 • 7 minutes to read • Edit Online

A virtual machine scale set allows you to deploy and manage a set of identical, autoscaling virtual machines. You
can scale the number of VMs in the scale set manually. You can also define rules to autoscale based on resource
usage such as CPU, memory demand, or network traffic. In this tutorial, you deploy a virtual machine scale set in
Azure and learn how to:
Use the Custom Script Extension to define an IIS site to scale
Create a load balancer for your scale set
Create a virtual machine scale set
Increase or decrease the number of instances in a scale set
Create autoscale rules

Launch Azure Cloud Shell


The Azure Cloud Shell is a free interactive shell that you can use to run the steps in this article. It has common
Azure tools preinstalled and configured to use with your account.
To open the Cloud Shell, just select Try it from the upper right corner of a code block. You can also launch Cloud
Shell in a separate browser tab by going to https://shell.azure.com/powershell. Select Copy to copy the blocks of
code, paste it into the Cloud Shell, and press enter to run it.

Scale Set overview


A virtual machine scale set allows you to deploy and manage a set of identical, autoscaling virtual machines. VMs
in a scale set are distributed across logic fault and update domains in one or more placement groups. Placement
groups are groups of similarly configured VMs, similar to availability sets.
VMs are created as needed in a scale set. You define autoscale rules to control how and when VMs are added or
removed from the scale set. These rules can trigger based on metrics such as CPU load, memory usage, or
network traffic.
Scale sets support up to 1,000 VMs when you use an Azure platform image. For workloads with significant
installation or VM customization requirements, you may wish to Create a custom VM image. You can create up to
300 VMs in a scale set when using a custom image.

Create a scale set


Create a virtual machine scale set with New -AzVmss. The following example creates a scale set named myScaleSet
that uses the Windows Server 2016 Datacenter platform image. The Azure network resources for virtual network,
public IP address, and load balancer are automatically created. When prompted, you can set your own
administrative credentials for the VM instances in the scale set:
New-AzVmss `
-ResourceGroupName "myResourceGroupScaleSet" `
-Location "EastUS" `
-VMScaleSetName "myScaleSet" `
-VirtualNetworkName "myVnet" `
-SubnetName "mySubnet" `
-PublicIpAddressName "myPublicIPAddress" `
-LoadBalancerName "myLoadBalancer" `
-UpgradePolicyMode "Automatic"

It takes a few minutes to create and configure all the scale set resources and VMs.

Deploy sample application


To test your scale set, install a basic web application. The Azure Custom Script Extension is used to download and
run a script that installs IIS on the VM instances. This extension is useful for post deployment configuration,
software installation, or any other configuration / management task. For more information, see the Custom Script
Extension overview.
Use the Custom Script Extension to install a basic IIS web server. Apply the Custom Script Extension that installs
IIS as follows:

# Define the script for your Custom Script Extension to run


$publicSettings = @{
"fileUris" = (,"https://raw.githubusercontent.com/Azure-Samples/compute-automation-
configurations/master/automate-iis.ps1");
"commandToExecute" = "powershell -ExecutionPolicy Unrestricted -File automate-iis.ps1"
}

# Get information about the scale set


$vmss = Get-AzVmss `
-ResourceGroupName "myResourceGroupScaleSet" `
-VMScaleSetName "myScaleSet"

# Use Custom Script Extension to install IIS and configure basic website
Add-AzVmssExtension -VirtualMachineScaleSet $vmss `
-Name "customScript" `
-Publisher "Microsoft.Compute" `
-Type "CustomScriptExtension" `
-TypeHandlerVersion 1.8 `
-Setting $publicSettings

# Update the scale set and apply the Custom Script Extension to the VM instances
Update-AzVmss `
-ResourceGroupName "myResourceGroupScaleSet" `
-Name "myScaleSet" `
-VirtualMachineScaleSet $vmss

Allow traffic to application


To allow access to the basic web application, create a network security group with New -
AzNetworkSecurityRuleConfig and New -AzNetworkSecurityGroup. For more information, see Networking for
Azure virtual machine scale sets.
# Get information about the scale set
$vmss = Get-AzVmss `
-ResourceGroupName "myResourceGroupScaleSet" `
-VMScaleSetName "myScaleSet"

#Create a rule to allow traffic over port 80


$nsgFrontendRule = New-AzNetworkSecurityRuleConfig `
-Name myFrontendNSGRule `
-Protocol Tcp `
-Direction Inbound `
-Priority 200 `
-SourceAddressPrefix * `
-SourcePortRange * `
-DestinationAddressPrefix * `
-DestinationPortRange 80 `
-Access Allow

#Create a network security group and associate it with the rule


$nsgFrontend = New-AzNetworkSecurityGroup `
-ResourceGroupName "myResourceGroupScaleSet" `
-Location EastUS `
-Name myFrontendNSG `
-SecurityRules $nsgFrontendRule

$vnet = Get-AzVirtualNetwork `
-ResourceGroupName "myResourceGroupScaleSet" `
-Name myVnet

$frontendSubnet = $vnet.Subnets[0]

$frontendSubnetConfig = Set-AzVirtualNetworkSubnetConfig `
-VirtualNetwork $vnet `
-Name mySubnet `
-AddressPrefix $frontendSubnet.AddressPrefix `
-NetworkSecurityGroup $nsgFrontend

Set-AzVirtualNetwork -VirtualNetwork $vnet

# Update the scale set and apply the Custom Script Extension to the VM instances
Update-AzVmss `
-ResourceGroupName "myResourceGroupScaleSet" `
-Name "myScaleSet" `
-VirtualMachineScaleSet $vmss

Test your scale set


To see your scale set in action, get the public IP address of your load balancer with Get-AzPublicIPAddress. The
following example displays the IP address for myPublicIP created as part of the scale set:

Get-AzPublicIPAddress `
-ResourceGroupName "myResourceGroupScaleSet" `
-Name "myPublicIPAddress" | select IpAddress

Enter the public IP address in to a web browser. The web app is displayed, including the hostname of the VM that
the load balancer distributed traffic to:
To see the scale set in action, you can force-refresh your web browser to see the load balancer distribute traffic
across all the VMs running your app.

Management tasks
Throughout the lifecycle of the scale set, you may need to run one or more management tasks. Additionally, you
may want to create scripts that automate various lifecycle-tasks. Azure PowerShell provides a quick way to do
those tasks. Here are a few common tasks.
View VMs in a scale set
To view a list of VM instances in a scale set, use Get-AzVmssVM as follows:

Get-AzVmssVM `
-ResourceGroupName "myResourceGroupScaleSet" `
-VMScaleSetName "myScaleSet"

The following example output shows two VM instances in the scale set:

ResourceGroupName Name Location Sku InstanceID ProvisioningState


----------------- ---- -------- --- ---------- -----------------
MYRESOURCEGROUPSCALESET myScaleSet_0 eastus Standard_DS1_v2 0 Succeeded
MYRESOURCEGROUPSCALESET myScaleSet_1 eastus Standard_DS1_v2 1 Succeeded

To view additional information about a specific VM instance, add the -InstanceId parameter to Get-AzVmssVM.
The following example views information about VM instance 1:

Get-AzVmssVM `
-ResourceGroupName "myResourceGroupScaleSet" `
-VMScaleSetName "myScaleSet" `
-InstanceId "1"

Increase or decrease VM instances


To see the number of instances you currently have in a scale set, use Get-AzVmss and query on sku.capacity:

Get-AzVmss -ResourceGroupName "myResourceGroupScaleSet" `


-VMScaleSetName "myScaleSet" | `
Select -ExpandProperty Sku

You can then manually increase or decrease the number of virtual machines in the scale set with Update-AzVmss.
The following example sets the number of VMs in your scale set to 3:
# Get current scale set
$scaleset = Get-AzVmss `
-ResourceGroupName "myResourceGroupScaleSet" `
-VMScaleSetName "myScaleSet"

# Set and update the capacity of your scale set


$scaleset.sku.capacity = 3
Update-AzVmss -ResourceGroupName "myResourceGroupScaleSet" `
-Name "myScaleSet" `
-VirtualMachineScaleSet $scaleset

If takes a few minutes to update the specified number of instances in your scale set.
Configure autoscale rules
Rather than manually scaling the number of instances in your scale set, you define autoscale rules. These rules
monitor the instances in your scale set and respond accordingly based on metrics and thresholds you define. The
following example scales out the number of instances by one when the average CPU load is greater than 60% over
a 5-minute period. If the average CPU load then drops below 30% over a 5-minute period, the instances are scaled
in by one instance:
# Define your scale set information
$mySubscriptionId = (Get-AzSubscription)[0].Id
$myResourceGroup = "myResourceGroupScaleSet"
$myScaleSet = "myScaleSet"
$myLocation = "East US"
$myScaleSetId = (Get-AzVmss -ResourceGroupName $myResourceGroup -VMScaleSetName $myScaleSet).Id

# Create a scale up rule to increase the number instances after 60% average CPU usage exceeded for a 5-minute
period
$myRuleScaleUp = New-AzAutoscaleRule `
-MetricName "Percentage CPU" `
-MetricResourceId $myScaleSetId `
-Operator GreaterThan `
-MetricStatistic Average `
-Threshold 60 `
-TimeGrain 00:01:00 `
-TimeWindow 00:05:00 `
-ScaleActionCooldown 00:05:00 `
-ScaleActionDirection Increase `
-ScaleActionValue 1

# Create a scale down rule to decrease the number of instances after 30% average CPU usage over a 5-minute
period
$myRuleScaleDown = New-AzAutoscaleRule `
-MetricName "Percentage CPU" `
-MetricResourceId $myScaleSetId `
-Operator LessThan `
-MetricStatistic Average `
-Threshold 30 `
-TimeGrain 00:01:00 `
-TimeWindow 00:05:00 `
-ScaleActionCooldown 00:05:00 `
-ScaleActionDirection Decrease `
-ScaleActionValue 1

# Create a scale profile with your scale up and scale down rules
$myScaleProfile = New-AzAutoscaleProfile `
-DefaultCapacity 2 `
-MaximumCapacity 10 `
-MinimumCapacity 2 `
-Rule $myRuleScaleUp,$myRuleScaleDown `
-Name "autoprofile"

# Apply the autoscale rules


Add-AzAutoscaleSetting `
-Location $myLocation `
-Name "autosetting" `
-ResourceGroup $myResourceGroup `
-TargetResourceId $myScaleSetId `
-AutoscaleProfile $myScaleProfile

For more design information on the use of autoscale, see autoscale best practices.

Next steps
In this tutorial, you created a virtual machine scale set. You learned how to:
Use the Custom Script Extension to define an IIS site to scale
Create a load balancer for your scale set
Create a virtual machine scale set
Increase or decrease the number of instances in a scale set
Create autoscale rules
Advance to the next tutorial to learn more about load balancing concepts for virtual machines.
Load balance virtual machines
Tutorial: Load balance Windows virtual machines in
Azure to create a highly available application with
Azure PowerShell
11/13/2019 • 8 minutes to read • Edit Online

Load balancing provides a higher level of availability by spreading incoming requests across multiple virtual
machines. In this tutorial, you learn about the different components of the Azure load balancer that distribute
traffic and provide high availability. You learn how to:
Create an Azure load balancer
Create a load balancer health probe
Create load balancer traffic rules
Use the Custom Script Extension to create a basic IIS site
Create virtual machines and attach to a load balancer
View a load balancer in action
Add and remove VMs from a load balancer

Azure load balancer overview


An Azure load balancer is a Layer-4 (TCP, UDP ) load balancer that provides high availability by distributing
incoming traffic among healthy VMs. A load balancer health probe monitors a given port on each VM and only
distributes traffic to an operational VM.
You define a front-end IP configuration that contains one or more public IP addresses. This front-end IP
configuration allows your load balancer and applications to be accessible over the Internet.
Virtual machines connect to a load balancer using their virtual network interface card (NIC ). To distribute traffic to
the VMs, a back-end address pool contains the IP addresses of the virtual (NICs) connected to the load balancer.
To control the flow of traffic, you define load balancer rules for specific ports and protocols that map to your VMs.

Launch Azure Cloud Shell


The Azure Cloud Shell is a free interactive shell that you can use to run the steps in this article. It has common
Azure tools preinstalled and configured to use with your account.
To open the Cloud Shell, just select Try it from the upper right corner of a code block. You can also launch Cloud
Shell in a separate browser tab by going to https://shell.azure.com/powershell. Select Copy to copy the blocks of
code, paste it into the Cloud Shell, and press enter to run it.

Create Azure load balancer


This section details how you can create and configure each component of the load balancer. Before you can create
your load balancer, create a resource group with New -AzResourceGroup. The following example creates a
resource group named myResourceGroupLoadBalancer in the EastUS location:
New-AzResourceGroup `
-ResourceGroupName "myResourceGroupLoadBalancer" `
-Location "EastUS"

Create a public IP address


To access your app on the Internet, you need a public IP address for the load balancer. Create a public IP address
with New -AzPublicIpAddress. The following example creates a public IP address named myPublicIP in the
myResourceGroupLoadBalancer resource group:

$publicIP = New-AzPublicIpAddress `
-ResourceGroupName "myResourceGroupLoadBalancer" `
-Location "EastUS" `
-AllocationMethod "Static" `
-Name "myPublicIP"

Create a load balancer


Create a frontend IP pool with New -AzLoadBalancerFrontendIpConfig. The following example creates a frontend
IP pool named myFrontEndPool and attaches the myPublicIP address:

$frontendIP = New-AzLoadBalancerFrontendIpConfig `
-Name "myFrontEndPool" `
-PublicIpAddress $publicIP

Create a backend address pool with New -AzLoadBalancerBackendAddressPoolConfig. The VMs attach to this
backend pool in the remaining steps. The following example creates a backend address pool named
myBackEndPool:

$backendPool = New-AzLoadBalancerBackendAddressPoolConfig `
-Name "myBackEndPool"

Now, create the load balancer with New -AzLoadBalancer. The following example creates a load balancer named
myLoadBalancer using the frontend and backend IP pools created in the preceding steps:

$lb = New-AzLoadBalancer `
-ResourceGroupName "myResourceGroupLoadBalancer" `
-Name "myLoadBalancer" `
-Location "EastUS" `
-FrontendIpConfiguration $frontendIP `
-BackendAddressPool $backendPool

Create a health probe


To allow the load balancer to monitor the status of your app, you use a health probe. The health probe dynamically
adds or removes VMs from the load balancer rotation based on their response to health checks. By default, a VM
is removed from the load balancer distribution after two consecutive failures at 15-second intervals. You create a
health probe based on a protocol or a specific health check page for your app.
The following example creates a TCP probe. You can also create custom HTTP probes for more fine grained health
checks. When using a custom HTTP probe, you must create the health check page, such as healthcheck.aspx. The
probe must return an HTTP 200 OK response for the load balancer to keep the host in rotation.
To create a TCP health probe, you use Add-AzLoadBalancerProbeConfig. The following example creates a health
probe named myHealthProbe that monitors each VM on TCP port 80:
Add-AzLoadBalancerProbeConfig `
-Name "myHealthProbe" `
-LoadBalancer $lb `
-Protocol tcp `
-Port 80 `
-IntervalInSeconds 15 `
-ProbeCount 2

To apply the health probe, update the load balancer with Set-AzLoadBalancer:

Set-AzLoadBalancer -LoadBalancer $lb

Create a load balancer rule


A load balancer rule is used to define how traffic is distributed to the VMs. You define the front-end IP
configuration for the incoming traffic and the back-end IP pool to receive the traffic, along with the required
source and destination port. To make sure only healthy VMs receive traffic, you also define the health probe to use.
Create a load balancer rule with Add-AzLoadBalancerRuleConfig. The following example creates a load balancer
rule named myLoadBalancerRule and balances traffic on TCP port 80:

$probe = Get-AzLoadBalancerProbeConfig -LoadBalancer $lb -Name "myHealthProbe"

Add-AzLoadBalancerRuleConfig `
-Name "myLoadBalancerRule" `
-LoadBalancer $lb `
-FrontendIpConfiguration $lb.FrontendIpConfigurations[0] `
-BackendAddressPool $lb.BackendAddressPools[0] `
-Protocol Tcp `
-FrontendPort 80 `
-BackendPort 80 `
-Probe $probe

Update the load balancer with Set-AzLoadBalancer:

Set-AzLoadBalancer -LoadBalancer $lb

Configure virtual network


Before you deploy some VMs and can test your balancer, create the supporting virtual network resources. For
more information about virtual networks, see the Manage Azure Virtual Networks tutorial.
Create network resources
Create a virtual network with New -AzVirtualNetwork. The following example creates a virtual network named
myVnet with mySubnet:
# Create subnet config
$subnetConfig = New-AzVirtualNetworkSubnetConfig `
-Name "mySubnet" `
-AddressPrefix 192.168.1.0/24

# Create the virtual network


$vnet = New-AzVirtualNetwork `
-ResourceGroupName "myResourceGroupLoadBalancer" `
-Location "EastUS" `
-Name "myVnet" `
-AddressPrefix 192.168.0.0/16 `
-Subnet $subnetConfig

Virtual NICs are created with New -AzNetworkInterface. The following example creates three virtual NICs. (One
virtual NIC for each VM you create for your app in the following steps). You can create additional virtual NICs and
VMs at any time and add them to the load balancer:

for ($i=1; $i -le 3; $i++)


{
New-AzNetworkInterface `
-ResourceGroupName "myResourceGroupLoadBalancer" `
-Name myVM$i `
-Location "EastUS" `
-Subnet $vnet.Subnets[0] `
-LoadBalancerBackendAddressPool $lb.BackendAddressPools[0]
}

Create virtual machines


To improve the high availability of your app, place your VMs in an availability set.
Create an availability set with New -AzAvailabilitySet. The following example creates an availability set named
myAvailabilitySet:

$availabilitySet = New-AzAvailabilitySet `
-ResourceGroupName "myResourceGroupLoadBalancer" `
-Name "myAvailabilitySet" `
-Location "EastUS" `
-Sku aligned `
-PlatformFaultDomainCount 2 `
-PlatformUpdateDomainCount 2

Set an administrator username and password for the VMs with Get-Credential:

$cred = Get-Credential

Now you can create the VMs with New -AzVM. The following example creates three VMs and the required virtual
network components if they do not already exist:
for ($i=1; $i -le 3; $i++)
{
New-AzVm `
-ResourceGroupName "myResourceGroupLoadBalancer" `
-Name "myVM$i" `
-Location "East US" `
-VirtualNetworkName "myVnet" `
-SubnetName "mySubnet" `
-SecurityGroupName "myNetworkSecurityGroup" `
-OpenPorts 80 `
-AvailabilitySetName "myAvailabilitySet" `
-Credential $cred `
-AsJob
}

The -AsJob parameter creates the VM as a background task, so the PowerShell prompts return to you. You can
view details of background jobs with the Job cmdlet. It takes a few minutes to create and configure all three VMs.
Install IIS with Custom Script Extension
In a previous tutorial on How to customize a Windows virtual machine, you learned how to automate VM
customization with the Custom Script Extension for Windows. You can use the same approach to install and
configure IIS on your VMs.
Use Set-AzVMExtension to install the Custom Script Extension. The extension runs
powershell Add-WindowsFeature Web-Server to install the IIS webserver and then updates the Default.htm page to
show the hostname of the VM:

for ($i=1; $i -le 3; $i++)


{
Set-AzVMExtension `
-ResourceGroupName "myResourceGroupLoadBalancer" `
-ExtensionName "IIS" `
-VMName myVM$i `
-Publisher Microsoft.Compute `
-ExtensionType CustomScriptExtension `
-TypeHandlerVersion 1.8 `
-SettingString '{"commandToExecute":"powershell Add-WindowsFeature Web-Server; powershell Add-Content -
Path \"C:\\inetpub\\wwwroot\\Default.htm\" -Value $($env:computername)"}' `
-Location EastUS
}

Test load balancer


Obtain the public IP address of your load balancer with Get-AzPublicIPAddress. The following example obtains
the IP address for myPublicIP created earlier:

Get-AzPublicIPAddress `
-ResourceGroupName "myResourceGroupLoadBalancer" `
-Name "myPublicIP" | select IpAddress

You can then enter the public IP address in to a web browser. The website is displayed, including the hostname of
the VM that the load balancer distributed traffic to as in the following example:
To see the load balancer distribute traffic across all three VMs running your app, you can force-refresh your web
browser.

Add and remove VMs


You may need to perform maintenance on the VMs running your app, such as installing OS updates. To deal with
increased traffic to your app, you may need to add additional VMs. This section shows you how to remove or add
a VM from the load balancer.
Remove a VM from the load balancer
Get the network interface card with Get-AzNetworkInterface, then set the LoadBalancerBackendAddressPools
property of the virtual NIC to $null. Finally, update the virtual NIC.:

$nic = Get-AzNetworkInterface `
-ResourceGroupName "myResourceGroupLoadBalancer" `
-Name "myVM2"
$nic.Ipconfigurations[0].LoadBalancerBackendAddressPools=$null
Set-AzNetworkInterface -NetworkInterface $nic

To see the load balancer distribute traffic across the remaining two VMs running your app you can force-refresh
your web browser. You can now perform maintenance on the VM, such as installing OS updates or performing a
VM reboot.
Add a VM to the load balancer
After performing VM maintenance, or if you need to expand capacity, set the LoadBalancerBackendAddressPools
property of the virtual NIC to the BackendAddressPool from Get-AzLoadBalancer:
Get the load balancer:

$lb = Get-AzLoadBalancer `
-ResourceGroupName myResourceGroupLoadBalancer `
-Name myLoadBalancer
$nic.IpConfigurations[0].LoadBalancerBackendAddressPools=$lb.BackendAddressPools[0]
Set-AzNetworkInterface -NetworkInterface $nic

Next steps
In this tutorial, you created a load balancer and attached VMs to it. You learned how to:
Create an Azure load balancer
Create a load balancer health probe
Create load balancer traffic rules
Use the Custom Script Extension to create a basic IIS site
Create virtual machines and attach to a load balancer
View a load balancer in action
Add and remove VMs from a load balancer
Advance to the next tutorial to learn how to manage VM networking.
Manage VMs and virtual networks
Tutorial: Create and manage Azure virtual networks
for Windows virtual machines with Azure PowerShell
11/13/2019 • 7 minutes to read • Edit Online

Azure virtual machines use Azure networking for internal and external network communication. This tutorial walks
through deploying two virtual machines and configuring Azure networking for these VMs. The examples in this
tutorial assume that the VMs are hosting a web application with a database back-end, however an application isn't
deployed in the tutorial. In this tutorial, you learn how to:
Create a virtual network and subnet
Create a public IP address
Create a front-end VM
Secure network traffic
Create back-end VM

VM networking overview
Azure virtual networks enable secure network connections between virtual machines, the internet, and other Azure
services such as Azure SQL database. Virtual networks are broken down into logical segments called subnets.
Subnets are used to control network flow, and as a security boundary. When deploying a VM, it generally includes
a virtual network interface, which is attached to a subnet.
While completing this tutorial, you can see these resources created:

myVNet - The virtual network that the VMs use to communicate with each other and the internet.
myFrontendSubnet - The subnet in myVNet used by the front-end resources.
myPublicIPAddress - The public IP address used to access myFrontendVM from the internet.
myFrontendNic - The network interface used by myFrontendVM to communicate with myBackendVM.
myFrontendVM - The VM used to communicate between the internet and myBackendVM.
myBackendNSG - The network security group that controls communication between the myFrontendVM and
myBackendVM.
myBackendSubnet - The subnet associated with myBackendNSG and used by the back-end resources.
myBackendNic - The network interface used by myBackendVM to communicate with myFrontendVM.
myBackendVM - The VM that uses port 1433 to communicate with myFrontendVM.

Launch Azure Cloud Shell


The Azure Cloud Shell is a free interactive shell that you can use to run the steps in this article. It has common
Azure tools preinstalled and configured to use with your account.
To open the Cloud Shell, just select Try it from the upper right corner of a code block. You can also launch Cloud
Shell in a separate browser tab by going to https://shell.azure.com/powershell. Select Copy to copy the blocks of
code, paste it into the Cloud Shell, and press enter to run it.

Create subnet
For this tutorial, a single virtual network is created with two subnets. A front-end subnet for hosting a web
application, and a back-end subnet for hosting a database server.
Before you can create a virtual network, create a resource group using New -AzResourceGroup. The following
example creates a resource group named myRGNetwork in the EastUS location:

New-AzResourceGroup -ResourceGroupName myRGNetwork -Location EastUS

Create a subnet configuration named myFrontendSubnet using New -AzVirtualNetworkSubnetConfig:

$frontendSubnet = New-AzVirtualNetworkSubnetConfig `
-Name myFrontendSubnet `
-AddressPrefix 10.0.0.0/24

And, create a subnet configuration named myBackendSubnet:

$backendSubnet = New-AzVirtualNetworkSubnetConfig `
-Name myBackendSubnet `
-AddressPrefix 10.0.1.0/24

Create virtual network


Create a VNET named myVNet using myFrontendSubnet and myBackendSubnet using New -AzVirtualNetwork:

$vnet = New-AzVirtualNetwork `
-ResourceGroupName myRGNetwork `
-Location EastUS `
-Name myVNet `
-AddressPrefix 10.0.0.0/16 `
-Subnet $frontendSubnet, $backendSubnet

At this point, a network has been created and segmented into two subnets, one for front-end services, and another
for back-end services. In the next section, virtual machines are created and connected to these subnets.

Create a public IP address


A public IP address allows Azure resources to be accessible on the internet. The allocation method of the public IP
address can be configured as dynamic or static. By default, a public IP address is dynamically allocated. Dynamic
IP addresses are released when a VM is deallocated. This behavior causes the IP address to change during any
operation that includes a VM deallocation.
The allocation method can be set to static, which makes sure that the IP address stays assigned to a VM, even
during a deallocated state. If you are using a static IP address, the IP address itself can't be specified. Instead, it's
allocated from a pool of available addresses.
Create a public IP address named myPublicIPAddress using New -AzPublicIpAddress:

$pip = New-AzPublicIpAddress `
-ResourceGroupName myRGNetwork `
-Location EastUS `
-AllocationMethod Dynamic `
-Name myPublicIPAddress

You could change the -AllocationMethod parameter to Static to assign a static public IP address.

Create a front-end VM
For a VM to communicate in a virtual network, it needs a virtual network interface (NIC ). Create a NIC using
New -AzNetworkInterface:

$frontendNic = New-AzNetworkInterface `
-ResourceGroupName myRGNetwork `
-Location EastUS `
-Name myFrontend `
-SubnetId $vnet.Subnets[0].Id `
-PublicIpAddressId $pip.Id

Set the username and password needed for the administrator account on the VM using Get-Credential. You use
these credentials to connect to the VM in additional steps:

$cred = Get-Credential

Create the VMs using New -AzVM.

New-AzVM `
-Credential $cred `
-Name myFrontend `
-PublicIpAddressName myPublicIPAddress `
-ResourceGroupName myRGNetwork `
-Location "EastUS" `
-Size Standard_D1 `
-SubnetName myFrontendSubnet `
-VirtualNetworkName myVNet

Secure network traffic


A network security group (NSG ) contains a list of security rules that allow or deny network traffic to resources
connected to Azure Virtual Networks (VNet). NSGs can be associated to subnets or individual network interfaces.
An NSG is associated with a network interface only applies to the associated VM. When an NSG is associated to a
subnet, the rules apply to all resources connected to the subnet.
Network security group rules
NSG rules define networking ports over which traffic is allowed or denied. The rules can include source and
destination IP address ranges so that traffic is controlled between specific systems or subnets. NSG rules also
include a priority (between 1—and 4096). Rules are evaluated in the order of priority. A rule with a priority of 100
is evaluated before a rule with priority 200.
All NSGs contain a set of default rules. The default rules can't be deleted, but because they are assigned the lowest
priority, they can be overridden by the rules that you create.
Virtual network - Traffic originating and ending in a virtual network is allowed both in inbound and outbound
directions.
Internet - Outbound traffic is allowed, but inbound traffic is blocked.
Load balancer - Allow Azure’s load balancer to probe the health of your VMs and role instances. If you are not
using a load balanced set, you can override this rule.
Create network security groups
Create an inbound rule named myFrontendNSGRule to allow incoming web traffic on myFrontendVM using
New -AzNetworkSecurityRuleConfig:

$nsgFrontendRule = New-AzNetworkSecurityRuleConfig `
-Name myFrontendNSGRule `
-Protocol Tcp `
-Direction Inbound `
-Priority 200 `
-SourceAddressPrefix * `
-SourcePortRange * `
-DestinationAddressPrefix * `
-DestinationPortRange 80 `
-Access Allow

You can limit internal traffic to myBackendVM from only myFrontendVM by creating an NSG for the back-end
subnet. The following example creates an NSG rule named myBackendNSGRule:

$nsgBackendRule = New-AzNetworkSecurityRuleConfig `
-Name myBackendNSGRule `
-Protocol Tcp `
-Direction Inbound `
-Priority 100 `
-SourceAddressPrefix 10.0.0.0/24 `
-SourcePortRange * `
-DestinationAddressPrefix * `
-DestinationPortRange 1433 `
-Access Allow

Add a network security group named myFrontendNSG using New -AzNetworkSecurityGroup:

$nsgFrontend = New-AzNetworkSecurityGroup `
-ResourceGroupName myRGNetwork `
-Location EastUS `
-Name myFrontendNSG `
-SecurityRules $nsgFrontendRule

Now, add a network security group named myBackendNSG using New -AzNetworkSecurityGroup:
$nsgBackend = New-AzNetworkSecurityGroup `
-ResourceGroupName myRGNetwork `
-Location EastUS `
-Name myBackendNSG `
-SecurityRules $nsgBackendRule

Add the network security groups to the subnets:

$vnet = Get-AzVirtualNetwork `
-ResourceGroupName myRGNetwork `
-Name myVNet
$frontendSubnet = $vnet.Subnets[0]
$backendSubnet = $vnet.Subnets[1]
$frontendSubnetConfig = Set-AzVirtualNetworkSubnetConfig `
-VirtualNetwork $vnet `
-Name myFrontendSubnet `
-AddressPrefix $frontendSubnet.AddressPrefix `
-NetworkSecurityGroup $nsgFrontend
$backendSubnetConfig = Set-AzVirtualNetworkSubnetConfig `
-VirtualNetwork $vnet `
-Name myBackendSubnet `
-AddressPrefix $backendSubnet.AddressPrefix `
-NetworkSecurityGroup $nsgBackend
Set-AzVirtualNetwork -VirtualNetwork $vnet

Create a back-end VM
The easiest way to create the back-end VM for this tutorial is by using a SQL Server image. This tutorial only
creates the VM with the database server, but doesn't provide information about accessing the database.
Create myBackendNic:

$backendNic = New-AzNetworkInterface `
-ResourceGroupName myRGNetwork `
-Location EastUS `
-Name myBackend `
-SubnetId $vnet.Subnets[1].Id

Set the username and password needed for the administrator account on the VM with Get-Credential:

$cred = Get-Credential

Create myBackendVM.

New-AzVM `
-Credential $cred `
-Name myBackend `
-ImageName "MicrosoftSQLServer:SQL2016SP1-WS2016:Enterprise:latest" `
-ResourceGroupName myRGNetwork `
-Location "EastUS" `
-SubnetName MyBackendSubnet `
-VirtualNetworkName myVNet

The image in this example has SQL Server installed, but it isn't used in this tutorial. It's included to show you how
you can configure a VM to handle web traffic and a VM to handle database management.
Next steps
In this tutorial, you created and secured Azure networks as related to virtual machines.
Create a virtual network and subnet
Create a public IP address
Create a front-end VM
Secure network traffic
Create a back-end VM
Advance to the next tutorial to learn about monitoring securing data on virtual machines using Azure backup.
Back up Windows virtual machines in Azure
Tutorial: Back up and restore files for Windows virtual
machines in Azure
11/13/2019 • 4 minutes to read • Edit Online

You can protect your data by taking backups at regular intervals. Azure Backup creates recovery points that are
stored in geo-redundant recovery vaults. When you restore from a recovery point, you can restore the whole VM
or specific files. This article explains how to restore a single file to a VM running Windows Server and IIS. If you
don't already have a VM to use, you can create one using the Windows quickstart. In this tutorial you learn how to:
Create a backup of a VM
Schedule a daily backup
Restore a file from a backup

Backup overview
When the Azure Backup service initiates a backup job, it triggers the backup extension to take a point-in-time
snapshot. The Azure Backup service uses the VMSnapshot extension. The extension is installed during the first VM
backup if the VM is running. If the VM is not running, the Backup service takes a snapshot of the underlying
storage (since no application writes occur while the VM is stopped).
When taking a snapshot of Windows VMs, the Backup service coordinates with the Volume Shadow Copy Service
(VSS ) to get a consistent snapshot of the virtual machine's disks. Once the Azure Backup service takes the
snapshot, the data is transferred to the vault. To maximize efficiency, the service identifies and transfers only the
blocks of data that have changed since the previous backup.
When the data transfer is complete, the snapshot is removed and a recovery point is created.

Create a backup
Create a simple scheduled daily backup to a Recovery Services Vault.
1. Sign in to the Azure portal.
2. In the menu on the left, select Virtual machines.
3. From the list, select a VM to back up.
4. On the VM blade, in the Operations section, click Backup. The Enable backup blade opens.
5. In Recovery Services vault, click Create new and provide the name for the new vault. A new vault is
created in the same resource group and location as the virtual machine.
6. Under Choose backup policy, keep the default (New) DailyPolicy, and then click Enable Backup.
7. To create an initial recovery point, on the Backup blade click Backup now.
8. On the Backup Now blade, click the calendar icon, use the calendar control to choose how long the restore
point is retained, and click OK.
9. In the Backup blade for your VM, you'll see the number of restore points that are complete.
The first backup takes about 20 minutes. Proceed to the next part of this tutorial after your backup is finished.

Recover a file
If you accidentally delete or make changes to a file, you can use File Recovery to recover the file from your backup
vault. File Recovery uses a script that runs on the VM, to mount the recovery point as local drive. These drives
remain mounted for 12 hours so that you can copy files from the recovery point and restore them to the VM.
In this example, we show how to recover the image file that is used in the default web page for IIS.
1. Open a browser and connect to the IP address of the VM to show the default IIS page.

2. Connect to the VM.


3. On the VM, open File Explorer and navigate to \inetpub\wwwroot and delete the file iisstart.png.
4. On your local computer, refresh the browser to see that the image on the default IIS page is gone.
5. On your local computer, open a new tab and go the Azure portal.
6. In the menu on the left, select Virtual machines and select the VM from the list.
7. On the VM blade, in the Operations section, click Backup. The Backup blade opens.
8. In the menu at the top of the blade, select File Recovery. The File Recovery blade opens.
9. In Step 1: Select recovery point, select a recovery point from the drop-down.
10. In Step 2: Download script to browse and recover files, click the Download Executable button. Copy
the password for the file and save it somewhere safe.
11. On your local computer, open File Explorer and navigate to your Downloads folder and copy the
downloaded .exe file. The filename is prefixed by your VM name.
12. On your VM (using the RDP connection), paste the .exe file to the Desktop of your VM.
13. Navigate to the desktop of your VM and double-click on the .exe. A command prompt will start. The
program mounts the recovery point as a file share that you can access. When it is finished creating the
share, type q to close the command prompt.
14. On your VM, open File Explorer and navigate to the drive letter that was used for the file share.
15. Navigate to \inetpub\wwwroot and copy iisstart.png from the file share and paste it into
\inetpub\wwwroot. For example, copy F:\inetpub\wwwroot\iisstart.png and paste it into
c:\inetpub\wwwroot to recover the file.
16. On your local computer, open the browser tab where you are connected to the IP address of the VM
showing the IIS default page. Press CTRL + F5 to refresh the browser page. You should now see that the
image has been restored.
17. On your local computer, go back to the browser tab for the Azure portal and in Step 3: Unmount the
disks after recovery click the Unmount Disks button. If you forget to do this step, the connection to the
mountpoint is automatically closed after 12 hours. After those 12 hours, you need to download a new script
to create a new mount point.

Next steps
In this tutorial, you learned how to:
Create a backup of a VM
Schedule a daily backup
Restore a file from a backup
Advance to the next tutorial to learn about monitoring virtual machines.
Govern virtual machines
Tutorial: Learn about Windows virtual machine
management with Azure PowerShell
1/14/2020 • 10 minutes to read • Edit Online

When deploying resources to Azure, you have tremendous flexibility when deciding what types of resources to
deploy, where they are located, and how to set them up. However, that flexibility may open more options than you
would like to allow in your organization. As you consider deploying resources to Azure, you might be wondering:
How do I meet legal requirements for data sovereignty in certain countries/regions?
How do I control costs?
How do I ensure that someone does not inadvertently change a critical system?
How do I track resource costs and bill it accurately?
This article addresses those questions. Specifically, you:
Assign users to roles and assign the roles to a scope so users have permission to perform expected actions but
not more actions.
Apply policies that prescribe conventions for resources in your subscription.
Lock resources that are critical to your system.
Tag resources so you can track them by values that make sense to your organization.
This article focuses on the tasks you take to implement governance. For a broader discussion of the concepts, see
Governance in Azure.

Launch Azure Cloud Shell


The Azure Cloud Shell is a free interactive shell that you can use to run the steps in this article. It has common
Azure tools preinstalled and configured to use with your account.
To open the Cloud Shell, just select Try it from the upper right corner of a code block. You can also launch Cloud
Shell in a separate browser tab by going to https://shell.azure.com/powershell. Select Copy to copy the blocks of
code, paste it into the Cloud Shell, and press enter to run it.

Understand scope
Before creating any items, let's review the concept of scope. Azure provides four levels of management:
management groups, subscription, resource group, and resource. Management groups are in a preview release.
The following image shows an example of these layers.
You apply management settings at any of these levels of scope. The level you select determines how widely the
setting is applied. Lower levels inherit settings from higher levels. When you apply a setting to the subscription,
that setting is applied to all resource groups and resources in your subscription. When you apply a setting on the
resource group, that setting is applied the resource group and all its resources. However, another resource group
does not have that setting.
Usually, it makes sense to apply critical settings at higher levels and project-specific requirements at lower levels.
For example, you might want to make sure all resources for your organization are deployed to certain regions. To
accomplish this requirement, apply a policy to the subscription that specifies the allowed locations. As other users
in your organization add new resource groups and resources, the allowed locations are automatically enforced.
In this tutorial, you apply all management settings to a resource group so you can easily remove those settings
when done.
Let's create that resource group.

New-AzResourceGroup -Name myResourceGroup -Location EastUS

Currently, the resource group is empty.

Role-based access control


You want to make sure users in your organization have the right level of access to these resources. You don't want
to grant unlimited access to users, but you also need to make sure they can do their work. Role-based access
control enables you to manage which users have permission to complete specific actions at a scope.
To create and remove role assignments, users must have Microsoft.Authorization/roleAssignments/* access. This
access is granted through the Owner or User Access Administrator roles.
For managing virtual machine solutions, there are three resource-specific roles that provide commonly needed
access:
Virtual Machine Contributor
Network Contributor
Storage Account Contributor
Instead of assigning roles to individual users, it's often easier to use an Azure Active Directory group that has users
who need to take similar actions. Then, assign that group to the appropriate role. For this article, either use an
existing group for managing the virtual machine, or use the portal to create an Azure Active Directory group.
After creating a new group or finding an existing one, use the New -AzRoleAssignment command to assign the
Azure Active Directory group to the Virtual Machine Contributor role for the resource group.
$adgroup = Get-AzADGroup -DisplayName <your-group-name>

New-AzRoleAssignment -ObjectId $adgroup.id `


-ResourceGroupName myResourceGroup `
-RoleDefinitionName "Virtual Machine Contributor"

If you receive an error stating Principal <guid> does not exist in the directory, the new group hasn't
propagated throughout Azure Active Directory. Try running the command again.
Typically, you repeat the process for Network Contributor and Storage Account Contributor to make sure users
are assigned to manage the deployed resources. In this article, you can skip those steps.

Azure Policy
Azure Policy helps you make sure all resources in subscription meet corporate standards. Your subscription already
has several policy definitions. To see the available policy definitions, use the Get-AzPolicyDefinition command:

(Get-AzPolicyDefinition).Properties | Format-Table displayName, policyType

You see the existing policy definitions. The policy type is either BuiltIn or Custom. Look through the definitions
for ones that describe a condition you want assign. In this article, you assign policies that:
Limit the locations for all resources.
Limit the SKUs for virtual machines.
Audit virtual machines that don't use managed disks.
In the following example, you retrieve three policy definitions based on the display name. You use the New -
AzPolicyAssignment command to assign those definitions to the resource group. For some policies, you provide
parameter values to specify the allowed values.
# Values to use for parameters
$locations ="eastus", "eastus2"
$skus = "Standard_DS1_v2", "Standard_E2s_v2"

# Get the resource group


$rg = Get-AzResourceGroup -Name myResourceGroup

# Get policy definitions for allowed locations, allowed SKUs, and auditing VMs that don't use managed disks
$locationDefinition = Get-AzPolicyDefinition | where-object {$_.properties.displayname -eq "Allowed
locations"}
$skuDefinition = Get-AzPolicyDefinition | where-object {$_.properties.displayname -eq "Allowed virtual machine
SKUs"}
$auditDefinition = Get-AzPolicyDefinition | where-object {$_.properties.displayname -eq "Audit VMs that do not
use managed disks"}

# Assign policy for allowed locations


New-AzPolicyAssignment -Name "Set permitted locations" `
-Scope $rg.ResourceId `
-PolicyDefinition $locationDefinition `
-listOfAllowedLocations $locations

# Assign policy for allowed SKUs


New-AzPolicyAssignment -Name "Set permitted VM SKUs" `
-Scope $rg.ResourceId `
-PolicyDefinition $skuDefinition `
-listOfAllowedSKUs $skus

# Assign policy for auditing unmanaged disks


New-AzPolicyAssignment -Name "Audit unmanaged disks" `
-Scope $rg.ResourceId `
-PolicyDefinition $auditDefinition

Deploy the virtual machine


You have assigned roles and policies, so you're ready to deploy your solution. The default size is Standard_DS1_v2,
which is one of your allowed SKUs. When running this step, you're prompted for credentials. The values that you
enter are configured as the user name and password for the virtual machine.

New-AzVm -ResourceGroupName "myResourceGroup" `


-Name "myVM" `
-Location "East US" `
-VirtualNetworkName "myVnet" `
-SubnetName "mySubnet" `
-SecurityGroupName "myNetworkSecurityGroup" `
-PublicIpAddressName "myPublicIpAddress" `
-OpenPorts 80,3389

After your deployment finishes, you can apply more management settings to the solution.

Lock resources
Resource locks prevent users in your organization from accidentally deleting or modifying critical resources. Unlike
role-based access control, resource locks apply a restriction across all users and roles. You can set the lock level to
CanNotDelete or ReadOnly.
To lock the virtual machine and network security group, use the New -AzResourceLock command:
# Add CanNotDelete lock to the VM
New-AzResourceLock -LockLevel CanNotDelete `
-LockName LockVM `
-ResourceName myVM `
-ResourceType Microsoft.Compute/virtualMachines `
-ResourceGroupName myResourceGroup

# Add CanNotDelete lock to the network security group


New-AzResourceLock -LockLevel CanNotDelete `
-LockName LockNSG `
-ResourceName myNetworkSecurityGroup `
-ResourceType Microsoft.Network/networkSecurityGroups `
-ResourceGroupName myResourceGroup

To test the locks, try running the following command:

Remove-AzResourceGroup -Name myResourceGroup

You see an error stating that the delete operation can't be completed because of a lock. The resource group can
only be deleted if you specifically remove the locks. That step is shown in Clean up resources.

Tag resources
You apply tags to your Azure resources to logically organize them by categories. Each tag consists of a name and a
value. For example, you can apply the name "Environment" and the value "Production" to all the resources in
production.
To add two tags to a resource group, use the Set-AzResourceGroup command:

Set-AzResourceGroup -Name myResourceGroup -Tag @{ Dept="IT"; Environment="Test" }

Let's suppose you want to add a third tag. Every time you apply tags to a resource or a resource group, you
overwrite the existing tags on that resource or resource group. To add a new tag without losing the existing tags,
you must retrieve the existing tags, add a new tag, and reapply the collection of tags:

# Get existing tags and add a new tag


$tags = (Get-AzResourceGroup -Name myResourceGroup).Tags
$tags.Add("Project", "Documentation")

# Reapply the updated set of tags


Set-AzResourceGroup -Tag $tags -Name myResourceGroup

Resources don't inherit tags from the resource group. Currently, your resource group has three tags but the
resources do not have any tags. To apply all tags from a resource group to its resources, and retain existing tags on
resources that are not duplicates, use the following script:
# Get the resource group
$group = Get-AzResourceGroup myResourceGroup

if ($group.Tags -ne $null) {


# Get the resources in the resource group
$resources = Get-AzResource -ResourceGroupName $group.ResourceGroupName

# Loop through each resource


foreach ($r in $resources)
{
# Get the tags for this resource
$resourcetags = (Get-AzResource -ResourceId $r.ResourceId).Tags

# If the resource has existing tags, add new ones


if ($resourcetags)
{
foreach ($key in $group.Tags.Keys)
{
if (-not($resourcetags.ContainsKey($key)))
{
$resourcetags.Add($key, $group.Tags[$key])
}
}

# Reapply the updated tags to the resource


Set-AzResource -Tag $resourcetags -ResourceId $r.ResourceId -Force
}
else
{
Set-AzResource -Tag $group.Tags -ResourceId $r.ResourceId -Force
}
}
}

Alternatively, you can apply tags from the resource group to the resources without keeping the existing tags:

# Get the resource group


$g = Get-AzResourceGroup -Name myResourceGroup

# Find all the resources in the resource group, and for each resource apply the tags from the resource group
Get-AzResource -ResourceGroupName $g.ResourceGroupName | ForEach-Object {Set-AzResource -ResourceId
$_.ResourceId -Tag $g.Tags -Force }

To combine several values in a single tag, use a JSON string.

Set-AzResourceGroup -Name myResourceGroup -Tag @{ CostCenter="{`"Dept`":`"IT`",`"Environment`":`"Test`"}" }

To add a new tag with several values without losing the existing tags, you must retrieve the existing tags, use a
JSON string for the new tag, and reapply the collection of tags:

# Get existing tags and add a new tag


$ResourceGroup = Get-AzResourceGroup -Name myResourceGroup
$Tags = $ResourceGroup.Tags
$Tags.Add("CostCenter", "{`"Dept`":`"IT`",`"Environment`":`"Test`"}")

# Reapply the updated set of tags


$ResourceGroup | Set-AzResourceGroup -Tag $Tags

To remove all tags, you pass an empty hash table.


Set-AzResourceGroup -Name myResourceGroup -Tag @{ }

To apply tags to a virtual machine, use the Set-AzResource command:

# Get the virtual machine


$r = Get-AzResource -ResourceName myVM `
-ResourceGroupName myResourceGroup `
-ResourceType Microsoft.Compute/virtualMachines

# Apply tags to the virtual machine


Set-AzResource -Tag @{ Dept="IT"; Environment="Test"; Project="Documentation" } -ResourceId $r.ResourceId -
Force

Find resources by tag


To find resources with a tag name and value, use the Get-AzResource command:

(Get-AzResource -Tag @{ Environment="Test"}).Name

You can use the returned values for management tasks like stopping all virtual machines with a tag value.

Get-AzResource -Tag @{ Environment="Test"} | Where-Object {$_.ResourceType -eq


"Microsoft.Compute/virtualMachines"} | Stop-AzVM

View costs by tag values


After applying tags to resources, you can view costs for resources with those tags. It takes a while for cost analysis
to show the latest usage, so you may not see the costs yet. When the costs are available, you can view costs for
resources across resource groups in your subscription. Users must have subscription level access to billing
information to see the costs.
To view costs by tag in the portal, select your subscription and select Cost Analysis.

Then, filter by the tag value, and select Apply.


You can also use the Azure Billing APIs to programmatically view costs.

Clean up resources
The locked network security group can't be deleted until the lock is removed. To remove the lock, use the Remove-
AzResourceLock command:

Remove-AzResourceLock -LockName LockVM `


-ResourceName myVM `
-ResourceType Microsoft.Compute/virtualMachines `
-ResourceGroupName myResourceGroup
Remove-AzResourceLock -LockName LockNSG `
-ResourceName myNetworkSecurityGroup `
-ResourceType Microsoft.Network/networkSecurityGroups `
-ResourceGroupName myResourceGroup

When no longer needed, you can use the Remove-AzResourceGroup command to remove the resource group,
VM, and all related resources.

Remove-AzResourceGroup -Name myResourceGroup

Next steps
In this tutorial, you created a custom VM image. You learned how to:
Assign users to a role
Apply policies that enforce standards
Protect critical resources with locks
Tag resources for billing and management
Advance to the next tutorial to learn about how to identify changes and manage package updates on a Linux
virtual machine.
Manage virtual machines
Tutorial: Monitor changes and update a Windows
virtual machine in Azure
11/13/2019 • 9 minutes to read • Edit Online

With Azure Change Tracking and Update Management, you can easily identify changes in your Windows virtual
machines in Azure and manage operating system updates for those VMs.
In this tutorial, you learn how to:
Manage Windows updates.
Monitor changes and inventory.

Open Azure Cloud Shell


Azure Cloud Shell is a free interactive shell that you can use to run the steps in this article. It has common Azure
tools preinstalled and configured to use with your Azure account.
To open any code block in Cloud Shell, just select Try it from the upper-right corner of that code block.
You can also open Cloud Shell in a separate browser tab by going to https://shell.azure.com/powershell. Select
Copy to copy code blocks, paste them into the Cloud Shell tab, and select the Enter key to run the code.

Create a virtual machine


To configure Azure monitoring and update management in this tutorial, you need a Windows VM in Azure.
First, set an administrator username and password for the VM with Get-Credential:

$cred = Get-Credential

Next, create the VM with New -AzVM. The following example creates a VM named myVM in the East US location.
If they don't already exist, the resource group myResourceGroupMonitor and supporting network resources are
created:

New-AzVm `
-ResourceGroupName "myResourceGroupMonitor" `
-Name "myVM" `
-Location "East US" `
-Credential $cred

It takes a few minutes for the resources and VM to be created.

Manage Windows updates


Update Management helps you manage updates and patches for your Azure Windows VMs. Directly from your
VM, you can quickly:
Assess the status of available updates.
Schedule installation of required updates.
Review deployment results to verify updates were successfully applied to the VM.
For pricing information, see Automation pricing for Update management.
Enable Update Management
To enable Update Management for your VM:
1. On the leftmost side of the window, select Virtual machines.
2. Choose a VM from the list.
3. In the Operations pane of the VM window, select Update management.
4. The Enable Update Management window opens.
Validation is done to determine if Update Management is enabled for this VM. Validation includes checks for a Log
Analytics workspace, for a linked Automation account, and for whether the solution is in the workspace.
You use a Log Analytics workspace to collect data that is generated by features and services such as Update
Management. The workspace provides a single location to review and analyze data from multiple sources.
To perform additional actions on VMs that require updates, you can use Azure Automation to run runbooks
against VMs. Such actions include downloading or applying updates.
The validation process also checks to see if the VM is provisioned with the Microsoft Monitoring Agent (MMA)
and Automation Hybrid Runbook Worker. You use the agent to communicate with the VM and obtain information
about the update status.
In the Enable Update Management window, choose the Log Analytics workspace and automation account, and
then select Enable. The solution takes up to 15 minutes to become enabled.
Any of the following prerequisites that are missing during onboarding are automatically added:
Log Analytics workspace
Automation
A Hybrid runbook worker, which is enabled on the VM
After the solution is enabled, the Update management window opens. Configure the location, Log Analytics
workspace and Automation account to use, and then select Enable. If these options appear dimmed, another
automation solution is enabled for the VM, and that solution's workspace and Automation account must be used.
The Update Management solution can take up to 15 minutes to become enabled. During this time, don't close the
browser window. After the solution is enabled, information about missing updates on the VM flows to Azure
Monitor logs. It can take from 30 minutes to 6 hours for the data to become available for analysis.
View an update assessment
After Update Management is enabled, the Update management window appears. After the evaluation of
updates is finished, you see a list of missing updates on the Missing updates tab.

Schedule an update deployment


To install updates, schedule a deployment that follows your release schedule and service window. You choose
which update types to include in the deployment. For example, you can include critical or security updates and
exclude update rollups.
To schedule a new update deployment for the VM, select Schedule update deployment at the top of the
Update management window. In the New update deployment window, specify the following information:

OPTION DESCRIPTION

Name Enter a unique name to identify the update deployment.


OPTION DESCRIPTION

Operating system Select either Linux or Windows.

Groups to update For VMs hosted on Azure, define a query based on a


combination of subscription, resource groups, locations, and
tags. This query builds a dynamic group of Azure-hosted VMs
to include in your deployment.
For VMs not hosted on Azure, select an existing saved search.
With this search, you can select a group of these VMs to
include in the deployment.

To learn more, see Dynamic Groups.

Machines to update Select Saved search, Imported group, or Machines.

If you select Machines, you can choose individual machines


from the drop-down list. The readiness of each machine is
shown in the UPDATE AGENT READINESS column of the
table.

To learn about the different methods of creating computer


groups in Azure Monitor logs, see Computer groups in Azure
Monitor logs

Update classifications Choose all necessary update classifications.

Include/exclude updates Select this option to open the Include/Exclude pane. Updates
to be included and those to be excluded are on separate tabs.
For more information on how inclusion is handled, see
Schedule an Update Deployment.

Schedule settings Choose the time to start, and select either Once or
Recurring.

Pre-scripts + Post-scripts Choose the scripts to run before and after your deployment.

Maintenance window Enter the number of minutes set for updates. Valid values
range from 30 to 360 minutes.

Reboot control Select how reboots are handled. Available selections are:
Reboot if required
Always reboot
Never reboot
Only reboot
Reboot if required is the default selection. If you select Only
reboot, updates aren't installed.

After you have finished configuring the schedule, click Create to return to the status dashboard. The Scheduled
table shows the deployment schedule you created.
You can also create update deployments programmatically. To learn how to create an update deployment with the
REST API, see Software Update Configurations - Create. There's also a sample runbook that you can use to create
a weekly update deployment. To learn more about this runbook, see Create a weekly update deployment for one or
more VMs in a resource group.
View results of an update deployment
After the scheduled deployment starts, you can see the deployment status in the Update deployments tab of the
Update management window.
If the deployment is currently running, its status shows as "In progress." After successful completion, the status
changes to "Succeeded." But if any updates in the deployment fail, the status is "Partially failed."
Select the completed update deployment to see the dashboard for that deployment.

The Update results tile shows a summary of the total number of updates and deployment results on the VM. The
table to the right shows a detailed breakdown of each update and the installation results. Each result has one of the
following values:
Not attempted: The update isn't installed. There wasn't enough time available based on the defined
maintenance-window duration.
Succeeded: The update succeeded.
Failed: The update failed.
Select All logs to see all log entries that the deployment created.
Select the Output tile to see the job stream of the runbook responsible for managing the update deployment on
the target VM.
Select Errors to see detailed information about any deployment errors.

Monitor changes and inventory


You can collect and view an inventory of the software, files, Linux daemons, Windows services, and Windows
registry keys on your computers. Tracking the configurations of your machines helps you pinpoint operational
issues across your environment and better understand the state of your machines.
Enable change and inventory management
To enable change and inventory management for your VM:
1. On the leftmost side of the window, select Virtual machines.
2. Choose a VM from the list.
3. Under Operations in the VM window, select either Inventory or Change tracking.
4. The Enable Change Tracking and Inventory pane opens.
Configure the location, Log Analytics workspace, and Automation account to use, and then select Enable. If the
options appear dimmed, an automation solution is already enabled for the VM. In that case, the already enabled
workspace and Automation account must be used.
Even though the solutions appear separately in the menu, they're the same solution. Enabling one enables both for
your VM.

After the solution has been enabled, it might take some time for inventory to be collected on the VM before data
appears.
Track changes
On your VM under OPERATIONS, select Change Tracking and then select Edit Settings. The Change
Tracking pane opens. Select the type of setting you want to track and then select + Add to configure the settings.
The available settings options for Windows are:
Windows Registry
Windows Files
For detailed information on Change Tracking, see Troubleshoot changes on a VM.
View inventory
On your VM select Inventory under OPERATIONS. On the Software tab, there's a table that shows the software
that had been found. The high-level details for each software record appear in the table. These details include the
software name, version, publisher, and last refreshed time.
Monitor activity logs and changes
From the Change tracking window on your VM, select Manage Activity Log Connection to open the Azure
Activity log pane. Select Connect to connect Change Tracking to the Azure activity log for your VM.
After Change Tracking is enabled, go to the Overview pane for your VM and select Stop to stop your VM. When
prompted, select Yes to stop the VM. After the VM is deallocated, select Start to restart your VM.
Stopping and restarting a VM logs an event in its activity log. Go back to the Change tracking pane and select the
Events tab at the bottom of the pane. After a while, the events appear in the chart and the table. You can select
each event to view detailed information for that event.

The previous chart shows changes that have occurred over time. After you add an Azure Activity Log connection,
the line graph at the top displays Azure Activity Log events.
Each row of bar graphs represents a different trackable change type. These types are Linux daemons, files,
Windows registry keys, software, and Windows services. The Change tab shows the change details. Changes
appear in the order of when each occurred, with the most recent change shown first.

Next steps
In this tutorial, you configured and reviewed Change Tracking and Update Management for your VM. You learned
how to:
Create a resource group and VM.
Manage Windows updates.
Monitor changes and inventory.
Go to the next tutorial to learn about monitoring your VM.
Monitor virtual machines
Tutorial: Monitor a Windows virtual machine in Azure
11/14/2019 • 4 minutes to read • Edit Online

Azure monitoring uses agents to collect boot and performance data from Azure VMs, store this data in Azure
storage, and make it accessible through portal, the Azure PowerShell module, and Azure CLI. Advanced
monitoring is delivered with Azure Monitor for VMs by collecting performance metrics, discover application
components installed on the VM, and includes performance charts and dependency map.
In this tutorial, you learn how to:
Enable boot diagnostics on a VM
View boot diagnostics
View VM host metrics
Enable Azure Monitor for VMs
View VM performance metrics
Create an alert

Launch Azure Cloud Shell


The Azure Cloud Shell is a free interactive shell that you can use to run the steps in this article. It has common
Azure tools preinstalled and configured to use with your account.
To open the Cloud Shell, just select Try it from the upper right corner of a code block. You can also launch Cloud
Shell in a separate browser tab by going to https://shell.azure.com/powershell. Select Copy to copy the blocks of
code, paste it into the Cloud Shell, and press enter to run it.

Create virtual machine


To configure Azure monitoring and update management in this tutorial, you need a Windows VM in Azure. First,
set an administrator username and password for the VM with Get-Credential:

$cred = Get-Credential

Now create the VM with New -AzVM. The following example creates a VM named myVM in the EastUS location. If
they do not already exist, the resource group myResourceGroupMonitorMonitor and supporting network
resources are created:

New-AzVm `
-ResourceGroupName "myResourceGroupMonitor" `
-Name "myVM" `
-Location "East US" `
-Credential $cred

It takes a few minutes for the resources and VM to be created.

View boot diagnostics


As Windows virtual machines boot up, the boot diagnostic agent captures screen output that can be used for
troubleshooting purpose. This capability is enabled by default. The captured screenshots are stored in an Azure
storage account, which is also created by default.
You can get the boot diagnostic data with the Get-AzureRmVMBootDiagnosticsData command. In the following
example, boot diagnostics are downloaded to the root of the *c:* drive.

Get-AzVMBootDiagnosticsData -ResourceGroupName "myResourceGroupMonitor" -Name "myVM" -Windows -LocalPath "c:\"

View host metrics


A Windows VM has a dedicated Host VM in Azure that it interacts with. Metrics are automatically collected for the
Host and can be viewed in the Azure portal.
1. In the Azure portal, click Resource Groups, select myResourceGroupMonitor, and then select myVM in
the resource list.
2. Click Metrics on the VM blade, and then select any of the Host metrics under Available metrics to see
how the Host VM is performing.

Enable advanced monitoring


To enable monitoring of your Azure VM with Azure Monitor for VMs:
1. In the Azure portal, click Resource Groups, select myResourceGroupMonitor, and then select myVM in
the resource list.
2. On the VM page, in the Monitoring section, select Insights (preview).
3. On the Insights (preview) page, select Try now.
4. On the Azure Monitor Insights Onboarding page, if you have an existing Log Analytics workspace in the
same subscription, select it in the drop-down list.
The list preselects the default workspace and location where the VM is deployed in the subscription.

NOTE
To create a new Log Analytics workspace to store the monitoring data from the VM, see Create a Log Analytics
workspace. Your Log Analytics workspace must belong to one of the supported regions.

After you've enabled monitoring, you might need to wait several minutes before you can view the performance
metrics for the VM.

View VM performance metrics


Azure Monitor for VMs includes a set of performance charts that target several key performance indicators (KPIs)
to help you determine how well a virtual machine is performing. To access from your VM, perform the following
steps.
1. In the Azure portal, click Resource Groups, select myResourceGroupMonitor, and then select myVM in
the resource list.
2. On the VM page, in the Monitoring section, select Insights (preview).
3. Select the Performance tab.
This page not only includes performance utilization charts, but also a table showing for each logical disk
discovered, its capacity, utilization, and total average by each measure.

Create alerts
You can create alerts based on specific performance metrics. Alerts can be used to notify you when average CPU
usage exceeds a certain threshold or available free disk space drops below a certain amount, for example. Alerts
are displayed in the Azure portal or can be sent via email. You can also trigger Azure Automation runbooks or
Azure Logic Apps in response to alerts being generated.
The following example creates an alert for average CPU usage.
1. In the Azure portal, click Resource Groups, select myResourceGroupMonitor, and then select myVM in
the resource list.
2. Click Alert rules on the VM blade, then click Add metric alert across the top of the alerts blade.
3. Provide a Name for your alert, such as myAlertRule
4. To trigger an alert when CPU percentage exceeds 1.0 for five minutes, leave all the other defaults selected.
5. Optionally, check the box for Email owners, contributors, and readers to send email notification. The default
action is to present a notification in the portal.
6. Click the OK button.

Next steps
In this tutorial, you configured and viewed performance of your VM. You learned how to:
Create a resource group and VM
Enable boot diagnostics on the VM
View boot diagnostics
View host metrics
Enable Azure Monitor for VMs
View VM metrics
Create an alert
Advance to the next tutorial to learn about Azure Security Center.
Manage VM security
Tutorial: Use Azure Security Center to monitor
Windows virtual machines
11/13/2019 • 4 minutes to read • Edit Online

Azure Security Center can help you gain visibility into your Azure resource security practices. Security Center
offers integrated security monitoring. It can detect threats that otherwise might go unnoticed. In this tutorial, you
learn about Azure Security Center, and how to:
Set up data collection
Set up security policies
View and fix configuration health issues
Review detected threats

Security Center overview


Security Center identifies potential virtual machine (VM ) configuration issues and targeted security threats. These
might include VMs that are missing network security groups, unencrypted disks, and brute-force Remote Desktop
Protocol (RDP ) attacks. The information is shown on the Security Center dashboard in easy-to-read graphs.
To access the Security Center dashboard, in the Azure portal, on the menu, select Security Center. On the
dashboard, you can see the security health of your Azure environment, find a count of current recommendations,
and view the current state of threat alerts. You can expand each high-level chart to see more detail.

Security Center goes beyond data discovery to provide recommendations for issues that it detects. For example, if
a VM was deployed without an attached network security group, Security Center displays a recommendation, with
remediation steps you can take. You get automated remediation without leaving the context of Security Center.

Set up data collection


Before you can get visibility into VM security configurations, you need to set up Security Center data collection.
This involves turning on data collection which automatically installs the Microsoft Monitoring Agent on all the VMs
in your subscription.
1. On the Security Center dashboard, click Security policy, and then select your subscription.
2. For Data collection, in Auto Provisioning select On.
3. For Default workspace configuration leave it as Use workspace(s) created by Security Center (default).
4. Under Security Events keep the default option of Common.
5. Click Save at the top of the page.
The Security Center data collection agent is then installed on all VMs, and data collection begins.

Set up a security policy


Security policies are used to define the items for which Security Center collects data and makes recommendations.
You can apply different security policies to different sets of Azure resources. Although by default Azure resources
are evaluated against all policy items, you can turn off individual policy items for all Azure resources or for a
resource group. For in-depth information about Security Center security policies, see Set security policies in Azure
Security Center.
To set up a security policy for an entire subscription:
1. On the Security Center dashboard, select Security policy and then select your subscription.
2. On the Security policy blade, select Security policy.
3. On the Security policy - Security policy blade, turn on or turn off policy items that you want to apply to the
subscription.
4. When you're finished selecting your settings, select Save at the top of the blade.
View VM configuration health
After you've turned on data collection and set a security policy, Security Center begins to provide alerts and
recommendations. As VMs are deployed, the data collection agent is installed. Security Center is then populated
with data for the new VMs. For in-depth information about VM configuration health, see Protect your VMs in
Security Center.
As data is collected, the resource health for each VM and related Azure resource is aggregated. The information is
shown in an easy-to-read chart.
To view resource health:
1. On the Security Center dashboard, under Prevention, select Compute.
2. On the Compute blade, select VMs and computers. This view provides a summary of the configuration status
for all your VMs.
To see all recommendations for a VM, select the VM. Recommendations and remediation are covered in more
detail in the next section of this tutorial.

Remediate configuration issues


After Security Center begins to populate with configuration data, recommendations are made based on the
security policy you set up. For instance, if a VM was set up without an associated network security group, a
recommendation is made to create one.
To see a list of all recommendations:
1. On the Security Center dashboard, select Recommendations.
2. Select a specific recommendation. A list of all resources for which the recommendation applies appears.
3. To apply a recommendation, select the resource.
4. Follow the instructions for remediation steps.
In many cases, Security Center provides actionable steps you can take to address a recommendation without
leaving Security Center. In the following example, Security Center detects a network security group that has an
unrestricted inbound rule. On the recommendation page, you can select the Edit inbound rules button. The UI
that is needed to modify the rule appears.
As recommendations are remediated, they are marked as resolved.

View detected threats


In addition to resource configuration recommendations, Security Center displays threat detection alerts. The
security alerts feature aggregates data collected from each VM, Azure networking logs, and connected partner
solutions to detect security threats against Azure resources. For in-depth information about Security Center threat
detection capabilities, see How does Security Center detect threats?.
The security alerts feature requires the Security Center pricing tier to be increased from Free to Standard. A free
trial is available when you move to this higher pricing tier.
To change the pricing tier:
1. On the Security Center dashboard, click Security policy, and then select your subscription.
2. Select Pricing tier.
3. Select Standard and then click Save at the top of the blade.
After you've changed the pricing tier, the security alerts graph begins to populate as security threats are detected.
Select an alert to view information. For example, you can see a description of the threat, the detection time, all
threat attempts, and the recommended remediation. In the following example, an RDP brute-force attack was
detected, with 294 failed RDP attempts. A recommended resolution is provided.
Next steps
In this tutorial, you set up Azure Security Center, and then reviewed VMs in Security Center. You learned how to:
Set up data collection
Set up security policies
View and fix configuration health issues
Review detected threats
Advance to the next tutorial to learn how to install a SQL\IIS\.NET stack on a pair of Windows VMs.
SQL\IIS\.NET stack
Tutorial: Install the SQL, IIS, .NET stack in a Windows
VM with Azure PowerShell
11/13/2019 • 2 minutes to read • Edit Online

In this tutorial, we install a SQL, IIS, .NET stack using Azure PowerShell. This stack consists of two VMs running
Windows Server 2016, one with IIS and .NET and the other with SQL Server.
Create a VM
Install IIS and the .NET Core SDK on the VM
Create a VM running SQL Server
Install the SQL Server extension

Launch Azure Cloud Shell


The Azure Cloud Shell is a free interactive shell that you can use to run the steps in this article. It has common
Azure tools preinstalled and configured to use with your account.
To open the Cloud Shell, just select Try it from the upper right corner of a code block. You can also launch Cloud
Shell in a separate browser tab by going to https://shell.azure.com/powershell. Select Copy to copy the blocks of
code, paste it into the Cloud Shell, and press enter to run it.

Create an IIS VM
In this example, we use New -AzVM cmdlet in the PowerShell Cloud Shell to quickly create a Windows Server
2016 VM and then install IIS and the .NET Framework. The IIS and SQL VMs share a resource group and virtual
network, so we create variables for those names.

$vmName = "IISVM"
$vNetName = "myIISSQLvNet"
$resourceGroup = "myIISSQLGroup"
New-AzVm `
-ResourceGroupName $resourceGroup `
-Name $vmName `
-Location "East US" `
-VirtualNetworkName $vNetName `
-SubnetName "myIISSubnet" `
-SecurityGroupName "myNetworkSecurityGroup" `
-AddressPrefix 192.168.0.0/16 `
-PublicIpAddressName "myIISPublicIpAddress" `
-OpenPorts 80,3389

Install IIS and the .NET framework using the custom script extension with the Set-AzVMExtension cmdlet.
Set-AzVMExtension `
-ResourceGroupName $resourceGroup `
-ExtensionName IIS `
-VMName $vmName `
-Publisher Microsoft.Compute `
-ExtensionType CustomScriptExtension `
-TypeHandlerVersion 1.4 `
-SettingString '{"commandToExecute":"powershell Add-WindowsFeature Web-Server,Web-Asp-Net45,NET-Framework-
Features"}' `
-Location EastUS

Create another subnet


Create a second subnet for the SQL VM. Get the vNet using [Get-AzVirtualNetwork]
{/powershell/module/az.network/get-azvirtualnetwork}.

$vNet = Get-AzVirtualNetwork `
-Name $vNetName `
-ResourceGroupName $resourceGroup

Create a configuration for the subnet using Add-AzVirtualNetworkSubnetConfig.

Add-AzVirtualNetworkSubnetConfig `
-AddressPrefix 192.168.0.0/24 `
-Name mySQLSubnet `
-VirtualNetwork $vNet `
-ServiceEndpoint Microsoft.Sql

Update the vNet with the new subnet information using Set-AzVirtualNetwork

$vNet | Set-AzVirtualNetwork

Azure SQL VM
Use a pre-configured Azure marketplace image of a SQL server to create the SQL VM. We first create the VM,
then we install the SQL Server Extension on the VM.

New-AzVm `
-ResourceGroupName $resourceGroup `
-Name "mySQLVM" `
-ImageName "MicrosoftSQLServer:SQL2016SP1-WS2016:Enterprise:latest" `
-Location eastus `
-VirtualNetworkName $vNetName `
-SubnetName "mySQLSubnet" `
-SecurityGroupName "myNetworkSecurityGroup" `
-PublicIpAddressName "mySQLPublicIpAddress" `
-OpenPorts 3389,1401

Use Set-AzVMSqlServerExtension to add the SQL Server extension to the SQL VM.

Set-AzVMSqlServerExtension `
-ResourceGroupName $resourceGroup `
-VMName mySQLVM `
-Name "SQLExtension" `
-Location "EastUS"
Next steps
In this tutorial, you installed a SQL\IIS\.NET stack using Azure PowerShell. You learned how to:
Create a VM
Install IIS and the .NET Core SDK on the VM
Create a VM running SQL Server
Install the SQL Server extension
Advance to the next tutorial to learn how to secure IIS web server with SSL certificates.
Secure IIS web server with SSL certificates
Tutorial: Secure a web server on a Windows virtual
machine in Azure with SSL certificates stored in Key
Vault
1/17/2020 • 4 minutes to read • Edit Online

NOTE
Currently this doc only works for Generalized images. If attempting this tutorial using a Specialized disk you will receive an
error.

To secure web servers, a Secure Sockets Layer (SSL ) certificate can be used to encrypt web traffic. These SSL
certificates can be stored in Azure Key Vault, and allow secure deployments of certificates to Windows virtual
machines (VMs) in Azure. In this tutorial you learn how to:
Create an Azure Key Vault
Generate or upload a certificate to the Key Vault
Create a VM and install the IIS web server
Inject the certificate into the VM and configure IIS with an SSL binding

Launch Azure Cloud Shell


The Azure Cloud Shell is a free interactive shell that you can use to run the steps in this article. It has common
Azure tools preinstalled and configured to use with your account.
To open the Cloud Shell, just select Try it from the upper right corner of a code block. You can also launch Cloud
Shell in a separate browser tab by going to https://shell.azure.com/powershell. Select Copy to copy the blocks of
code, paste it into the Cloud Shell, and press enter to run it.

Overview
Azure Key Vault safeguards cryptographic keys and secrets, such certificates or passwords. Key Vault helps
streamline the certificate management process and enables you to maintain control of keys that access those
certificates. You can create a self-signed certificate inside Key Vault, or upload an existing, trusted certificate that
you already own.
Rather than using a custom VM image that includes certificates baked-in, you inject certificates into a running VM.
This process ensures that the most up-to-date certificates are installed on a web server during deployment. If you
renew or replace a certificate, you don't also have to create a new custom VM image. The latest certificates are
automatically injected as you create additional VMs. During the whole process, the certificates never leave the
Azure platform or are exposed in a script, command-line history, or template.

Create an Azure Key Vault


Before you can create a Key Vault and certificates, create a resource group with New -AzResourceGroup. The
following example creates a resource group named myResourceGroupSecureWeb in the East US location:
$resourceGroup = "myResourceGroupSecureWeb"
$location = "East US"
New-AzResourceGroup -ResourceGroupName $resourceGroup -Location $location

Next, create a Key Vault with New -AzKeyVault. Each Key Vault requires a unique name, and should be all lower
case. Replace mykeyvault in the following example with your own unique Key Vault name:

$keyvaultName="mykeyvault"
New-AzKeyVault -VaultName $keyvaultName `
-ResourceGroup $resourceGroup `
-Location $location `
-EnabledForDeployment

Generate a certificate and store in Key Vault


For production use, you should import a valid certificate signed by trusted provider with Import-
AzKeyVaultCertificate. For this tutorial, the following example shows how you can generate a self-signed certificate
with Add-AzKeyVaultCertificate that uses the default certificate policy from New -AzKeyVaultCertificatePolicy.

$policy = New-AzKeyVaultCertificatePolicy `
-SubjectName "CN=www.contoso.com" `
-SecretContentType "application/x-pkcs12" `
-IssuerName Self `
-ValidityInMonths 12

Add-AzKeyVaultCertificate `
-VaultName $keyvaultName `
-Name "mycert" `
-CertificatePolicy $policy

Create a virtual machine


Set an administrator username and password for the VM with Get-Credential:

$cred = Get-Credential

Now you can create the VM with New -AzVM. The following example creates a VM named myVM in the EastUS
location. If they do not already exist, the supporting network resources are created. To allow secure web traffic, the
cmdlet also opens port 443.
# Create a VM
New-AzVm `
-ResourceGroupName $resourceGroup `
-Name "myVM" `
-Location $location `
-VirtualNetworkName "myVnet" `
-SubnetName "mySubnet" `
-SecurityGroupName "myNetworkSecurityGroup" `
-PublicIpAddressName "myPublicIpAddress" `
-Credential $cred `
-OpenPorts 443

# Use the Custom Script Extension to install IIS


Set-AzVMExtension -ResourceGroupName $resourceGroup `
-ExtensionName "IIS" `
-VMName "myVM" `
-Location $location `
-Publisher "Microsoft.Compute" `
-ExtensionType "CustomScriptExtension" `
-TypeHandlerVersion 1.8 `
-SettingString '{"commandToExecute":"powershell Add-WindowsFeature Web-Server -IncludeManagementTools"}'

It takes a few minutes for the VM to be created. The last step uses the Azure Custom Script Extension to install the
IIS web server with Set-AzVmExtension.

Add a certificate to VM from Key Vault


To add the certificate from Key Vault to a VM, obtain the ID of your certificate with Get-AzKeyVaultSecret. Add the
certificate to the VM with Add-AzVMSecret:

$certURL=(Get-AzKeyVaultSecret -VaultName $keyvaultName -Name "mycert").id

$vm=Get-AzVM -ResourceGroupName $resourceGroup -Name "myVM"


$vaultId=(Get-AzKeyVault -ResourceGroupName $resourceGroup -VaultName $keyVaultName).ResourceId
$vm = Add-AzVMSecret -VM $vm -SourceVaultId $vaultId -CertificateStore "My" -CertificateUrl $certURL

Update-AzVM -ResourceGroupName $resourceGroup -VM $vm

Configure IIS to use the certificate


Use the Custom Script Extension again with Set-AzVMExtension to update the IIS configuration. This update
applies the certificate injected from Key Vault to IIS and configures the web binding:

$PublicSettings = '{
"fileUris":["https://raw.githubusercontent.com/Azure-Samples/compute-automation-
configurations/master/secure-iis.ps1"],
"commandToExecute":"powershell -ExecutionPolicy Unrestricted -File secure-iis.ps1"
}'

Set-AzVMExtension -ResourceGroupName $resourceGroup `


-ExtensionName "IIS" `
-VMName "myVM" `
-Location $location `
-Publisher "Microsoft.Compute" `
-ExtensionType "CustomScriptExtension" `
-TypeHandlerVersion 1.8 `
-SettingString $publicSettings

Test the secure web app


Obtain the public IP address of your VM with Get-AzPublicIPAddress. The following example obtains the IP
address for myPublicIP created earlier:

Get-AzPublicIPAddress -ResourceGroupName $resourceGroup -Name "myPublicIPAddress" | select "IpAddress"

Now you can open a web browser and enter https://<myPublicIP> in the address bar. To accept the security
warning if you used a self-signed certificate, select Details and then Go on to the webpage:

Your secured IIS website is then displayed as in the following example:


Next steps
In this tutorial, you secured an IIS web server with an SSL certificate stored in Azure Key Vault. You learned how
to:
Create an Azure Key Vault
Generate or upload a certificate to the Key Vault
Create a VM and install the IIS web server
Inject the certificate into the VM and configure IIS with an SSL binding
Follow this link to see pre-built virtual machine script samples.
Windows virtual machine script samples
Azure Virtual Machine PowerShell samples
11/13/2019 • 2 minutes to read • Edit Online

The following table provides links to PowerShell script samples that create and manage Windows virtual
machines (VMs).

Create virtual machines

Quickly create a virtual machine Creates a resource group, a virtual machine, and all related
resources, with a minimum of prompts.

Create a fully configured virtual machine Creates a resource group, a virtual machine, and all related
resources.

Create highly available virtual machines Creates several virtual machines in a highly-available and
load-balanced configuration.

Create a VM and run a configuration script Creates a virtual machine and uses the Azure Custom Script
extension to install IIS.

Create a VM and run a DSC configuration Creates a virtual machine and uses the Azure Desired State
Configuration (DSC) extension to install IIS.

Upload a VHD and create VMs Uploads a local VHD file to Azure, creates an image from the
VHD, and then creates a VM from that image.

Create a VM from a managed OS disk Creates a virtual machine by attaching an existing Managed
Disk as OS disk.

Create a VM from a snapshot Creates a virtual machine from a snapshot by first creating a
managed disk from the snapshot and then attaching the
new managed disk as OS disk.

Manage storage

Create a managed disk from a VHD in the same or a Creates a managed disk from a specialized VHD as an OS
different subscription disk, or from a data VHD as a data disk, in the same or a
different subscription.

Create a managed disk from a snapshot Creates a managed disk from a snapshot.

Copy a managed disk to the same or a different subscription Copies a managed disk to the same or a different
subscription that is in the same region as the parent
managed disk.

Export a snapshot as a VHD to a storage account Exports a managed snapshot as a VHD to a storage account
in a different region.

Export the VHD of a managed disk to a storage account Exports the underlying VHD of a managed disk to a storage
account in a different region.
Create a snapshot from a VHD Creates a snapshot from a VHD and then uses that snapshot
to create multiple identical managed disks quickly.

Copy a snapshot to the same or a different subscription Copies snapshot to the same or a different subscription that
is in the same region as the parent snapshot.

Secure virtual machines

Encrypt a VM and its data disks Creates an Azure key vault, an encryption key, and a service
principal, and then encrypts a VM.

Monitor virtual machines

Monitor a VM with Azure Monitor Creates a virtual machine, installs the Azure Log Analytics
agent, and enrolls the VM in a Log Analytics workspace.

Collect details about all VMs in a subscription with Creates a csv that contains the VM Name, Resource Group
PowerShell Name, Region, Virtual Network, Subnet, Private IP Address,
OS Type, and Public IP Address of the VMs in the provided
subscription.
Create a virtual machine with PowerShell
11/13/2019 • 2 minutes to read • Edit Online

This script creates an Azure Virtual Machine running Windows Server 2016. After running the script, you can
access the virtual machine over RDP.
If you don't have an Azure subscription, create a free account before you begin.

Sample script
# Variables for common values
$resourceGroup = "myResourceGroup"
$location = "westeurope"
$vmName = "myVM"

# Create user object


$cred = Get-Credential -Message "Enter a username and password for the virtual machine."

# Create a resource group


New-AzResourceGroup -Name $resourceGroup -Location $location

# Create a virtual machine


New-AzVM `
-ResourceGroupName $resourceGroup `
-Name $vmName `
-Location $location `
-ImageName "Win2016Datacenter" `
-VirtualNetworkName "myVnet" `
-SubnetName "mySubnet" `
-SecurityGroupName "myNetworkSecurityGroup" `
-PublicIpAddressName "myPublicIp" `
-Credential $cred `
-OpenPorts 3389

Clean up deployment
Run the following command to remove the resource group, VM, and all related resources.

Remove-AzResourceGroup -Name myResourceGroup

Script explanation
This script uses the following commands to create the deployment. Each item in the table links to command
specific documentation.

COMMAND NOTES

New-AzResourceGroup Creates a resource group in which all resources are stored.

New-AzVM Creates the virtual machine and connects it to the network


card, virtual network, subnet, and network security group.
This command also opens port 80 and sets the administrative
credentials.
COMMAND NOTES

Remove-AzResourceGroup Removes a resource group and all resources contained within.

Next steps
For more information on the Azure PowerShell module, see Azure PowerShell documentation.
Additional virtual machine PowerShell script samples can be found in the Azure Windows VM documentation.
Create a fully configured virtual machine with
PowerShell
11/13/2019 • 2 minutes to read • Edit Online

This script creates an Azure Virtual Machine running Windows Server 2016. After running the script, you can
access the virtual machine over RDP.
This sample requires Azure PowerShell Az 1.0 or later. Run Get-Module -ListAvailable Az to see which versions
are installed. If you need to install, see Install Azure PowerShell module.
Run Connect-AzAccount to sign in to Azure.
If you don't have an Azure subscription, create a free account before you begin.

Sample script
# Variables for common values
$resourceGroup = "myResourceGroup"
$location = "westeurope"
$vmName = "myVM"

# Create user object


$cred = Get-Credential -Message "Enter a username and password for the virtual machine."

# Create a resource group


New-AzResourceGroup -Name $resourceGroup -Location $location

# Create a subnet configuration


$subnetConfig = New-AzVirtualNetworkSubnetConfig -Name mySubnet -AddressPrefix 192.168.1.0/24

# Create a virtual network


$vnet = New-AzVirtualNetwork -ResourceGroupName $resourceGroup -Location $location `
-Name MYvNET -AddressPrefix 192.168.0.0/16 -Subnet $subnetConfig

# Create a public IP address and specify a DNS name


$pip = New-AzPublicIpAddress -ResourceGroupName $resourceGroup -Location $location `
-Name "mypublicdns$(Get-Random)" -AllocationMethod Static -IdleTimeoutInMinutes 4

# Create an inbound network security group rule for port 3389


$nsgRuleRDP = New-AzNetworkSecurityRuleConfig -Name myNetworkSecurityGroupRuleRDP -Protocol Tcp `
-Direction Inbound -Priority 1000 -SourceAddressPrefix * -SourcePortRange * -DestinationAddressPrefix * `
-DestinationPortRange 3389 -Access Allow

# Create a network security group


$nsg = New-AzNetworkSecurityGroup -ResourceGroupName $resourceGroup -Location $location `
-Name myNetworkSecurityGroup -SecurityRules $nsgRuleRDP

# Create a virtual network card and associate with public IP address and NSG
$nic = New-AzNetworkInterface -Name myNic -ResourceGroupName $resourceGroup -Location $location `
-SubnetId $vnet.Subnets[0].Id -PublicIpAddressId $pip.Id -NetworkSecurityGroupId $nsg.Id

# Create a virtual machine configuration


$vmConfig = New-AzVMConfig -VMName $vmName -VMSize Standard_D1 | `
Set-AzVMOperatingSystem -Windows -ComputerName $vmName -Credential $cred | `
Set-AzVMSourceImage -PublisherName MicrosoftWindowsServer -Offer WindowsServer -Skus 2016-Datacenter -Version
latest | `
Add-AzVMNetworkInterface -Id $nic.Id

# Create a virtual machine


New-AzVM -ResourceGroupName $resourceGroup -Location $location -VM $vmConfig

Clean up deployment
Run the following command to remove the resource group, VM, and all related resources.

Remove-AzResourceGroup -Name myResourceGroup

Script explanation
This script uses the following commands to create the deployment. Each item in the table links to command
specific documentation.

COMMAND NOTES

New-AzResourceGroup Creates a resource group in which all resources are stored.


COMMAND NOTES

New-AzVirtualNetworkSubnetConfig Creates a subnet configuration. This configuration is used with


the virtual network creation process.

New-AzVirtualNetwork Creates a virtual network.

New-AzPublicIpAddress Creates a public IP address.

New-AzNetworkSecurityRuleConfig Creates a network security group rule configuration. This


configuration is used to create an NSG rule when the NSG is
created.

New-AzNetworkSecurityGroup Creates a network security group.

Get-AzVirtualNetworkSubnetConfig Gets subnet information. This information is used when


creating a network interface.

New-AzNetworkInterface Creates a network interface.

New-AzVMConfig Creates a VM configuration. This configuration includes


information such as VM name, operating system, and
administrative credentials. The configuration is used during
VM creation.

New-AzVM Create a virtual machine.

Remove-AzResourceGroup Removes a resource group and all resources contained within.

Next steps
For more information on the Azure PowerShell module, see Azure PowerShell documentation.
Additional virtual machine PowerShell script samples can be found in the Azure Windows VM documentation.
Load balance traffic between highly available virtual
machines
11/13/2019 • 5 minutes to read • Edit Online

This script sample creates everything needed to run several Windows Server 2016 virtual machines configured in
a highly available and load balanced configuration. After running the script, you will have three virtual machines,
joined to an Azure Availability Set, and accessible through an Azure Load Balancer.
This sample requires Azure PowerShell Az 1.0 or later. Run Get-Module -ListAvailable Az to see which versions
are installed. If you need to install, see Install Azure PowerShell module.
Run Connect-AzAccount to sign in to Azure.
If you don't have an Azure subscription, create a free account before you begin.

Sample script
# Variables for common values
$rgName='MyResourceGroup'
$location='eastus'

# Create user object


$cred = Get-Credential -Message 'Enter a username and password for the virtual machine.'

# Create a resource group.


New-AzResourceGroup -Name $rgName -Location $location

# Create a virtual network.


$subnet = New-AzVirtualNetworkSubnetConfig -Name 'MySubnet' -AddressPrefix 192.168.1.0/24

$vnet = New-AzVirtualNetwork -ResourceGroupName $rgName -Name 'MyVnet' `


-AddressPrefix 192.168.0.0/16 -Location $location -Subnet $subnet

# Create a public IP address.


$publicIp = New-AzPublicIpAddress -ResourceGroupName $rgName -Name 'myPublicIP' `
-Location $location -AllocationMethod Dynamic

# Create a front-end IP configuration for the website.


$feip = New-AzLoadBalancerFrontendIpConfig -Name 'myFrontEndPool' -PublicIpAddress $publicIp

# Create the back-end address pool.


$bepool = New-AzLoadBalancerBackendAddressPoolConfig -Name 'myBackEndPool'

# Creates a load balancer probe on port 80.


$probe = New-AzLoadBalancerProbeConfig -Name 'myHealthProbe' -Protocol Http -Port 80 `
-RequestPath / -IntervalInSeconds 360 -ProbeCount 5

# Creates a load balancer rule for port 80.


$rule = New-AzLoadBalancerRuleConfig -Name 'myLoadBalancerRuleWeb' -Protocol Tcp `
-Probe $probe -FrontendPort 80 -BackendPort 80 `
-FrontendIpConfiguration $feip -BackendAddressPool $bePool

# Create three NAT rules for port 3389.


$natrule1 = New-AzLoadBalancerInboundNatRuleConfig -Name 'myLoadBalancerRDP1' -FrontendIpConfiguration $feip `
-Protocol tcp -FrontendPort 4221 -BackendPort 3389

$natrule2 = New-AzLoadBalancerInboundNatRuleConfig -Name 'myLoadBalancerRDP2' -FrontendIpConfiguration $feip `


-Protocol tcp -FrontendPort 4222 -BackendPort 3389
$natrule3 = New-AzLoadBalancerInboundNatRuleConfig -Name 'myLoadBalancerRDP3' -FrontendIpConfiguration $feip `
-Protocol tcp -FrontendPort 4223 -BackendPort 3389

# Create a load balancer.


$lb = New-AzLoadBalancer -ResourceGroupName $rgName -Name 'MyLoadBalancer' -Location $location `
-FrontendIpConfiguration $feip -BackendAddressPool $bepool `
-Probe $probe -LoadBalancingRule $rule -InboundNatRule $natrule1,$natrule2,$natrule3

# Create a network security group rule for port 3389.


$rule1 = New-AzNetworkSecurityRuleConfig -Name 'myNetworkSecurityGroupRuleRDP' -Description 'Allow RDP' `
-Access Allow -Protocol Tcp -Direction Inbound -Priority 1000 `
-SourceAddressPrefix Internet -SourcePortRange * `
-DestinationAddressPrefix * -DestinationPortRange 3389

# Create a network security group rule for port 80.


$rule2 = New-AzNetworkSecurityRuleConfig -Name 'myNetworkSecurityGroupRuleHTTP' -Description 'Allow HTTP' `
-Access Allow -Protocol Tcp -Direction Inbound -Priority 2000 `
-SourceAddressPrefix Internet -SourcePortRange * `
-DestinationAddressPrefix * -DestinationPortRange 80

# Create a network security group


$nsg = New-AzNetworkSecurityGroup -ResourceGroupName $RgName -Location $location `
-Name 'myNetworkSecurityGroup' -SecurityRules $rule1,$rule2

# Create three virtual network cards and associate with public IP address and NSG.
$nicVM1 = New-AzNetworkInterface -ResourceGroupName $rgName -Location $location `
-Name 'MyNic1' -LoadBalancerBackendAddressPool $bepool -NetworkSecurityGroup $nsg `
-LoadBalancerInboundNatRule $natrule1 -Subnet $vnet.Subnets[0]

$nicVM2 = New-AzNetworkInterface -ResourceGroupName $rgName -Location $location `


-Name 'MyNic2' -LoadBalancerBackendAddressPool $bepool -NetworkSecurityGroup $nsg `
-LoadBalancerInboundNatRule $natrule2 -Subnet $vnet.Subnets[0]

$nicVM3 = New-AzNetworkInterface -ResourceGroupName $rgName -Location $location `


-Name 'MyNic3' -LoadBalancerBackendAddressPool $bepool -NetworkSecurityGroup $nsg `
-LoadBalancerInboundNatRule $natrule3 -Subnet $vnet.Subnets[0]

# Create an availability set.


$as = New-AzAvailabilitySet -ResourceGroupName $rgName -Location $location `
-Name 'MyAvailabilitySet' -Sku Aligned -PlatformFaultDomainCount 3 -PlatformUpdateDomainCount 3

# Create three virtual machines.

# ############## VM1 ###############

# Create a virtual machine configuration


$vmConfig = New-AzVMConfig -VMName 'myVM1' -VMSize Standard_DS2 -AvailabilitySetId $as.Id | `
Set-AzVMOperatingSystem -Windows -ComputerName 'myVM1' -Credential $cred | `
Set-AzVMSourceImage -PublisherName MicrosoftWindowsServer -Offer WindowsServer `
-Skus 2016-Datacenter -Version latest | Add-AzVMNetworkInterface -Id $nicVM1.Id

# Create a virtual machine


$vm1 = New-AzVM -ResourceGroupName $rgName -Location $location -VM $vmConfig

# ############## VM2 ###############

# Create a virtual machine configuration


$vmConfig = New-AzVMConfig -VMName 'myVM2' -VMSize Standard_DS2 -AvailabilitySetId $as.Id | `
Set-AzVMOperatingSystem -Windows -ComputerName 'myVM2' -Credential $cred | `
Set-AzVMSourceImage -PublisherName MicrosoftWindowsServer -Offer WindowsServer `
-Skus 2016-Datacenter -Version latest | Add-AzVMNetworkInterface -Id $nicVM2.Id

# Create a virtual machine


$vm2 = New-AzVM -ResourceGroupName $rgName -Location $location -VM $vmConfig

# ############## VM3 ###############

# Create a virtual machine configuration


$vmConfig = New-AzVMConfig -VMName 'myVM3' -VMSize Standard_DS2 -AvailabilitySetId $as.Id | `
$vmConfig = New-AzVMConfig -VMName 'myVM3' -VMSize Standard_DS2 -AvailabilitySetId $as.Id | `
Set-AzVMOperatingSystem -Windows -ComputerName 'myVM3' -Credential $cred | `
Set-AzVMSourceImage -PublisherName MicrosoftWindowsServer -Offer WindowsServer `
-Skus 2016-Datacenter -Version latest | Add-AzVMNetworkInterface -Id $nicVM3.Id

# Create a virtual machine


$vm3 = New-AzVM -ResourceGroupName $rgName -Location $location -VM $vmConfig

Clean up deployment
Run the following command to remove the resource group, VM, and all related resources.

Remove-AzResourceGroup -Name myResourceGroup

Script explanation
This script uses the following commands to create the deployment. Each item in the table links to command
specific documentation.

COMMAND NOTES

New-AzResourceGroup Creates a resource group in which all resources are stored.

New-AzVirtualNetworkSubnetConfig Creates a subnet configuration. This configuration is used with


the virtual network creation process.

New-AzVirtualNetwork Creates a virtual network.

New-AzPublicIpAddress Creates a public IP address.

New-AzLoadBalancerFrontendIpConfig Creates a front-end IP configuration for a load balancer.

New-AzLoadBalancerBackendAddressPoolConfig Creates a backend address pool configuration for a load


balancer.

New-AzLoadBalancerProbeConfig Creates a probe configuration for a load balancer.

New-AzLoadBalancerRuleConfig Creates a rule configuration for a load balancer.

New-AzLoadBalancerInboundNatRuleConfig Creates an inbound NAT rule configuration for a load balancer.

New-AzLoadBalancer Creates a load balancer.

New-AzNetworkSecurityRuleConfig Creates a network security group rule configuration. This


configuration is used to create an NSG rule when the NSG is
created.

New-AzNetworkSecurityGroup Creates a network security group.

Get-AzVirtualNetworkSubnetConfig Gets subnet information. This information is used when


creating a network interface.

New-AzNetworkInterface Creates a network interface.


COMMAND NOTES

New-AzVMConfig Creates a VM configuration. This configuration includes


information such as VM name, operating system, and
administrative credentials. The configuration is used during
VM creation.

New-AzVM Create a virtual machine.

Remove-AzResourceGroup Removes a resource group and all resources contained within.

You can also create the VMs using your own custom managed image. In the VM configuration, for
Set-AzVMSourceImage use the -Id and -VM parameters instead of -PublisherName , -Offer , -Skus , and -Version .
For example, creating the VM config would be:

$vmConfig = New-AzVMConfig -VMName 'myVM3' -VMSize Standard_DS1_v2 -AvailabilitySetId $as.Id | `


Set-AzVMOperatingSystem -Windows -ComputerName 'myVM3' -Credential $cred | `
Set-AzVMSourceImage -Id <Image.ID of the custom managed image> | Add-AzVMNetworkInterface -Id $nicVM3.Id

Next steps
For more information on the Azure PowerShell module, see Azure PowerShell documentation.
Additional virtual machine PowerShell script samples can be found in the Azure Windows VM documentation.
Create an IIS VM with PowerShell
11/13/2019 • 2 minutes to read • Edit Online

This script creates an Azure Virtual Machine running Windows Server 2016, and then uses the Azure Virtual
Machine Custom Script Extension to install IIS. After running the script, you can access the default IIS website on
the public IP address of the virtual machine.
If you don't have an Azure subscription, create a free account before you begin.

Sample script
# Variables for common values
$resourceGroup = "myResourceGroup"
$location = "westeurope"
$vmName = "myVM"

# Create user object


$cred = Get-Credential -Message "Enter a username and password for the virtual machine."

# Create a resource group


New-AzResourceGroup -Name $resourceGroup -Location $location

# Create a virtual machine


New-AzVM `
-ResourceGroupName $resourceGroup `
-Name $vmName `
-Location $location `
-ImageName "Win2016Datacenter" `
-VirtualNetworkName "myVnet" `
-SubnetName "mySubnet" `
-SecurityGroupName "myNetworkSecurityGroup" `
-PublicIpAddressName "myPublicIp" `
-Credential $cred `
-OpenPorts 80

# Install IIS
$PublicSettings = '{"commandToExecute":"powershell Add-WindowsFeature Web-Server"}'

Set-AzVMExtension -ExtensionName "IIS" -ResourceGroupName $resourceGroup -VMName $vmName `


-Publisher "Microsoft.Compute" -ExtensionType "CustomScriptExtension" -TypeHandlerVersion 1.4 `
-SettingString $PublicSettings -Location $location

Clean up deployment
Run the following command to remove the resource group, VM, and all related resources.

Remove-AzResourceGroup -Name myResourceGroup

Script explanation
This script uses the following commands to create the deployment. Each item in the table links to command
specific documentation.
COMMAND NOTES

New-AzResourceGroup Creates a resource group in which all resources are stored.

New-AzVM Creates the virtual machine and connects it to the network


card, virtual network, subnet, and network security group.
This command also opens port 80 and sets the administrative
credentials.

Set-AzVMExtension Add a VM extension to the virtual machine. In this sample, the


custom script extension is used to install IIS.

Remove-AzResourceGroup Removes a resource group and all resources contained within.

Next steps
For more information on the Azure PowerShell module, see Azure PowerShell documentation.
Additional virtual machine PowerShell script samples can be found in the Azure Windows VM documentation.
Create an IIS VM with PowerShell
11/13/2019 • 2 minutes to read • Edit Online

This script creates an Azure Virtual Machine running Windows Server 2016, and then uses the Azure Virtual
Machine DSC Extension to install IIS. After running the script, you can access the default IIS website on the public
IP address of the virtual machine.
This sample requires Azure PowerShell Az 1.0 or later. Run Get-Module -ListAvailable Az to see which versions
are installed. If you need to install, see Install Azure PowerShell module.
Run Connect-AzAccount to sign in to Azure.
If you don't have an Azure subscription, create a free account before you begin.

Sample script
# Variables for common values
$resourceGroup = "myResourceGroup"
$location = "westeurope"
$vmName = "myVM"

# Create a resource group


New-AzResourceGroup -Name $resourceGroup -Location $location

# Create user object


$cred = Get-Credential -Message "Enter a username and password for the virtual machine."

# Create a virtual machine


New-AzVM `
-ResourceGroupName $resourceGroup `
-Name $vmName `
-Location $location `
-ImageName "Win2016Datacenter" `
-VirtualNetworkName "myVnet" `
-SubnetName "mySubnet" `
-SecurityGroupName "myNetworkSecurityGroup" `
-PublicIpAddressName "myPublicIp" `
-Credential $cred `
-OpenPorts 80

# Install IIS
$PublicSettings = '{"ModulesURL":"https://github.com/Azure/azure-quickstart-templates/raw/master/dsc-
extension-iis-server-windows-vm/ContosoWebsite.ps1.zip", "configurationFunction":
"ContosoWebsite.ps1\\ContosoWebsite", "Properties": {"MachineName": "myVM"} }'

Set-AzVMExtension -ExtensionName "DSC" -ResourceGroupName $resourceGroup -VMName $vmName `


-Publisher "Microsoft.Powershell" -ExtensionType "DSC" -TypeHandlerVersion 2.19 `
-SettingString $PublicSettings -Location $location

Clean up deployment
Run the following command to remove the resource group, VM, and all related resources.

Remove-AzResourceGroup -Name myResourceGroup


Script explanation
This script uses the following commands to create the deployment. Each item in the table links to command
specific documentation.

COMMAND NOTES

New-AzResourceGroup Creates a resource group in which all resources are stored.

New-AzVM Creates the virtual machine and connects it to the network


card, virtual network, subnet, and network security group.
This command also opens port 80 and sets the administrative
credentials.

Set-AzVMExtension Add a VM extension to the virtual machine. In this sample, the


DSC extension is used to install IIS.

Remove-AzResourceGroup Removes a resource group and all resources contained within.

Next steps
For more information on the Azure PowerShell module, see Azure PowerShell documentation.
Additional virtual machine PowerShell script samples can be found in the Azure Windows VM documentation.
Sample script to upload a VHD to Azure and create a
new VM
11/13/2019 • 3 minutes to read • Edit Online

This script takes a local .vhd file from a generalized VM and uploads it to Azure, creates a Managed Disk image
and uses the to create a new VM.
This sample requires Azure PowerShell Az 1.0 or later. Run Get-Module -ListAvailable Az to see which versions
are installed. If you need to install, see Install Azure PowerShell module.
Run Connect-AzAccount to sign in to Azure.
If you don't have an Azure subscription, create a free account before you begin.

Sample script
# Provide values for the variables
$resourceGroup = 'myResourceGroup'
$location = 'EastUS'
$storageaccount = 'mystorageaccount'
$storageType = 'Standard_LRS'
$containername = 'mycontainer'
$localPath = 'C:\Users\Public\Documents\Hyper-V\VHDs\generalized.vhd'
$vmName = 'myVM'
$imageName = 'myImage'
$vhdName = 'myUploadedVhd.vhd'
$diskSizeGB = '128'
$subnetName = 'mySubnet'
$vnetName = 'myVnet'
$ipName = 'myPip'
$nicName = 'myNic'
$nsgName = 'myNsg'
$ruleName = 'myRdpRule'
$computerName = 'myComputerName'
$vmSize = 'Standard_DS1_v2'

# Get the username and password to be used for the administrators account on the VM.
# This is used when connecting to the VM using RDP.

$cred = Get-Credential

# Upload the VHD


New-AzResourceGroup -Name $resourceGroup -Location $location
New-AzStorageAccount -ResourceGroupName $resourceGroup -Name $storageAccount -Location $location `
-SkuName $storageType -Kind "Storage"
$urlOfUploadedImageVhd = ('https://' + $storageaccount + '.blob.core.windows.net/' + $containername + '/' +
$vhdName)
Add-AzVhd -ResourceGroupName $resourceGroup -Destination $urlOfUploadedImageVhd `
-LocalFilePath $localPath

# Note: Uploading the VHD may take awhile!

# Create a managed image from the uploaded VHD


$imageConfig = New-AzImageConfig -Location $location
$imageConfig = Set-AzImageOsDisk -Image $imageConfig -OsType Windows -OsState Generalized `
-BlobUri $urlOfUploadedImageVhd
$image = New-AzImage -ImageName $imageName -ResourceGroupName $resourceGroup -Image $imageConfig

# Create the networking resources


$singleSubnet = New-AzVirtualNetworkSubnetConfig -Name $subnetName -AddressPrefix 10.0.0.0/24
$vnet = New-AzVirtualNetwork -Name $vnetName -ResourceGroupName $resourceGroup -Location $location `
-AddressPrefix 10.0.0.0/16 -Subnet $singleSubnet
$pip = New-AzPublicIpAddress -Name $ipName -ResourceGroupName $resourceGroup -Location $location `
-AllocationMethod Dynamic
$rdpRule = New-AzNetworkSecurityRuleConfig -Name $ruleName -Description 'Allow RDP' -Access Allow `
-Protocol Tcp -Direction Inbound -Priority 110 -SourceAddressPrefix Internet -SourcePortRange * `
-DestinationAddressPrefix * -DestinationPortRange 3389
$nsg = New-AzNetworkSecurityGroup -ResourceGroupName $resourceGroup -Location $location `
-Name $nsgName -SecurityRules $rdpRule
$nic = New-AzNetworkInterface -Name $nicName -ResourceGroupName $resourceGroup -Location $location `
-SubnetId $vnet.Subnets[0].Id -PublicIpAddressId $pip.Id -NetworkSecurityGroupId $nsg.Id
$vnet = Get-AzVirtualNetwork -ResourceGroupName $resourceGroup -Name $vnetName

# Start building the VM configuration


$vm = New-AzVMConfig -VMName $vmName -VMSize $vmSize

# Set the VM image as source image for the new VM


$vm = Set-AzVMSourceImage -VM $vm -Id $image.Id

# Finish the VM configuration and add the NIC.


$vm = Set-AzVMOSDisk -VM $vm -DiskSizeInGB $diskSizeGB -CreateOption FromImage -Caching ReadWrite
$vm = Set-AzVMOperatingSystem -VM $vm -Windows -ComputerName $computerName -Credential $cred `
-ProvisionVMAgent -EnableAutoUpdate
$vm = Add-AzVMNetworkInterface -VM $vm -Id $nic.Id

# Create the VM
New-AzVM -VM $vm -ResourceGroupName $resourceGroup -Location $location

# Verify that the VM was created


$vmList = Get-AzVM -ResourceGroupName $resourceGroup
$vmList.Name

Clean up deployment
Run the following command to remove the resource group, VM, and all related resources.

Remove-AzResourceGroup -Name $resourceGroup

Script explanation
This script uses the following commands to create the deployment. Each item in the table links to command
specific documentation.

COMMAND NOTES

New-AzResourceGroup Creates a resource group in which all resources are stored.

New-AzStorageAccount Creates a storage account.

Add-AzVhd Uploads a virtual hard disk from an on-premises virtual


machine to a blob in a cloud storage account in Azure.

New-AzImageConfig Creates a configurable image object.

Set-AzImageOsDisk Sets the operating system disk properties on an image object.


COMMAND NOTES

New-AzImage Creates a new image.

New-AzVirtualNetworkSubnetConfig Creates a subnet configuration. This configuration is used with


the virtual network creation process.

New-AzVirtualNetwork Creates a virtual network.

New-AzPublicIpAddress Creates a public IP address.

New-AzNetworkInterface Creates a network interface.

New-AzNetworkSecurityRuleConfig Creates a network security group rule configuration. This


configuration is used to create an NSG rule when the NSG is
created.

New-AzNetworkSecurityGroup Creates a network security group.

Get-AzVirtualNetwork Gets a virtual network in a resource group.

New-AzVMConfig Creates a VM configuration. This configuration includes


information such as VM name, operating system, and
administrative credentials. The configuration is used during
VM creation.

Set-AzVMSourceImage Specifies an image for a virtual machine.

Set-AzVMOSDisk Sets the operating system disk properties on a virtual


machine.

Set-AzVMOperatingSystem Sets the operating system disk properties on a virtual


machine.

Add-AzVMNetworkInterface Adds a network interface to a virtual machine.

New-AzVM Create a virtual machine.

Remove-AzResourceGroup Removes a resource group and all resources contained within.

Next steps
For more information on the Azure PowerShell module, see Azure PowerShell documentation.
Additional virtual machine PowerShell script samples can be found in the Azure Windows VM documentation.
Create a virtual machine using an existing managed
OS disk with PowerShell
12/10/2019 • 2 minutes to read • Edit Online

This script creates a virtual machine by attaching an existing managed disk as OS disk. Use this script in preceding
scenarios:
Create a VM from an existing managed OS disk that was copied from a managed disk in different subscription
Create a VM from an existing managed disk that was created from a specialized VHD file
Create a VM from an existing managed OS disk that was created from a snapshot
If you don't have an Azure subscription, create a free account before you begin.

Sample script
#Provide the subscription Id
$subscriptionId = 'yourSubscriptionId'

#Provide the name of your resource group


$resourceGroupName ='yourResourceGroupName'

#Provide the name of the snapshot that will be used to create OS disk
$snapshotName = 'yourSnapshotName'

#Provide the name of the OS disk that will be created using the snapshot
$osDiskName = 'yourOSDiskName'

#Provide the name of an existing virtual network where virtual machine will be created
$virtualNetworkName = 'yourVNETName'

#Provide the name of the virtual machine


$virtualMachineName = 'yourVMName'

#Provide the size of the virtual machine


#e.g. Standard_DS3
#Get all the vm sizes in a region using below script:
#e.g. Get-AzVMSize -Location westus
$virtualMachineSize = 'Standard_DS3'

#Set the context to the subscription Id where Managed Disk will be created
Select-AzSubscription -SubscriptionId $SubscriptionId

$snapshot = Get-AzSnapshot -ResourceGroupName $resourceGroupName -SnapshotName $snapshotName

$diskConfig = New-AzDiskConfig -Location $snapshot.Location -SourceResourceId $snapshot.Id -CreateOption Copy

$disk = New-AzDisk -Disk $diskConfig -ResourceGroupName $resourceGroupName -DiskName $osDiskName

#Initialize virtual machine configuration


$VirtualMachine = New-AzVMConfig -VMName $virtualMachineName -VMSize $virtualMachineSize

#Use the Managed Disk Resource Id to attach it to the virtual machine. Please change the OS type to linux if
OS disk has linux OS
$VirtualMachine = Set-AzVMOSDisk -VM $VirtualMachine -ManagedDiskId $disk.Id -CreateOption Attach -Windows

#Create a public IP for the VM


$publicIp = New-AzPublicIpAddress -Name ($VirtualMachineName.ToLower()+'_ip') -ResourceGroupName
$resourceGroupName -Location $snapshot.Location -AllocationMethod Dynamic

#Get the virtual network where virtual machine will be hosted


$vnet = Get-AzVirtualNetwork -Name $virtualNetworkName -ResourceGroupName $resourceGroupName

# Create NIC in the first subnet of the virtual network


$nic = New-AzNetworkInterface -Name ($VirtualMachineName.ToLower()+'_nic') -ResourceGroupName
$resourceGroupName -Location $snapshot.Location -SubnetId $vnet.Subnets[0].Id -PublicIpAddressId $publicIp.Id

$VirtualMachine = Add-AzVMNetworkInterface -VM $VirtualMachine -Id $nic.Id

#Create the virtual machine with Managed Disk


New-AzVM -VM $VirtualMachine -ResourceGroupName $resourceGroupName -Location $snapshot.Location

Clean up deployment
Run the following command to remove the resource group, VM, and all related resources.

Remove-AzResourceGroup -Name myResourceGroup


Script explanation
This script uses the following commands to get managed disk properties, attach a managed disk to a new VM and
create a VM. Each item in the table links to command specific documentation.

COMMAND NOTES

Get-AzDisk Gets disk object based on the name and the resource group
of a disk. Id property of the returned disk object is used to
attach the disk to a new VM

New-AzVMConfig Creates a VM configuration. This configuration includes


information such as VM name, operating system, and
administrative credentials. The configuration is used during
VM creation.

Set-AzVMOSDisk Attaches a managed disk using the Id property of the disk as


OS disk to a new virtual machine

New-AzPublicIpAddress Creates a public IP address.

New-AzNetworkInterface Creates a network interface.

New-AzVM Create a virtual machine.

Remove-AzResourceGroup Removes a resource group and all resources contained within.

For marketplace images use Set-AzVMPlan to set the plan information.

Set-AzVMPlan -VM $VirtualMachine -Publisher $Publisher -Product $Product -Name $Bame

Next steps
For more information on the Azure PowerShell module, see Azure PowerShell documentation.
Additional virtual machine PowerShell script samples can be found in the Azure Windows VM documentation.
Create a virtual machine from a snapshot with
PowerShell
12/10/2019 • 2 minutes to read • Edit Online

This script creates a virtual machine from a snapshot of an OS disk.


If you don't have an Azure subscription, create a free account before you begin.

Sample script
#Provide the subscription Id
$subscriptionId = 'yourSubscriptionId'

#Provide the name of your resource group


$resourceGroupName ='yourResourceGroupName'

#Provide the name of the snapshot that will be used to create OS disk
$snapshotName = 'yourSnapshotName'

#Provide the name of the OS disk that will be created using the snapshot
$osDiskName = 'yourOSDiskName'

#Provide the name of an existing virtual network where virtual machine will be created
$virtualNetworkName = 'yourVNETName'

#Provide the name of the virtual machine


$virtualMachineName = 'yourVMName'

#Provide the size of the virtual machine


#e.g. Standard_DS3
#Get all the vm sizes in a region using below script:
#e.g. Get-AzVMSize -Location westus
$virtualMachineSize = 'Standard_DS3'

#Set the context to the subscription Id where Managed Disk will be created
Select-AzSubscription -SubscriptionId $SubscriptionId

$snapshot = Get-AzSnapshot -ResourceGroupName $resourceGroupName -SnapshotName $snapshotName

$diskConfig = New-AzDiskConfig -Location $snapshot.Location -SourceResourceId $snapshot.Id -CreateOption Copy

$disk = New-AzDisk -Disk $diskConfig -ResourceGroupName $resourceGroupName -DiskName $osDiskName

#Initialize virtual machine configuration


$VirtualMachine = New-AzVMConfig -VMName $virtualMachineName -VMSize $virtualMachineSize

#Use the Managed Disk Resource Id to attach it to the virtual machine. Please change the OS type to linux if
OS disk has linux OS
$VirtualMachine = Set-AzVMOSDisk -VM $VirtualMachine -ManagedDiskId $disk.Id -CreateOption Attach -Windows

#Create a public IP for the VM


$publicIp = New-AzPublicIpAddress -Name ($VirtualMachineName.ToLower()+'_ip') -ResourceGroupName
$resourceGroupName -Location $snapshot.Location -AllocationMethod Dynamic

#Get the virtual network where virtual machine will be hosted


$vnet = Get-AzVirtualNetwork -Name $virtualNetworkName -ResourceGroupName $resourceGroupName

# Create NIC in the first subnet of the virtual network


$nic = New-AzNetworkInterface -Name ($VirtualMachineName.ToLower()+'_nic') -ResourceGroupName
$resourceGroupName -Location $snapshot.Location -SubnetId $vnet.Subnets[0].Id -PublicIpAddressId $publicIp.Id

$VirtualMachine = Add-AzVMNetworkInterface -VM $VirtualMachine -Id $nic.Id

#Create the virtual machine with Managed Disk


New-AzVM -VM $VirtualMachine -ResourceGroupName $resourceGroupName -Location $snapshot.Location

Clean up deployment
Run the following command to remove the resource group, VM, and all related resources.

Remove-AzResourceGroup -Name myResourceGroup


Script explanation
This script uses the following commands to get snapshot properties, create a managed disk from snapshot and
create a VM. Each item in the table links to command specific documentation.

COMMAND NOTES

Get-AzSnapshot Gets a snapshot using snapshot name.

New-AzDiskConfig Creates a disk configuration. This configuration is used with


the disk creation process.

New-AzDisk Creates a managed disk.

New-AzVMConfig Creates a VM configuration. This configuration includes


information such as VM name, operating system, and
administrative credentials. The configuration is used during
VM creation.

Set-AzVMOSDisk Attaches the managed disk as OS disk to the virtual machine

New-AzPublicIpAddress Creates a public IP address.

New-AzNetworkInterface Creates a network interface.

New-AzVM Creates a virtual machine.

Remove-AzResourceGroup Removes a resource group and all resources contained within.

Next steps
For more information on the Azure PowerShell module, see Azure PowerShell documentation.
Additional virtual machine PowerShell script samples can be found in the Azure Windows VM documentation.
Create a managed disk from a VHD file in a storage
account in same or different subscription with
PowerShell
12/10/2019 • 2 minutes to read • Edit Online

This script creates a managed disk from a VHD file in a storage account in same or different subscription. Use this
script to import a specialized (not generalized/sysprepped) VHD to managed OS disk to create a virtual machine.
Also, use it to import a data VHD to managed data disk.
Don't create multiple identical managed disks from a VHD file in small amount of time. To create managed disks
from a vhd file, blob snapshot of the vhd file is created and then it is used to create managed disks. Only one blob
snapshot can be created in a minute that causes disk creation failures due to throttling. To avoid this throttling,
create a managed snapshot from the vhd file and then use the managed snapshot to create multiple managed
disks in short amount of time.
If you don't have an Azure subscription, create a free account before you begin.

Sample script
#Provide the subscription Id where Managed Disks will be created
$subscriptionId = 'yourSubscriptionId'

#Provide the name of your resource group where Managed Disks will be created.
$resourceGroupName ='yourResourceGroupName'

#Provide the name of the Managed Disk


$diskName = 'yourDiskName'

#Provide the size of the disks in GB. It should be greater than the VHD file size.
$diskSize = '128'

#Provide the storage type for Managed Disk. Premium_LRS or Standard_LRS.


$storageType = 'Premium_LRS'

#Provide the Azure region (e.g. westus) where Managed Disk will be located.
#This location should be same as the storage account where VHD file is stored
#Get all the Azure location using command below:
#Get-AzLocation
$location = 'westus'

#Provide the URI of the VHD file (page blob) in a storage account. Please not that this is NOT the SAS URI of
the storage container where VHD file is stored.
#e.g. https://contosostorageaccount1.blob.core.windows.net/vhds/contosovhd123.vhd
#Note: VHD file can be deleted as soon as Managed Disk is created.
$sourceVHDURI = 'https://contosostorageaccount1.blob.core.windows.net/vhds/contosovhd123.vhd'

#Provide the resource Id of the storage account where VHD file is stored.
#e.g. /subscriptions/6472s1g8-h217-446b-b509-
314e17e1efb0/resourceGroups/MDDemo/providers/Microsoft.Storage/storageAccounts/contosostorageaccount
#This is an optional parameter if you are creating managed disk in the same subscription
$storageAccountId =
'/subscriptions/yourSubscriptionId/resourceGroups/yourResourceGroupName/providers/Microsoft.Storage/storageAcc
ounts/yourStorageAccountName'

#Set the context to the subscription Id where Managed Disk will be created
Select-AzSubscription -SubscriptionId $SubscriptionId

$diskConfig = New-AzDiskConfig -AccountType $storageType -Location $location -CreateOption Import -


StorageAccountId $storageAccountId -SourceUri $sourceVHDURI

New-AzDisk -Disk $diskConfig -ResourceGroupName $resourceGroupName -DiskName $diskName

Script explanation
This script uses following commands to create a managed disk from a VHD in different subscription. Each
command in the table links to command specific documentation.

COMMAND NOTES

New-AzDiskConfig Creates disk configuration that is used for disk creation. It


includes storage type, location, resource Id of the storage
account where the parent VHD is stored, VHD URI of the
parent VHD.

New-AzDisk Creates a disk using disk configuration, disk name, and


resource group name passed as parameters.

Next steps
Create a virtual machine by attaching a managed disk as OS disk
For more information on the Azure PowerShell module, see Azure PowerShell documentation.
Additional virtual machine PowerShell script samples can be found in the Azure Windows VM documentation.
Create a managed disk from a snapshot with
PowerShell
12/10/2019 • 2 minutes to read • Edit Online

This script creates a managed disk from a snapshot. Use it to restore a virtual machine from snapshots of OS and
data disks. Create OS and data managed disks from respective snapshots and then create a new virtual machine
by attaching managed disks. You can also restore data disks of an existing VM by attaching data disks created from
snapshots.
If you don't have an Azure subscription, create a free account before you begin.

Sample script
#Provide the subscription Id
$subscriptionId = 'yourSubscriptionId'

#Provide the name of your resource group


$resourceGroupName ='yourResourceGroupName'

#Provide the name of the snapshot that will be used to create Managed Disks
$snapshotName = 'yourSnapshotName'

#Provide the name of the Managed Disk


$diskName = 'yourManagedDiskName'

#Provide the size of the disks in GB. It should be greater than the VHD file size.
$diskSize = '128'

#Provide the storage type for Managed Disk. PremiumLRS or StandardLRS.


$storageType = 'Premium_LRS'

#Provide the Azure region (e.g. westus) where Managed Disks will be located.
#This location should be same as the snapshot location
#Get all the Azure location using command below:
#Get-AzLocation
$location = 'westus'

#Set the context to the subscription Id where Managed Disk will be created
Select-AzSubscription -SubscriptionId $SubscriptionId

$snapshot = Get-AzSnapshot -ResourceGroupName $resourceGroupName -SnapshotName $snapshotName

$diskConfig = New-AzDiskConfig -SkuName $storageType -Location $location -CreateOption Copy -SourceResourceId


$snapshot.Id

New-AzDisk -Disk $diskConfig -ResourceGroupName $resourceGroupName -DiskName $diskName

Script explanation
This script uses following commands to create a managed disk from a snapshot. Each command in the table links
to command specific documentation.
COMMAND NOTES

Get-AzSnapshot Gets snapshot properties.

New-AzDiskConfig Creates disk configuration that is used for disk creation. It


includes the resource Id of the parent snapshot, location that
is same as the location of parent snapshot and the storage
type.

New-AzDisk Creates a disk using disk configuration, disk name, and


resource group name passed as parameters.

Next steps
Create a virtual machine from a managed disk
For more information on the Azure PowerShell module, see Azure PowerShell documentation.
Additional virtual machine PowerShell script samples can be found in the Azure Windows VM documentation.
Copy managed disks in the same subscription or
different subscription with PowerShell
12/10/2019 • 2 minutes to read • Edit Online

This script creates a copy of an existing managed disk in the same subscription or different subscription. The new
disk is created in the same region as the parent managed disk.
If needed, install the Azure PowerShell module using the instructions found in the Azure PowerShell guide, and
then run Connect-AzAccount to create a connection with Azure. Also, you need to have an SSH public key named
id_rsa.pub in the .ssh directory of your user profile.

If you don't have an Azure subscription, create a free account before you begin.

Sample script
#Provide the subscription Id of the subscription where managed disk exists
$sourceSubscriptionId='yourSourceSubscriptionId'

#Provide the name of your resource group where managed disk exists
$sourceResourceGroupName='mySourceResourceGroupName'

#Provide the name of the managed disk


$managedDiskName='myDiskName'

#Set the context to the subscription Id where Managed Disk exists


Select-AzSubscription -SubscriptionId $sourceSubscriptionId

#Get the source managed disk


$managedDisk= Get-AzDisk -ResourceGroupName $sourceResourceGroupName -DiskName $managedDiskName

#Provide the subscription Id of the subscription where managed disk will be copied to
#If managed disk is copied to the same subscription then you can skip this step
$targetSubscriptionId='yourTargetSubscriptionId'

#Name of the resource group where snapshot will be copied to


$targetResourceGroupName='myTargetResourceGroupName'

#Set the context to the subscription Id where managed disk will be copied to
#If snapshot is copied to the same subscription then you can skip this step
Select-AzSubscription -SubscriptionId $targetSubscriptionId

$diskConfig = New-AzDiskConfig -SourceResourceId $managedDisk.Id -Location $managedDisk.Location -CreateOption


Copy

#Create a new managed disk in the target subscription and resource group
New-AzDisk -Disk $diskConfig -DiskName $managedDiskName -ResourceGroupName $targetResourceGroupName

Script explanation
This script uses following commands to create a new managed disk in the target subscription using the Id of the
source managed disk. Each command in the table links to command specific documentation.
COMMAND NOTES

New-AzDiskConfig Creates disk configuration that is used for disk creation. It


includes the resource Id of the parent disk and location that is
same as the location of parent disk.

New-AzDisk Creates a disk using disk configuration, disk name, and


resource group name passed as parameters.

Next steps
Create a virtual machine from a managed disk
For more information on the Azure PowerShell module, see Azure PowerShell documentation.
Additional virtual machine PowerShell script samples can be found in the Azure Windows VM documentation.
Export/Copy managed snapshots as VHD to a
storage account in different region with PowerShell
12/10/2019 • 2 minutes to read • Edit Online

This script exports a managed snapshot to a storage account in different region. It first generates the SAS URI of
the snapshot and then uses it to copy it to a storage account in different region. Use this script to maintain backup
of your managed disks in different region for disaster recovery.
If needed, install the Azure PowerShell module using the instructions found in the Azure PowerShell guide, and
then run Connect-AzAccount to create a connection with Azure. Also, you need to have an SSH public key named
id_rsa.pub in the .ssh directory of your user profile.

If you don't have an Azure subscription, create a free account before you begin.

Sample script
#Provide the subscription Id of the subscription where snapshot is created
$subscriptionId = "yourSubscriptionId"

#Provide the name of your resource group where snapshot is created


$resourceGroupName ="yourResourceGroupName"

#Provide the snapshot name


$snapshotName = "yourSnapshotName"

#Provide Shared Access Signature (SAS) expiry duration in seconds e.g. 3600.
#Know more about SAS here: https://docs.microsoft.com/en-us/Az.Storage/storage-dotnet-shared-access-signature-
part-1
$sasExpiryDuration = "3600"

#Provide storage account name where you want to copy the snapshot.
$storageAccountName = "yourstorageaccountName"

#Name of the storage container where the downloaded snapshot will be stored
$storageContainerName = "yourstoragecontainername"

#Provide the key of the storage account where you want to copy snapshot.
$storageAccountKey = 'yourStorageAccountKey'

#Provide the name of the VHD file to which snapshot will be copied.
$destinationVHDFileName = "yourvhdfilename"

# Set the context to the subscription Id where Snapshot is created


Select-AzSubscription -SubscriptionId $SubscriptionId

#Generate the SAS for the snapshot


$sas = Grant-AzSnapshotAccess -ResourceGroupName $ResourceGroupName -SnapshotName $SnapshotName -
DurationInSecond $sasExpiryDuration -Access Read
#Create the context for the storage account which will be used to copy snapshot to the storage account
$destinationContext = New-AzStorageContext -StorageAccountName $storageAccountName -StorageAccountKey
$storageAccountKey

#Copy the snapshot to the storage account


Start-AzStorageBlobCopy -AbsoluteUri $sas.AccessSAS -DestContainer $storageContainerName -DestContext
$destinationContext -DestBlob $destinationVHDFileName
Script explanation
This script uses following commands to generate SAS URI for a managed snapshot and copies the snapshot to a
storage account using SAS URI. Each command in the table links to command specific documentation.

COMMAND NOTES

Grant-AzSnapshotAccess Generates SAS URI for a snapshot that is used to copy it to a


storage account.

New-AzureStorageContext Creates a storage account context using the account name


and key. This context can be used to perform read/write
operations on the storage account.

Start-AzureStorageBlobCopy Copies the underlying VHD of a snapshot to a storage


account

Next steps
Create a managed disk from a VHD
Create a virtual machine from a managed disk
For more information on the Azure PowerShell module, see Azure PowerShell documentation.
Additional virtual machine PowerShell script samples can be found in the Azure Windows VM documentation.
Export/Copy the VHD of a managed disk to a
storage account in different region with PowerShell
12/10/2019 • 2 minutes to read • Edit Online

This script exports the VHD of a managed disk to a storage account in different region. It first generates the SAS
URI of the managed disk and then uses it to copy the underlying VHD to a storage account in different region. Use
this script to copy managed disks to another region for regional expansion.
If needed, install the Azure PowerShell module using the instructions found in the Azure PowerShell guide, and
then run Connect-AzAccount to create a connection with Azure. Also, you need to have an SSH public key named
id_rsa.pub in the .ssh directory of your user profile.

If you don't have an Azure subscription, create a free account before you begin.

Sample script
#Provide the subscription Id of the subscription where managed disk is created
$subscriptionId = "yourSubscriptionId"

#Provide the name of your resource group where managed is created


$resourceGroupName ="yourResourceGroupName"

#Provide the managed disk name


$diskName = "yourDiskName"

#Provide Shared Access Signature (SAS) expiry duration in seconds e.g. 3600.
#Know more about SAS here: https://docs.microsoft.com/en-us/Az.Storage/storage-dotnet-shared-access-signature-
part-1
$sasExpiryDuration = "3600"

#Provide storage account name where you want to copy the underlying VHD of the managed disk.
$storageAccountName = "yourstorageaccountName"

#Name of the storage container where the downloaded VHD will be stored
$storageContainerName = "yourstoragecontainername"

#Provide the key of the storage account where you want to copy the VHD of the managed disk.
$storageAccountKey = 'yourStorageAccountKey'

#Provide the name of the destination VHD file to which the VHD of the managed disk will be copied.
$destinationVHDFileName = "yourvhdfilename"

#Set the value to 1 to use AzCopy tool to download the data. This is the recommended option for faster copy.
#Download AzCopy v10 from the link here: https://docs.microsoft.com/en-us/azure/storage/common/storage-use-
azcopy-v10
#Ensure that AzCopy is downloaded in the same folder as this file
#If you set the value to 0 then Start-AzStorageBlobCopy will be used. Azure storage will asynchronously copy
the data.
$useAzCopy = 1

# Set the context to the subscription Id where managed disk is created


Select-AzSubscription -SubscriptionId $SubscriptionId

#Generate the SAS for the managed disk


$sas = Grant-AzDiskAccess -ResourceGroupName $ResourceGroupName -DiskName $diskName -DurationInSecond
$sasExpiryDuration -Access Read

#Create the context of the storage account where the underlying VHD of the managed disk will be copied
$destinationContext = New-AzStorageContext -StorageAccountName $storageAccountName -StorageAccountKey
$storageAccountKey

#Copy the VHD of the managed disk to the storage account


if($useAzCopy -eq 1)
{
$containerSASURI = New-AzStorageContainerSASToken -Context $destinationContext -ExpiryTime(get-
date).AddSeconds($sasExpiryDuration) -FullUri -Name $storageContainerName -Permission rw
$containername,$sastokenkey = $containerSASURI -split "\?"
$containerSASURI = "$containername/$destinationVHDFileName`?$sastokenkey"
azcopy copy $sas.AccessSAS $containerSASURI

}else{

Start-AzStorageBlobCopy -AbsoluteUri $sas.AccessSAS -DestContainer $storageContainerName -DestContext


$destinationContext -DestBlob $destinationVHDFileName
}

Script explanation
This script uses the following commands to generate SAS URI of a managed disk and copies the underlying VHD
to a storage account using the SAS URI. Each command in the table links to the command specific documentation.
COMMAND NOTES

Grant-AzDiskAccess Generates SAS URI for a managed disk that is used to copy
the underlying VHD to a storage account.

New-AzureStorageContext Creates a storage account context using the account name


and key. This context can be used to perform read/write
operations on the storage account.

Start-AzureStorageBlobCopy Copies the underlying VHD of a snapshot to a storage


account

Next steps
Create a managed disk from a VHD
Create a virtual machine from a managed disk
For more information on the Azure PowerShell module, see Azure PowerShell documentation.
Additional virtual machine PowerShell script samples can be found in the Azure Windows VM documentation.
Create a snapshot from a VHD to create multiple
identical managed disks in small amount of time with
PowerShell
1/2/2020 • 2 minutes to read • Edit Online

This script creates a snapshot from a VHD file in a storage account in same or different subscription. Use this
script to import a specialized (not generalized/sysprepped) VHD to a snapshot and then use the snapshot to create
multiple identical managed disks in small amount of time. Also, use it to import a data VHD to a snapshot and
then use the snapshot to create multiple managed disks in small amount of time.
If you don't have an Azure subscription, create a free account before you begin.

Sample script
#Provide the subscription Id where snapshot will be created
$subscriptionId = 'yourSubscriptionId'

#Provide the name of your resource group where snapshot will be created.
$resourceGroupName ='yourResourceGroupName'

#Provide the name of the snapshot


$snapshotName = 'yourSnapshotName'

#Provide the storage type for snapshot. PremiumLRS or StandardLRS.


$storageType = 'StandardLRS'

#Provide the Azure region (e.g. westus) where snapshot will be located.
#This location should be same as the storage account location where VHD file is stored
#Get all the Azure location using command below:
#Get-AzLocation
$location = 'westus'

#Provide the URI of the VHD file (page blob) in a storage account. Please not that this is NOT the SAS URI of
the storage container where VHD file is stored.
#e.g. https://contosostorageaccount1.blob.core.windows.net/vhds/contosovhd123.vhd
#Note: VHD file can be deleted as soon as Managed Disk is created.
$sourceVHDURI = 'https://yourStorageAccountName.blob.core.windows.net/vhds/yourVHDName.vhd'

#Provide the resource Id of the storage account where VHD file is stored.
#e.g. /subscriptions/6582b1g7-e212-446b-b509-
314e17e1efb0/resourceGroups/MDDemo/providers/Microsoft.Storage/storageAccounts/contosostorageaccount1
#This is an optional parameter if you are creating snapshot in the same subscription
$storageAccountId =
'/subscriptions/yourSubscriptionId/resourceGroups/yourResourceGroupName/providers/Microsoft.Storage/storageAcc
ounts/yourStorageAccountName'

#Set the context to the subscription Id where Managed Disk will be created
Select-AzSubscription -SubscriptionId $SubscriptionId

$snapshotConfig = New-AzSnapshotConfig -AccountType $storageType -Location $location -CreateOption Import -


StorageAccountId $storageAccountId -SourceUri $sourceVHDURI

New-AzSnapshot -Snapshot $snapshotConfig -ResourceGroupName $resourceGroupName -SnapshotName $snapshotName


Next steps
Create a managed disk from snapshot
Create a virtual machine by attaching a managed disk as OS disk
For more information on the Azure PowerShell module, see Azure PowerShell documentation.
Additional virtual machine PowerShell script samples can be found in the Azure Windows VM documentation.
Copy snapshot of a managed disk in same
subscription or different subscription with PowerShell
12/10/2019 • 2 minutes to read • Edit Online

This script copies a snapshot of a managed disk to same or different subscription. Use this script for the following
scenarios:
1. Migrate a snapshot in Premium storage (Premium_LRS ) to Standard storage (Standard_LRS or Standard_ZRS )
to reduce your cost.
2. Migrate a snapshot from locally redundant storage (Premium_LRS, Standard_LRS ) to zone redundant storage
(Standard_ZRS ) to benefit from the higher reliability of ZRS storage.
3. Move a snapshot to different subscription in the same region for longer retention.
If needed, install the Azure PowerShell module using the instructions found in the Azure PowerShell guide, and
then run Connect-AzAccount to create a connection with Azure. Also, you need to have an SSH public key named
id_rsa.pub in the .ssh directory of your user profile.

If you don't have an Azure subscription, create a free account before you begin.

Sample script
#Provide the subscription Id of the subscription where snapshot exists
$sourceSubscriptionId='yourSourceSubscriptionId'

#Provide the name of your resource group where snapshot exists


$sourceResourceGroupName='yourResourceGroupName'

#Provide the name of the snapshot


$snapshotName='yourSnapshotName'

#Set the context to the subscription Id where snapshot exists


Select-AzSubscription -SubscriptionId $sourceSubscriptionId

#Get the source snapshot


$snapshot= Get-AzSnapshot -ResourceGroupName $sourceResourceGroupName -Name $snapshotName

#Provide the subscription Id of the subscription where snapshot will be copied to


#If snapshot is copied to the same subscription then you can skip this step
$targetSubscriptionId='yourTargetSubscriptionId'

#Name of the resource group where snapshot will be copied to


$targetResourceGroupName='yourTargetResourceGroupName'

#Set the context to the subscription Id where snapshot will be copied to


#If snapshot is copied to the same subscription then you can skip this step
Select-AzSubscription -SubscriptionId $targetSubscriptionId

#We recommend you to store your snapshots in Standard storage to reduce cost. Please use Standard_ZRS in
regions where zone redundant storage (ZRS) is available, otherwise use Standard_LRS
#Please check out the availability of ZRS here: https://docs.microsoft.com/en-us/Az.Storage/common/storage-
redundancy-zrs#support-coverage-and-regional-availability
$snapshotConfig = New-AzSnapshotConfig -SourceResourceId $snapshot.Id -Location $snapshot.Location -
CreateOption Copy -SkuName Standard_LRS

#Create a new snapshot in the target subscription and resource group


New-AzSnapshot -Snapshot $snapshotConfig -SnapshotName $snapshotName -ResourceGroupName
$targetResourceGroupName

Script explanation
This script uses following commands to create a snapshot in the target subscription using the Id of the source
snapshot. Each command in the table links to command specific documentation.

COMMAND NOTES

New-AzSnapshotConfig Creates snapshot configuration that is used for snapshot


creation. It includes the resource Id of the parent snapshot
and location that is same as the parent snapshot.

New-AzSnapshot Creates a snapshot using snapshot configuration, snapshot


name, and resource group name passed as parameters.

Next steps
Create a virtual machine from a snapshot
For more information on the Azure PowerShell module, see Azure PowerShell documentation.
Additional virtual machine PowerShell script samples can be found in the Azure Windows VM documentation.
Encrypt a Windows virtual machine with Azure
PowerShell
11/13/2019 • 3 minutes to read • Edit Online

This script creates a secure Azure Key Vault, encryption keys, Azure Active Directory service principal, and a
Windows virtual machine (VM ). The VM is then encrypted using the encryption key from Key Vault and service
principal credentials.
If you don't have an Azure subscription, create a free account before you begin.

Sample script
# Edit these global variables with you unique Key Vault name, resource group name and location
#Name of the Key Vault
$keyVaultName = "myKeyVault00"
#Resource Group Name
$rgName = "myResourceGroup"
#Region
$location = "East US"
#Password to place w/in the KeyVault
$password = $([guid]::NewGuid()).Guid
$securePassword = ConvertTo-SecureString -String $password -AsPlainText -Force
#Name for the Azure AD Application
$appName = "My App"
#Name for the VM to be encrypt
$vmName = "myEncryptedVM"
#user name for the admin account in the vm being created and then encrypted
$vmAdminName = "encryptedUser"

# Register the Key Vault provider and create a resource group


New-AzResourceGroup -Location $location -Name $rgName

# Create a Key Vault and enable it for disk encryption


New-AzKeyVault `
-Location $location `
-ResourceGroupName $rgName `
-VaultName $keyVaultName `
-EnabledForDiskEncryption

# Create a key in your Key Vault


Add-AzKeyVaultKey `
-VaultName $keyVaultName `
-Name "myKey" `
-Destination "Software"

# Put the password in the Key Vault as a Key Vault Secret so we can use it later
# We should never put passwords in scripts.
Set-AzKeyVaultSecret -VaultName $keyVaultName -Name adminCreds -SecretValue $securePassword
Set-AzKeyVaultSecret -VaultName $keyVaultName -Name protectValue -SecretValue $securePassword

# Create Azure Active Directory app and service principal


$app = New-AzADApplication -DisplayName $appName `
-HomePage "https://myapp0.contoso.com" `
-IdentifierUris "https://contoso.com/myapp0" `
-Password (Get-AzKeyVaultSecret -VaultName $keyVaultName -Name adminCreds).SecretValue

New-AzADServicePrincipal -ApplicationId $app.ApplicationId

# Set permissions to allow your AAD service principal to read keys from Key Vault
# Set permissions to allow your AAD service principal to read keys from Key Vault
Set-AzKeyVaultAccessPolicy -VaultName $keyvaultName `
-ServicePrincipalName $app.ApplicationId `
-PermissionsToKeys decrypt,encrypt,unwrapKey,wrapKey,verify,sign,get,list,update `
-PermissionsToSecrets get,list,set,delete,backup,restore,recover,purge

# Create PSCredential object for VM


$cred = New-Object System.Management.Automation.PSCredential($vmAdminName, (Get-AzKeyVaultSecret -VaultName
$keyVaultName -Name adminCreds).SecretValue)

# Create a virtual machine


New-AzVM `
-ResourceGroupName $rgName `
-Name $vmName `
-Location $location `
-ImageName "Win2016Datacenter" `
-VirtualNetworkName "myVnet" `
-SubnetName "mySubnet" `
-SecurityGroupName "myNetworkSecurityGroup" `
-PublicIpAddressName "myPublicIp" `
-Credential $cred `
-OpenPorts 3389

# Define required information for our Key Vault and keys


$keyVault = Get-AzKeyVault -VaultName $keyVaultName -ResourceGroupName $rgName;
$diskEncryptionKeyVaultUrl = $keyVault.VaultUri;
$keyVaultResourceId = $keyVault.ResourceId;
$keyEncryptionKeyUrl = (Get-AzKeyVaultKey -VaultName $keyVaultName -Name "myKey").Key.kid;

# Encrypt our virtual machine


Set-AzVMDiskEncryptionExtension `
-ResourceGroupName $rgName `
-VMName $vmName `
-AadClientID $app.ApplicationId `
-AadClientSecret (Get-AzKeyVaultSecret -VaultName $keyVaultName -Name adminCreds).SecretValueText `
-DiskEncryptionKeyVaultUrl $diskEncryptionKeyVaultUrl `
-DiskEncryptionKeyVaultId $keyVaultResourceId `
-KeyEncryptionKeyUrl $keyEncryptionKeyUrl `
-KeyEncryptionKeyVaultId $keyVaultResourceId

# View encryption status


Get-AzVmDiskEncryptionStatus -ResourceGroupName $rgName -VMName $vmName

<#
#clean up
Remove-AzResourceGroup -Name $rgName
#removes all of the Azure AD Applications you created w/ the same name
Remove-AzADApplication -ObjectId $app.ObjectId -Force
#>

Clean up deployment
Run the following command to remove the resource group, VM, and all related resources.

Remove-AzResourceGroup -Name myResourceGroup

Script explanation
This script uses the following commands to create the deployment. Each item in the table links to command
specific documentation.
COMMAND NOTES

New-AzResourceGroup Creates a resource group in which all resources are stored.

New-AzKeyVault Creates an Azure Key Vault to store secure data such as


encryption keys.

Add-AzKeyVaultKey Creates an encryption key in Key Vault.

New-AzADServicePrincipal Creates an Azure Active Directory service principal to securely


authenticate and control access to encryption keys.

Set-AzKeyVaultAccessPolicy Sets permissions on the Key Vault to grant the service


principal access to encryption keys.

New-AzVM Creates the virtual machine and connects it to the network


card, virtual network, subnet, and network security group.
This command also opens port 80 and sets the administrative
credentials.

Get-AzKeyVault Gets required information on the Key Vault

Set-AzVMDiskEncryptionExtension Enables encryption on a VM using the service principal


credentials and encryption key.

Get-AzVmDiskEncryptionStatus Shows the status of the VM encryption process.

Remove-AzResourceGroup Removes a resource group and all resources contained within.

Next steps
For more information on the Azure PowerShell module, see Azure PowerShell documentation.
Additional virtual machine PowerShell script samples can be found in the Azure Windows VM documentation.
Create an Azure Monitor VM with PowerShell
11/13/2019 • 2 minutes to read • Edit Online

This script creates an Azure Virtual Machine, installs the Log Analytics agent, and enrolls the system with a Log
Analytics workspace. Once the script has run, the virtual machine will be visible in Azure Monitor. Also, you need
to update the Log Analytics workspace ID and workspace key.
If you don't have an Azure subscription, create a free account before you begin.

Sample script
# OMS ID and OMS key
$omsId = "<Replace with your OMS ID>"
$omsKey = "<Replace with your OMS key>"

# Variables for common values


$resourceGroup = "myResourceGroup"
$location = "westeurope"
$vmName = "myVM"

# Create a user object


$cred = Get-Credential -Message "Enter a username and password for the virtual machine."

# Create a resource group


New-AzResourceGroup -Name $resourceGroup -Location $location

# Create a virtual machine


New-AzVM `
-ResourceGroupName $resourceGroup `
-Name $vmName `
-Location $location `
-ImageName "Win2016Datacenter" `
-VirtualNetworkName "myVnet" `
-SubnetName "mySubnet" `
-SecurityGroupName "myNetworkSecurityGroup" `
-PublicIpAddressName "myPublicIp" `
-Credential $cred `
-OpenPorts 3389

# Install and configure the OMS agent


$PublicSettings = New-Object psobject | Add-Member -PassThru NoteProperty workspaceId $omsId | ConvertTo-Json
$protectedSettings = New-Object psobject | Add-Member -PassThru NoteProperty workspaceKey $omsKey | ConvertTo-
Json

Set-AzVMExtension -ExtensionName "OMS" -ResourceGroupName $resourceGroup -VMName $vmName `


-Publisher "Microsoft.EnterpriseCloud.Monitoring" -ExtensionType "MicrosoftMonitoringAgent" `
-TypeHandlerVersion 1.0 -SettingString $PublicSettings -ProtectedSettingString $protectedSettings `
-Location $location

Clean up deployment
Run the following command to remove the resource group, VM, and all related resources.

Remove-AzResourceGroup -Name myResourceGroup


Script explanation
This script uses the following commands to create the deployment. Each item in the table links to command
specific documentation.

COMMAND NOTES

New-AzResourceGroup Creates a resource group in which all resources are stored.

New-AzVM Creates the virtual machine and connects it to the network


card, virtual network, subnet, and network security group.
This command also opens port 80 and sets the administrative
credentials.

Set-AzVMExtension Add a VM extension to the virtual machine.

Remove-AzResourceGroup Removes a resource group and all resources contained within.

Next steps
For more information on the Azure PowerShell module, see Azure PowerShell documentation.
Additional virtual machine PowerShell script samples can be found in the Azure Windows VM documentation.
Collect details about all VMs in a subscription with
PowerShell
12/6/2019 • 2 minutes to read • Edit Online

This script creates a csv that contains the VM Name, Resource Group Name, Region, Virtual Network, Subnet,
Private IP Address, OS Type, and Public IP Address of the VMs in the provided subscription.
If you don't have an Azure subscription, create a free account before you begin.

Launch Azure Cloud Shell


The Azure Cloud Shell is a free interactive shell that you can use to run the steps in this article. It has common
Azure tools preinstalled and configured to use with your account.
To open the Cloud Shell, just select Try it from the upper right corner of a code block. You can also launch Cloud
Shell in a separate browser tab by going to https://shell.azure.com/powershell. Select Copy to copy the blocks of
code, paste it into the Cloud Shell, and press enter to run it.

Sample script
#Provide the subscription Id where the VMs reside
$subscriptionId = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"

#Provide the name of the csv file to be exported


$reportName = "myReport.csv"

Select-AzSubscription $subscriptionId
$report = @()
$vms = Get-AzVM
$publicIps = Get-AzPublicIpAddress
$nics = Get-AzNetworkInterface | ?{ $_.VirtualMachine -NE $null}
foreach ($nic in $nics) {
$info = "" | Select VmName, ResourceGroupName, Region, VirturalNetwork, Subnet, PrivateIpAddress, OsType,
PublicIPAddress
$vm = $vms | ? -Property Id -eq $nic.VirtualMachine.id
foreach($publicIp in $publicIps) {
if($nic.IpConfigurations.id -eq $publicIp.ipconfiguration.Id) {
$info.PublicIPAddress = $publicIp.ipaddress
}
}
$info.OsType = $vm.StorageProfile.OsDisk.OsType
$info.VMName = $vm.Name
$info.ResourceGroupName = $vm.ResourceGroupName
$info.Region = $vm.Location
$info.VirturalNetwork = $nic.IpConfigurations.subnet.Id.Split("/")[-3]
$info.Subnet = $nic.IpConfigurations.subnet.Id.Split("/")[-1]
$info.PrivateIpAddress = $nic.IpConfigurations.PrivateIpAddress
$report+=$info
}
$report | ft VmName, ResourceGroupName, Region, VirturalNetwork, Subnet, PrivateIpAddress, OsType,
PublicIPAddress
$report | Export-CSV "$home/$reportName"

Script explanation
This script uses following commands to create a csv export of the details of VMs in a subscription. Each command
in the table links to command specific documentation.

COMMAND NOTES

Select-AzSubscription Sets the tenant, subscription, and environment for cmdlets to


use in the current session.

Get-AzVM Gets the properties of a virtual machine.

Get-AzPublicIpAddress Gets a public IP address.

Get-AzNetworkInterface Gets a network interface.

Next steps
For more information on the Azure PowerShell module, see Azure PowerShell documentation.
Additional virtual machine PowerShell script samples can be found in the Azure Windows VM documentation.
Azure CLI Samples for Windows virtual machines
11/13/2019 • 2 minutes to read • Edit Online

The following table includes links to bash scripts built using the Azure CLI that deploy Windows virtual
machines.

Create virtual machines

Create a virtual machine Creates a Windows virtual machine with minimal


configuration.

Create a fully configured virtual machine Creates a resource group, virtual machine, and all related
resources.

Create highly available virtual machines Creates several virtual machines in a highly available and load
balanced configuration.

Create a VM and run configuration script Creates a virtual machine and uses the Azure Custom Script
extension to install IIS.

Create a VM and run DSC configuration Creates a virtual machine and uses the Azure Desired State
Configuration (DSC) extension to install IIS.

Manage storage

Create managed disk from a VHD Creates a managed disk from a specialized VHD as an OS disk
or from a data VHD as data disk.

Create a managed disk from a snapshot Creates a managed disk from a snapshot.

Copy managed disk to same or different subscription Copies managed disk to same or different subscription but in
the same region as the parent managed disk.

Export a snapshot as VHD to a storage account Exports a managed snapshot as VHD to a storage account in
different region.

Export the VHD of a managed disk to a storage account Exports the underlying VHD of a managed disk to a storage
account in different region.

Copy snapshot to same or different subscription Copies snapshot to same or different subscription but in the
same region as the parent snapshot.

Network virtual machines

Secure network traffic between virtual machines Creates two virtual machines, all related resources, and an
internal and external network security groups (NSG).

Secure virtual machines


Encrypt a VM and data disks Creates an Azure Key Vault, encryption key, and service
principal, then encrypts a VM.

Monitor virtual machines

Monitor a VM with Azure Monitor Creates a virtual machine, installs the Log Analytics agent,
and enrolls the VM in a Log Analytics workspace.
Quick Create a virtual machine with the Azure CLI
11/13/2019 • 2 minutes to read • Edit Online

This script creates an Azure Virtual Machine running Windows Server 2016. After running the script, you can
access the virtual machine through a Remote Desktop connection.
To run this sample, install the latest version of the Azure CLI. To start, run az login to create a connection with
Azure.
Samples for the Azure CLI are written for the bash shell. To run this sample in Windows PowerShell or Command
Prompt, you may need to change elements of the script.
If you don't have an Azure subscription, create a free account before you begin.

Sample script
#!/bin/bash

# Update for your admin password


AdminPassword=ChangeYourAdminPassword1

# Create a resource group.


az group create --name myResourceGroup --location westus

# Create a virtual machine.


az vm create \
--resource-group myResourceGroup \
--name myVM \
--image win2016datacenter \
--admin-username azureuser \
--admin-password $AdminPassword \
--no-wait

Clean up deployment
Run the following command to remove the resource group, VM, and all related resources.

az group delete --name myResourceGroup --yes

Script explanation
This script uses the following commands to create a resource group, virtual machine, and all related resources.
Each command in the table links to command specific documentation.

COMMAND NOTES

az group create Creates a resource group in which all resources are stored.

az vm create Creates the virtual machine and connects it to the network


card, virtual network, subnet, and network security group.
This command also specifies the virtual machine image to be
used and administrative credentials.
COMMAND NOTES

az group delete Deletes a resource group including all nested resources.

Next steps
For more information on the Azure CLI, see Azure CLI documentation.
Additional virtual machine CLI script samples can be found in the Azure Windows VM documentation.
Create a virtual machine with the Azure CLI
11/13/2019 • 2 minutes to read • Edit Online

This script creates an Azure Virtual Machine running Windows Server 2016. After running the script, you can
access the virtual machine through a Remote Desktop connection.
To run this sample, install the latest version of the Azure CLI. To start, run az login to create a connection with
Azure.
Samples for the Azure CLI are written for the bash shell. To run this sample in Windows PowerShell or Command
Prompt, you may need to change elements of the script.
If you don't have an Azure subscription, create a free account before you begin.

Sample script
#!/bin/bash

# Update for your admin password


AdminPassword=ChangeYourAdminPassword1

# Create a resource group.


az group create --name myResourceGroup --location westeurope

# Create a virtual network.


az network vnet create --resource-group myResourceGroup --name myVnet --subnet-name mySubnet

# Create a public IP address.


az network public-ip create --resource-group myResourceGroup --name myPublicIP

# Create a network security group.


az network nsg create --resource-group myResourceGroup --name myNetworkSecurityGroup

# Create a virtual network card and associate with public IP address and NSG.
az network nic create \
--resource-group myResourceGroup \
--name myNic \
--vnet-name myVnet \
--subnet mySubnet \
--network-security-group myNetworkSecurityGroup \
--public-ip-address myPublicIP

# Create a virtual machine.


az vm create \
--resource-group myResourceGroup \
--name myVM \
--location westeurope \
--nics myNic \
--image win2016datacenter \
--admin-username azureuser \
--admin-password $AdminPassword

# Open port 3389 to allow RDP traffic to host.


az vm open-port --port 3389 --resource-group myResourceGroup --name myVM

Clean up deployment
Run the following command to remove the resource group, VM, and all related resources.
az group delete --name myResourceGroup --yes

Script explanation
This script uses the following commands to create a resource group, virtual machine, and all related resources.
Each command in the table links to command specific documentation.

COMMAND NOTES

az group create Creates a resource group in which all resources are stored.

az network vnet create Creates an Azure virtual network and subnet.

az network public-ip create Creates a public IP address with a static IP address and an
associated DNS name.

az network nsg create Creates a network security group (NSG), which is a security
boundary between the internet and the virtual machine.

az network nic create Creates a virtual network card and attaches it to the virtual
network, subnet, and NSG.

az vm create Creates the virtual machine and connects it to the network


card, virtual network, subnet, and NSG. This command also
specifies the virtual machine image to be used, and
administrative credentials.

az group delete Deletes a resource group including all nested resources.

Next steps
For more information on the Azure CLI, see Azure CLI documentation.
Additional virtual machine CLI script samples can be found in the Azure Windows VM documentation.
Load balance traffic between highly available virtual
machines
11/13/2019 • 4 minutes to read • Edit Online

This script sample creates everything needed to run several Ubuntu virtual machines configured in a highly
available and load balanced configuration. After running the script, you will have three virtual machines, joined to
an Azure Availability Set, and accessible through an Azure Load Balancer.
To run this sample, install the latest version of the Azure CLI. To start, run az login to create a connection with
Azure.
Samples for the Azure CLI are written for the bash shell. To run this sample in Windows PowerShell or Command
Prompt, you may need to change elements of the script.
If you don't have an Azure subscription, create a free account before you begin.

Sample script
#!/bin/bash

# Update for your admin password


AdminPassword=ChangeYourAdminPassword1

# Create a resource group.


az group create --name myResourceGroup --location westus

# Create a virtual network.


az network vnet create --resource-group myResourceGroup --name myVnet \
--address-prefix 192.168.0.0/16 --subnet-name mySubnet --subnet-prefix 192.168.1.0/24

# Create a public IP address.


az network public-ip create --resource-group myResourceGroup --name myPublicIP

# Create an Azure Load Balancer.


az network lb create --resource-group myResourceGroup --name myLoadBalancer --public-ip-address myPublicIP \
--frontend-ip-name myFrontEndPool --backend-pool-name myBackEndPool

# Creates an LB probe on port 80.


az network lb probe create --resource-group myResourceGroup --lb-name myLoadBalancer \
--name myHealthProbe --protocol tcp --port 80

# Creates an LB rule for port 80.


az network lb rule create --resource-group myResourceGroup --lb-name myLoadBalancer --name
myLoadBalancerRuleWeb \
--protocol tcp --frontend-port 80 --backend-port 80 --frontend-ip-name myFrontEndPool \
--backend-pool-name myBackEndPool --probe-name myHealthProbe

# Create three NAT rules for port 3389.


for i in `seq 1 3`; do
az network lb inbound-nat-rule create \
--resource-group myResourceGroup --lb-name myLoadBalancer \
--name myLoadBalancerRuleSSH$i --protocol tcp \
--frontend-port 422$i --backend-port 3389 \
--frontend-ip-name myFrontEndPool
done

# Create a network security group


az network nsg create --resource-group myResourceGroup --name myNetworkSecurityGroup
# Create a network security group rule for port 3389.
az network nsg rule create --resource-group myResourceGroup --nsg-name myNetworkSecurityGroup --name
myNetworkSecurityGroupRuleSSH \
--protocol tcp --direction inbound --source-address-prefix '*' --source-port-range '*' \
--destination-address-prefix '*' --destination-port-range 3389 --access allow --priority 1000

# Create a network security group rule for port 80.


az network nsg rule create --resource-group myResourceGroup --nsg-name myNetworkSecurityGroup --name
myNetworkSecurityGroupRuleHTTP \
--protocol tcp --direction inbound --priority 1001 --source-address-prefix '*' --source-port-range '*' \
--destination-address-prefix '*' --destination-port-range 80 --access allow --priority 2000

# Create three virtual network cards and associate with public IP address and NSG.
for i in `seq 1 3`; do
az network nic create \
--resource-group myResourceGroup --name myNic$i \
--vnet-name myVnet --subnet mySubnet \
--network-security-group myNetworkSecurityGroup --lb-name myLoadBalancer \
--lb-address-pools myBackEndPool --lb-inbound-nat-rules myLoadBalancerRuleSSH$i
done

# Create an availability set.


az vm availability-set create --resource-group myResourceGroup --name myAvailabilitySet --platform-fault-
domain-count 3 --platform-update-domain-count 3

# Create three virtual machines.


for i in `seq 1 3`; do
az vm create \
--resource-group myResourceGroup \
--name myVM$i \
--availability-set myAvailabilitySet \
--nics myNic$i \
--image win2016datacenter \
--admin-password $AdminPassword \
--admin-username azureuser \
--no-wait
done

Clean up deployment
Run the following command to remove the resource group, VM, and all related resources.

az group delete --name myResourceGroup --yes

Script explanation
This script uses the following commands to create a resource group, virtual machine, availability set, load balancer,
and all related resources. Each command in the table links to command specific documentation.

COMMAND NOTES

az group create Creates a resource group in which all resources are stored.

az network vnet create Creates an Azure virtual network and subnet.

az network public-ip create Creates a public IP address with a static IP address and an
associated DNS name.

az network lb create Creates an Azure Network Load Balancer (NLB).


COMMAND NOTES

az network lb probe create Creates an NLB probe. An NLB probe is used to monitor each
VM in the NLB set. If any VM becomes inaccessible, traffic is
not routed to the VM.

az network lb rule create Creates an NLB rule. In this sample, a rule is created for port
80. As HTTP traffic arrives at the NLB, it is routed to port 80
one of the VMs in the NLB set.

az network lb inbound-nat-rule create Creates an NLB Network Address Translation (NAT) rule. NAT
rules map a port of the NLB to a port on a VM. In this sample,
a NAT rule is created for SSH traffic to each VM in the NLB set.

az network nsg create Creates a network security group (NSG), which is a security
boundary between the internet and the virtual machine.

az network nsg rule create Creates an NSG rule to allow inbound traffic. In this sample,
port 22 is opened for SSH traffic.

az network nic create Creates a virtual network card and attaches it to the virtual
network, subnet, and NSG.

az vm availability-set create Creates an availability set. Availability sets ensure application


uptime by spreading the virtual machines across physical
resources such that if failure occurs, the entire set is not
effected.

az vm create Creates the virtual machine and connects it to the network


card, virtual network, subnet, and NSG. This command also
specifies the virtual machine image to be used and
administrative credentials.

az group delete Deletes a resource group including all nested resources.

Next steps
For more information on the Azure CLI, see Azure CLI documentation.
Additional virtual machine CLI script samples can be found in the Azure Windows VM documentation.
Quick Create a virtual machine with the Azure CLI
11/13/2019 • 2 minutes to read • Edit Online

This script creates an Azure Virtual Machine running Windows Server 2016, and uses the Azure Virtual Machine
Custom Script Extension to install IIS. After running the script, you can access the default IIS website on the public
IP address of the virtual machine.
To run this sample, install the latest version of the Azure CLI. To start, run az login to create a connection with
Azure.
Samples for the Azure CLI are written for the bash shell. To run this sample in Windows PowerShell or Command
Prompt, you may need to change elements of the script.
If you don't have an Azure subscription, create a free account before you begin.

Sample script
#!/bin/bash

# Update for your admin password


AdminPassword=ChangeYourAdminPassword1

# Create a resource group.


az group create --name myResourceGroup --location westeurope

# Create a virtual machine.


az vm create \
--resource-group myResourceGroup \
--name myVM \
--image win2016datacenter \
--admin-username azureuser \
--admin-password $AdminPassword

# Open port 80 to allow web traffic to host.


az vm open-port --port 80 --resource-group myResourceGroup --name myVM

# Use CustomScript extension to install IIS.


az vm extension set \
--publisher Microsoft.Compute \
--version 1.8 \
--name CustomScriptExtension \
--vm-name myVM \
--resource-group myResourceGroup \
--settings '{"commandToExecute":"powershell.exe Install-WindowsFeature -Name Web-Server"}'

Clean up deployment
Run the following command to remove the resource group, VM, and all related resources.

az group delete --name myResourceGroup --yes

Script explanation
This script uses the following commands to create a resource group, virtual machine, and all related resources.
Each command in the table links to command specific documentation.

COMMAND NOTES

az group create Creates a resource group in which all resources are stored.

az vm create Creates the virtual machine and connects it to the network


card, virtual network, subnet, and network security group.
This command also specifies the virtual machine image to be
used and administrative credentials.

az vm open-port Creates a network security group rule to allow inbound traffic.


In this sample, port 80 is opened for HTTP traffic.

azure vm extension set Adds and runs a virtual machine extension to a VM. In this
sample, the custom script extension is used to install IIS.

az group delete Deletes a resource group including all nested resources.

Next steps
For more information on the Azure CLI, see Azure CLI documentation.
Additional virtual machine CLI script samples can be found in the Azure Windows VM documentation.
Create a VM with IIS using DSC
11/13/2019 • 2 minutes to read • Edit Online

This script creates a virtual machine, and uses the Azure Virtual Machine DSC custom script extension to install
and configure IIS.
To run this sample, install the latest version of the Azure CLI. To start, run az login to create a connection with
Azure.
Samples for the Azure CLI are written for the bash shell. To run this sample in Windows PowerShell or Command
Prompt, you may need to change elements of the script.
If you don't have an Azure subscription, create a free account before you begin.

Sample script
#!/bin/bash

# Update for your admin password


AdminPassword=ChangeYourAdminPassword1

# Create a resource group.


az group create --name myResourceGroup --location westus

# Create a VM
az vm create \
--resource-group myResourceGroup \
--name myVM \
--image win2016datacenter \
--admin-username azureuser \
--admin-password $AdminPassword

# Start a CustomScript extension to use a simple bash script to update, download and install WordPress and
MySQL
az vm extension set \
--name DSC \
--publisher Microsoft.Powershell \
--version 2.19 \
--vm-name myVM \
--resource-group myResourceGroup \
--settings '{"ModulesURL":"https://github.com/Azure/azure-quickstart-templates/raw/master/dsc-extension-
iis-server-windows-vm/ContosoWebsite.ps1.zip", "configurationFunction": "ContosoWebsite.ps1\\ContosoWebsite",
"Properties": {"MachineName": "myVM"} }'

# open port 80 to allow web traffic to host


az vm open-port \
--port 80 \
--resource-group myResourceGroup \
--name myVM

Clean up deployment
Run the following command to remove the resource group, VM, and all related resources.

az group delete --name myResourceGroup --yes


Script explanation
This script uses the following commands to create a resource group, virtual machine, and all related resources.
Each command in the table links to command specific documentation.

COMMAND NOTES

az group create Creates a resource group in which all resources are stored.

az vm create Creates the virtual machine and connects it to the network


card, virtual network, subnet, and NSG. This command also
specifies the virtual machine image to be used, and
administrative credentials.

az vm extension set Add the Custom Script Extension to the virtual machine which
invokes a script to install IIS.

az vm open-port Creates a network security group rule to allow inbound traffic.


In this sample, port 80 is opened for HTTP traffic.

az group delete Deletes a resource group including all nested resources.

Next steps
For more information on the Azure CLI, see Azure CLI documentation.
Additional virtual machine CLI script samples can be found in the Azure Windows VM documentation.
Create a managed disk from a VHD file in a storage
account in the same subscription with CLI
12/10/2019 • 2 minutes to read • Edit Online

This script creates a managed disk from a VHD file in a storage account in the same subscription. Use this script to
import a specialized (not generalized/sysprepped) VHD to managed OS disk to create a virtual machine. Or, use it
to import a data VHD to managed data disk.
To run this sample, install the latest version of the Azure CLI. To start, run az login to create a connection with
Azure.
Samples for the Azure CLI are written for the bash shell. To run this sample in Windows PowerShell or
Command Prompt, you may need to change elements of the script.
If you don't have an Azure subscription, create a free account before you begin.

Sample script
#Provide the subscription Id
subscriptionId=mySubscriptionId

#Provide the name of your resource group.


#Ensure that resource group is already created
resourceGroupName=myResourceGroupName

#Provide the name of the Managed Disk


diskName=myDiskName

#Provide the size of the disks in GB. It should be greater than the VHD file size.
diskSize=128

#Provide the URI of the VHD file that will be used to create Managed Disk.
# VHD file can be deleted as soon as Managed Disk is created.
# e.g. https://contosostorageaccount1.blob.core.windows.net/vhds/contosovhd123.vhd
vhdUri=https://contosostorageaccount1.blob.core.windows.net/vhds/contosoumd78620170425131836.vhd

#Provide the storage type for the Managed Disk. Premium_LRS or Standard_LRS.
storageType=Premium_LRS

#Provide the Azure location (e.g. westus) where Managed Disk will be located.
#The location should be same as the location of the storage account where VHD file is stored.
#Get all the Azure location supported for your subscription using command below:
#az account list-locations
location=westus

#Set the context to the subscription Id where Managed Disk will be created
az account set --subscription $subscriptionId

#Create the Managed disk from the VHD file


az disk create --resource-group $resourceGroupName --name $diskName --sku $storageType --location $location --
size-gb $diskSize --source $vhdUri

Script explanation
This script uses following commands to create a managed disk from a VHD. Each command in the table links to
command specific documentation.

COMMAND NOTES

az disk create Creates a managed disk using URI of a VHD in a storage


account in the same subscription

Next steps
For more information on the Azure CLI, see Azure CLI documentation.
Additional virtual machine and managed disks CLI script samples can be found in the Azure Windows VM
documentation.
Create a managed disk from a snapshot with CLI
12/10/2019 • 2 minutes to read • Edit Online

This script creates a managed disk from a snapshot. Use it to restore a virtual machine from snapshots of OS and
data disks. Create OS and data managed disks from respective snapshots and then create a new virtual machine
by attaching managed disks. You can also restore data disks of an existing VM by attaching data disks created from
snapshots.
To run this sample, install the latest version of the Azure CLI. To start, run az login to create a connection with
Azure.
Samples for the Azure CLI are written for the bash shell. To run this sample in Windows PowerShell or Command
Prompt, you may need to change elements of the script.
If you don't have an Azure subscription, create a free account before you begin.

Sample script
#Provide the subscription Id of the subscription where you want to create Managed Disks
subscriptionId=dd80b94e-0463-4a65-8d04-c94f403879dc

#Provide the name of your resource group


resourceGroupName=myResourceGroupName

#Provide the name of the snapshot that will be used to create Managed Disks
snapshotName=mySnapshotName

#Provide the name of the new Managed Disks that will be create
diskName=myDiskName

#Provide the size of the disks in GB. It should be greater than the VHD file size.
diskSize=128

#Provide the storage type for Managed Disk. Premium_LRS or Standard_LRS.


storageType=Premium_LRS

#Set the context to the subscription Id where Managed Disk will be created
az account set --subscription $subscriptionId

#Get the snapshot Id


snapshotId=$(az snapshot show --name $snapshotName --resource-group $resourceGroupName --query [id] -o tsv)

#Create a new Managed Disks using the snapshot Id


#Note that managed disk will be created in the same location as the snapshot
az disk create --resource-group $resourceGroupName --name $diskName --sku $storageType --size-gb $diskSize --
source $snapshotId

Script explanation
This script uses following commands to create a managed disk from a snapshot. Each command in the table links
to command specific documentation.
COMMAND NOTES

az snapshot show Gets all the properties of a snapshot using the name and
resource group properties of the snapshot. Id property is
used to create managed disk.

az disk create Creates a managed disk using snapshot Id of a managed


snapshot

Next steps
For more information on the Azure CLI, see Azure CLI documentation.
Additional virtual machine and managed disks CLI script samples can be found in the Azure Windows VM
documentation.
Copy managed disks to same or different
subscription with CLI
12/10/2019 • 2 minutes to read • Edit Online

This script copies a managed disk to same or different subscription but in the same region. The copy works only
when the subscriptions are part of same AAD tenant.
To run this sample, install the latest version of the Azure CLI. To start, run az login to create a connection with
Azure.
Samples for the Azure CLI are written for the bash shell. To run this sample in Windows PowerShell or Command
Prompt, you may need to change elements of the script.
If you don't have an Azure subscription, create a free account before you begin.

Sample script
#Provide the subscription Id of the subscription where managed disk exists
sourceSubscriptionId=dd80b94e-0463-4a65-8d04-c94f403879dc

#Provide the name of your resource group where managed disk exists
sourceResourceGroupName=mySourceResourceGroupName

#Provide the name of the managed disk


managedDiskName=myDiskName

#Set the context to the subscription Id where managed disk exists


az account set --subscription $sourceSubscriptionId

#Get the managed disk Id


managedDiskId=$(az disk show --name $managedDiskName --resource-group $sourceResourceGroupName --query [id] -o
tsv)

#If managedDiskId is blank then it means that managed disk does not exist.
echo 'source managed disk Id is: ' $managedDiskId

#Provide the subscription Id of the subscription where managed disk will be copied to
targetSubscriptionId=6492b1f7-f219-446b-b509-314e17e1efb0

#Name of the resource group where managed disk will be copied to


targetResourceGroupName=mytargetResourceGroupName

#Set the context to the subscription Id where managed disk will be copied to
az account set --subscription $targetSubscriptionId

#Copy managed disk to different subscription using managed disk Id


az disk create --resource-group $targetResourceGroupName --name $managedDiskName --source $managedDiskId

Script explanation
This script uses following commands to create a new managed disk in the target subscription using the Id of the
source managed disk. Each command in the table links to command specific documentation.
COMMAND NOTES

az disk show Gets all the properties of a managed disk using the name and
resource group properties of the managed disk. Id property is
used to copy the managed disk to different subscription.

az disk create Copies a managed disk by creating a new managed disk in


different subscription using Id and name the parent managed
disk.

Next steps
For more information on the Azure CLI, see Azure CLI documentation.
Additional virtual machine and managed disks CLI script samples can be found in the Azure Windows VM
documentation.
Export/Copy a snapshot to a storage account in
different region with CLI
12/10/2019 • 2 minutes to read • Edit Online

This script exports a managed snapshot to a storage account in different region. It first generates the SAS URI of
the snapshot and then uses it to copy it to a storage account in different region. Use this script to maintain backup
of your managed disks in different region for disaster recovery.
To run this sample, install the latest version of the Azure CLI. To start, run az login to create a connection with
Azure.
Samples for the Azure CLI are written for the bash shell. To run this sample in Windows PowerShell or Command
Prompt, you may need to change elements of the script.
If you don't have an Azure subscription, create a free account before you begin.

Sample script
#Provide the subscription Id where snapshot is created
subscriptionId=dd80b94e-0463-4a65-8d04-c94f403879dc

#Provide the name of your resource group where snapshot is created


resourceGroupName=myResourceGroupName

#Provide the snapshot name


snapshotName=mySnapshotName

#Provide Shared Access Signature (SAS) expiry duration in seconds e.g. 3600.
#Know more about SAS here: https://docs.microsoft.com/en-us/azure/storage/storage-dotnet-shared-access-
signature-part-1
sasExpiryDuration=3600

#Provide storage account name where you want to copy the snapshot.
storageAccountName=mystorageaccountname

#Name of the storage container where the downloaded snapshot will be stored
storageContainerName=mystoragecontainername

#Provide the key of the storage account where you want to copy snapshot.
storageAccountKey=mystorageaccountkey

#Provide the name of the VHD file to which snapshot will be copied.
destinationVHDFileName=myvhdfilename

az account set --subscription $subscriptionId

sas=$(az snapshot grant-access --resource-group $resourceGroupName --name $snapshotName --duration-in-seconds


$sasExpiryDuration --query [accessSas] -o tsv)

az storage blob copy start --destination-blob $destinationVHDFileName --destination-container


$storageContainerName --account-name $storageAccountName --account-key $storageAccountKey --source-uri $sas
Script explanation
This script uses following commands to generate SAS URI for a managed snapshot and copies the snapshot to a
storage account using SAS URI. Each command in the table links to command specific documentation.

COMMAND NOTES

az snapshot grant-access Generates read-only SAS that is used to copy underlying VHD
file to a storage account or download it to on-premises

az storage blob copy start Copies a blob asynchronously from one storage account to
another

Next steps
Create a managed disk from a VHD
For more information on the Azure CLI, see Azure CLI documentation.
Additional virtual machine and managed disks CLI script samples can be found in the Azure Windows VM
documentation.
Export/Copy a managed disk to a storage account
using the Azure CLI
12/10/2019 • 2 minutes to read • Edit Online

This script exports the underlying VHD of a managed disk to a storage account in same or different region. It first
generates the SAS URI of the managed disk and then uses it to copy the VHD to a storage account. Use this script
to copy your managed disks for regional expansion.
To run this sample, install the latest version of the Azure CLI. To start, run az login to create a connection with
Azure.
Samples for the Azure CLI are written for the bash shell. To run this sample in Windows PowerShell or Command
Prompt, you may need to change elements of the script.
If you don't have an Azure subscription, create a free account before you begin.

Sample script
#Provide the subscription Id where managed disk is created
subscriptionId=yourSubscriptionId

#Provide the name of your resource group where managed disk is created
resourceGroupName=myResourceGroupName

#Provide the managed disk name


diskName=myDiskName

#Provide Shared Access Signature (SAS) expiry duration in seconds e.g. 3600.
#Know more about SAS here: https://docs.microsoft.com/en-us/azure/storage/storage-dotnet-shared-access-
signature-part-1
sasExpiryDuration=3600

#Provide storage account name where you want to copy the underlying VHD file of the managed disk.
storageAccountName=mystorageaccountname

#Name of the storage container where the downloaded VHD will be stored
storageContainerName=mystoragecontainername

#Provide the key of the storage account where you want to copy the VHD
storageAccountKey=mystorageaccountkey

#Provide the name of the destination VHD file to which the VHD of the managed disk will be copied.
destinationVHDFileName=myvhdfilename.vhd

az account set --subscription $subscriptionId

sas=$(az disk grant-access --resource-group $resourceGroupName --name $diskName --duration-in-seconds


$sasExpiryDuration --query [accessSas] -o tsv)

az storage blob copy start --destination-blob $destinationVHDFileName --destination-container


$storageContainerName --account-name $storageAccountName --account-key $storageAccountKey --source-uri $sas
Script explanation
This script uses following commands to generate the SAS URI for a managed disk and copies the underlying VHD
to a storage account using the SAS URI. Each command in the table links to command specific documentation.

COMMAND NOTES

az disk grant-access Generates read-only SAS that is used to copy the underlying
VHD file to a storage account or download it to on-premises

az storage blob copy start Copies a blob asynchronously from one storage account to
another

Next steps
Create a managed disk from a VHD
For more information on the Azure CLI, see Azure CLI documentation.
Additional virtual machine and managed disks CLI script samples can be found in the Azure Windows VM
documentation.
Copy snapshot of a managed disk to same or
different subscription with CLI
12/10/2019 • 2 minutes to read • Edit Online

This script copies a snapshot of a managed disk to same or different subscription. Use this script for the following
scenarios:
1. Migrate a snapshot in Premium storage (Premium_LRS ) to Standard storage (Standard_LRS or Standard_ZRS )
to reduce your cost.
2. Migrate a snapshot from locally redundant storage (Premium_LRS, Standard_LRS ) to zone redundant storage
(Standard_ZRS ) to benefit from the higher reliability of ZRS storage.
3. Move a snapshot to different subscription in the same region for longer retention.
To run this sample, install the latest version of the Azure CLI. To start, run az login to create a connection with
Azure.
Samples for the Azure CLI are written for the bash shell. To run this sample in Windows PowerShell or Command
Prompt, you may need to change elements of the script.
If you don't have an Azure subscription, create a free account before you begin.

Sample script
#Provide the subscription Id of the subscription where snapshot exists
sourceSubscriptionId=dd80b94e-0463-4a65-8d04-c94f403879dc

#Provide the name of your resource group where snapshot exists


sourceResourceGroupName=mySourceResourceGroupName

#Provide the name of the snapshot


snapshotName=mySnapshotName

#Set the context to the subscription Id where snapshot exists


az account set --subscription $sourceSubscriptionId

#Get the snapshot Id


snapshotId=$(az snapshot show --name $snapshotName --resource-group $sourceResourceGroupName --query [id] -o
tsv)

#If snapshotId is blank then it means that snapshot does not exist.
echo 'source snapshot Id is: ' $snapshotId

#Provide the subscription Id of the subscription where snapshot will be copied to


#If snapshot is copied to the same subscription then you can skip this step
targetSubscriptionId=6492b1f7-f219-446b-b509-314e17e1efb0

#Name of the resource group where snapshot will be copied to


targetResourceGroupName=mytargetResourceGroupName

#Set the context to the subscription Id where snapshot will be copied to


#If snapshot is copied to the same subscription then you can skip this step
az account set --subscription $targetSubscriptionId

#Copy snapshot to different subscription using the snapshot Id


#We recommend you to store your snapshots in Standard storage to reduce cost. Please use Standard_ZRS in
regions where zone redundant storage (ZRS) is available, otherwise use Standard_LRS
#Please check out the availability of ZRS here: https://docs.microsoft.com/en-us/azure/storage/common/storage-
redundancy-zrs#support-coverage-and-regional-availability
az snapshot create --resource-group $targetResourceGroupName --name $snapshotName --source $snapshotId --sku
Standard_LRS

Script explanation
This script uses following commands to create a snapshot in the target subscription using the Id of the source
snapshot. Each command in the table links to command specific documentation.

COMMAND NOTES

az snapshot show Gets all the properties of a snapshot using the name and
resource group properties of the snapshot. Id property is
used to copy the snapshot to different subscription.

az snapshot create Copies a snapshot by creating a snapshot in different


subscription using the Id and name of the parent snapshot.

Next steps
For more information on the Azure CLI, see Azure CLI documentation.
Additional virtual machine and managed disks CLI script samples can be found in the Azure Windows VM
documentation.
Secure network traffic between virtual machines
11/13/2019 • 3 minutes to read • Edit Online

This script creates two virtual machines and secures incoming traffic to both. One virtual machine is accessible on
the internet and has a network security group (NSG ) configured to allow traffic on port 3389 and port 80. The
second virtual machine is not accessible on the internet, and has an NSG configured to only allow traffic from the
first virtual machine.
To run this sample, install the latest version of the Azure CLI. To start, run az login to create a connection with
Azure.
Samples for the Azure CLI are written for the bash shell. To run this sample in Windows PowerShell or Command
Prompt, you may need to change elements of the script.
If you don't have an Azure subscription, create a free account before you begin.

Sample script
#!/bin/bash

# Update for your admin password


AdminPassword=ChangeYourAdminPassword1

# Create a resource group.


az group create --name myResourceGroup --location westeurope

# Create a virtual network and front-end subnet.


az network vnet create --resource-group myResourceGroup --name myVnet --address-prefix 10.0.0.0/16 \
--subnet-name mySubnetFrontEnd --subnet-prefix 10.0.1.0/24

# Create a back-end subnet and associate with virtual network.


az network vnet subnet create --resource-group myResourceGroup --vnet-name myVnet \
--name mySubnetBackEnd --address-prefix 10.0.2.0/24

# Create a front-end virtual machine.


az vm create --resource-group myResourceGroup --name myVMFrontEnd --image win2016datacenter \
--admin-username azureuser --admin-password $AdminPassword --vnet-name myVnet --subnet mySubnetFrontEnd \
--nsg myNetworkSecurityGroupFrontEnd --no-wait

# Create a back-end virtual machine without a public IP address.


az vm create --resource-group myResourceGroup --name myVMBackEnd --image win2016datacenter \
--admin-username azureuser --admin-password $AdminPassword --public-ip-address "" --vnet-name myVnet \
--subnet mySubnetBackEnd --nsg myNetworkSecurityGroupBackEnd

# Create front-end NSG rule to allow traffic on port 80.


az network nsg rule create --resource-group myResourceGroup --nsg-name myNetworkSecurityGroupFrontEnd \
--name http --access allow --protocol Tcp --direction Inbound --priority 200 \
--source-address-prefix "*" --source-port-range "*" --destination-address-prefix "*" --destination-port-
range 80

# Get nsg rule name.


nsgrule=$(az network nsg rule list --resource-group myResourceGroup --nsg-name myNetworkSecurityGroupBackEnd -
-query [0].name -o tsv)

# Update back-end network security group rule to limit SSH to source prefix (priority 100).
az network nsg rule update --resource-group myResourceGroup --nsg-name myNetworkSecurityGroupBackEnd \
--name $nsgrule --protocol tcp --direction inbound --priority 100 \
--source-address-prefix 10.0.1.0/24 --source-port-range '*' --destination-address-prefix '*' \
--destination-port-range 22 --access allow

# Create backend NSG rule to block all incoming traffic (priority 200).
az network nsg rule create --resource-group myResourceGroup --nsg-name myNetworkSecurityGroupBackEnd \
--name denyAll --access Deny --protocol Tcp --direction Inbound --priority 200 \
--source-address-prefix "*" --source-port-range "*" --destination-address-prefix "*" --destination-port-
range "*"

Clean up deployment
Run the following command to remove the resource group, VM, and all related resources.

az group delete --name myResourceGroup --yes

Script explanation
This script uses the following commands to create a resource group, virtual machine, and all related resources.
Each command in the table links to command specific documentation.
COMMAND NOTES

az group create Creates a resource group in which all resources are stored.

az network vnet create Creates an Azure virtual network and subnet.

az network vnet subnet create Creates a subnet.

az vm create Creates the virtual machine and connects it to the network


card, virtual network, subnet, and NSG. This command also
specifies the virtual machine image to be used, and
administrative credentials.

az network nsg rule update Updates an NSG rule. In this sample, the back-end rule is
updated to pass through traffic only from the front-end
subnet.

az network nsg rule list Returns information about a network security group rule. In
this sample, the rule name is stored in a variable for use later
in the script.

az group delete Deletes a resource group including all nested resources.

Next steps
For more information on the Azure CLI, see Azure CLI documentation.
Additional virtual machine CLI script samples can be found in the Azure Windows VM documentation.
Encrypt a Windows virtual machine in Azure
11/13/2019 • 2 minutes to read • Edit Online

This script creates a secure Azure Key Vault, encryption keys, Azure Active Directory service principal, and a
Windows virtual machine (VM ). The VM is then encrypted using the encryption key from Key Vault and service
principal credentials.
To run this sample, install the latest version of the Azure CLI. To start, run az login to create a connection with
Azure.
Samples for the Azure CLI are written for the bash shell. To run this sample in Windows PowerShell or Command
Prompt, you may need to change elements of the script.
If you don't have an Azure subscription, create a free account before you begin.

Sample script
#!/bin/bash

# Provide your own unique Key Vault name


keyvault_name=<your_unique_keyvault_name>

# Register the Key Vault provider and create a resource group.


az provider register -n Microsoft.KeyVault
az group create --name myResourceGroup --location eastus

# Create a Key Vault for storing keys and enabled for disk encryption.
az keyvault create --name $keyvault_name --resource-group myResourceGroup --location eastus \
--enabled-for-disk-encryption True

# Create a key within the Key Vault.


az keyvault key create --vault-name $keyvault_name --name myKey --protection software

# Create an Azure Active Directory service principal for authenticating requests to Key Vault.
# Read in the service principal ID and password for use in later commands.
read sp_id sp_password <<< $(az ad sp create-for-rbac --query [appId,password] -o tsv)

# Grant permissions on the Key Vault to the AAD service principal.


az keyvault set-policy --name $keyvault_name \
--spn $sp_id \
--key-permissions wrapKey \
--secret-permissions set

# Create a virtual machine.


az vm create \
--resource-group myResourceGroup \
--name myVM \
--name myVM --image win2016datacenter \
--admin-username azureuser \
--admin-password myPassword12

# Encrypt the VM disks.


az vm encryption enable --resource-group myResourceGroup --name myVM \
--aad-client-id $sp_id \
--aad-client-secret $sp_password \
--disk-encryption-keyvault $keyvault_name \
--key-encryption-key myKey \
--volume-type all

# Output how to monitor the encryption status and next steps.


echo "The encryption process can take some time. View status with:

az vm encryption show --resource-group myResourceGroup --name myVM --query [osDisk] -o tsv

When encryption status shows \`Encrypted\`, restart the VM with:

az vm restart --resource-group myResourceGroup --name myVM"

Clean up deployment
Run the following command to remove the resource group, VM, and all related resources.

az group delete --name myResourceGroup

Script explanation
This script uses the following commands to create a resource group, Azure Key Vault, service principal, virtual
machine, and all related resources. Each command in the table links to command specific documentation.
COMMAND NOTES

az group create Creates a resource group in which all resources are stored.

az keyvault create Creates an Azure Key Vault to store secure data such as
encryption keys.

az keyvault key create Creates an encryption key in Key Vault.

az ad sp create-for-rbac Creates an Azure Active Directory service principal to securely


authenticate and control access to encryption keys.

az keyvault set-policy Sets permissions on the Key Vault to grant the service
principal access to encryption keys.

az vm create Creates the virtual machine and connects it to the network


card, virtual network, subnet, and NSG. This command also
specifies the virtual machine image to be used, and
administrative credentials.

az vm encryption enable Enables encryption on a VM using the service principal


credentials and encryption key.

az vm encryption show Shows the status of the VM encryption process.

az group delete Deletes a resource group including all nested resources.

Next steps
For more information on the Azure CLI, see Azure CLI documentation.
Additional virtual machine CLI script samples can be found in the Azure Windows VM documentation.
Monitor a VM with Azure Monitor logs
11/13/2019 • 2 minutes to read • Edit Online

This script creates an Azure Virtual Machine, installs the Log Analytics agent, and enrolls the system with a Log
Analytics workspace. Once the script has run, the virtual machine will be visible in Azure Monitoring.
To run this sample, install the latest version of the Azure CLI. To start, run az login to create a connection with
Azure.
Samples for the Azure CLI are written for the bash shell. To run this sample in Windows PowerShell or Command
Prompt, you may need to change elements of the script.
If you don't have an Azure subscription, create a free account before you begin.

Sample script
#!/bin/sh

# Update for your admin password


AdminPassword=ChangeYourAdminPassword1

# OMS Id and OMS key.


omsid=<Replace with your OMS Id>
omskey=<Replace with your OMS key>

# Create a resource group.


az group create --name myResourceGroup --location westeurope

# Create a virtual machine.


az vm create \
--resource-group myResourceGroup \
--name myVM \
--image win2016datacenter \
--admin-username azureuser \
--admin-password $AdminPassword

# Install and configure the OMS agent.


az vm extension set \
--resource-group myResourceGroup \
--vm-name myVM --name MicrosoftMonitoringAgent \
--publisher Microsoft.EnterpriseCloud.Monitoring \
--version 1.0 --protected-settings '{"workspaceKey": "'"$omskey"'"}' \
--settings '{"workspaceId": "'"$omsid"'"}'

Clean up deployment
Run the following command to remove the resource group, VM, and all related resources.

az group delete --name myResourceGroup --yes

Script explanation
This script uses the following commands to create a resource group, virtual machine, and all related resources.
Each command in the table links to command specific documentation.
COMMAND NOTES

az group create Creates a resource group in which all resources are stored.

az vm create Creates the virtual machine and connects it to the network


card, virtual network, subnet, and NSG. This command also
specifies the virtual machine image to be used, and
administrative credentials.

azure vm extension set Runs a VM extension against a virtual machine.

az group delete Deletes a resource group including all nested resources.

Next steps
For more information on the Azure CLI, see Azure CLI documentation.
Additional virtual machine CLI script samples can be found in the Azure Windows VM documentation.
Azure Resource Manager overview
12/23/2019 • 5 minutes to read • Edit Online

Azure Resource Manager is the deployment and management service for Azure. It provides a management layer
that enables you to create, update, and delete resources in your Azure subscription. You use management
features, like access control, locks, and tags, to secure and organize your resources after deployment.
To learn about Azure Resource Manager templates, see Template deployment overview.

Consistent management layer


When a user sends a request from any of the Azure tools, APIs, or SDKs, Resource Manager receives the request.
It authenticates and authorizes the request. Resource Manager sends the request to the Azure service, which
takes the requested action. Because all requests are handled through the same API, you see consistent results and
capabilities in all the different tools.
The following image shows the role Azure Resource Manager plays in handling Azure requests.

All capabilities that are available in the portal are also available through PowerShell, Azure CLI, REST APIs, and
client SDKs. Functionality initially released through APIs will be represented in the portal within 180 days of
initial release.

Terminology
If you're new to Azure Resource Manager, there are some terms you might not be familiar with.
resource - A manageable item that is available through Azure. Virtual machines, storage accounts, web apps,
databases, and virtual networks are examples of resources.
resource group - A container that holds related resources for an Azure solution. The resource group includes
those resources that you want to manage as a group. You decide which resources belong in a resource group
based on what makes the most sense for your organization. See Resource groups.
resource provider - A service that supplies Azure resources. For example, a common resource provider is
Microsoft.Compute, which supplies the virtual machine resource. Microsoft.Storage is another common
resource provider. See Resource providers and types.
Resource Manager template - A JavaScript Object Notation (JSON ) file that defines one or more resources
to deploy to a resource group or subscription. The template can be used to deploy the resources consistently
and repeatedly. See Template deployment overview.
declarative syntax - Syntax that lets you state "Here is what I intend to create" without having to write the
sequence of programming commands to create it. The Resource Manager template is an example of
declarative syntax. In the file, you define the properties for the infrastructure to deploy to Azure. See Template
deployment overview.

The benefits of using Resource Manager


With Resource Manager, you can:
Manage your infrastructure through declarative templates rather than scripts.
Deploy, manage, and monitor all the resources for your solution as a group, rather than handling these
resources individually.
Redeploy your solution throughout the development lifecycle and have confidence your resources are
deployed in a consistent state.
Define the dependencies between resources so they're deployed in the correct order.
Apply access control to all services in your resource group because Role-Based Access Control (RBAC ) is
natively integrated into the management platform.
Apply tags to resources to logically organize all the resources in your subscription.
Clarify your organization's billing by viewing costs for a group of resources sharing the same tag.

Understand scope
Azure provides four levels of scope: management groups, subscriptions, resource groups, and resources. The
following image shows an example of these layers.

You apply management settings at any of these levels of scope. The level you select determines how widely the
setting is applied. Lower levels inherit settings from higher levels. For example, when you apply a policy to the
subscription, the policy is applied to all resource groups and resources in your subscription. When you apply a
policy on the resource group, that policy is applied the resource group and all its resources. However, another
resource group doesn't have that policy assignment.
You can deploy templates to management groups, subscriptions, or resource groups.

Resource groups
There are some important factors to consider when defining your resource group:
All the resources in your group should share the same lifecycle. You deploy, update, and delete them
together. If one resource, such as a database server, needs to exist on a different deployment cycle it should
be in another resource group.
Each resource can only exist in one resource group.
You can add or remove a resource to a resource group at any time.
You can move a resource from one resource group to another group. For more information, see Move
resources to new resource group or subscription.
A resource group can contain resources that are located in different regions.
A resource group can be used to scope access control for administrative actions.
A resource can interact with resources in other resource groups. This interaction is common when the two
resources are related but don't share the same lifecycle (for example, web apps connecting to a database).
When creating a resource group, you need to provide a location for that resource group. You may be wondering,
"Why does a resource group need a location? And, if the resources can have different locations than the resource
group, why does the resource group location matter at all?" The resource group stores metadata about the
resources. When you specify a location for the resource group, you're specifying where that metadata is stored.
For compliance reasons, you may need to ensure that your data is stored in a particular region.
If the resource group's region is temporarily unavailable, you can't update resources in the resource group
because the metadata is unavailable. The resources in other regions will still function as expected, but you can't
update them. For more information about building reliable applications, see Designing reliable Azure
applications.

Resiliency of Azure Resource Manager


The Azure Resource Manager service is designed for resiliency and continuous availability. Resource Manager
and control plane operations (requests sent to management.azure.com) in the REST API are:
Distributed across regions. Some services are regional.
Distributed across Availability Zones (as well regions) in locations that have multiple Availability Zones.
Not dependent on a single logical data center.
Never taken down for maintenance activities.
This resiliency applies to services that receive requests through Resource Manager. For example, Key Vault
benefits from this resiliency.

Next steps
For all the operations offered by resource providers, see the Azure REST APIs.
To learn about moving resources, see Move resources to new resource group or subscription.
To learn about tagging resources, see Use tags to organize your Azure resources.
To learn about locking resources, see Lock resources to prevent unexpected changes.
For information about creating templates for deployments, see Template deployment overview.
Regions for virtual machines in Azure
1/19/2020 • 4 minutes to read • Edit Online

It is important to understand how and where your virtual machines (VMs) operate in Azure, along with your
options to maximize performance, availability, and redundancy. This article provides you with an overview of the
availability and redundancy features of Azure.

What are Azure regions?


Azure operates in multiple datacenters around the world. These datacenters are grouped in to geographic regions,
giving you flexibility in choosing where to build your applications.
You create Azure resources in defined geographic regions like 'West US', 'North Europe', or 'Southeast Asia'. You
can review the list of regions and their locations. Within each region, multiple datacenters exist to provide for
redundancy and availability. This approach gives you flexibility as you design applications to create VMs closest to
your users and to meet any legal, compliance, or tax purposes.

Special Azure regions


Azure has some special regions that you may wish to use when building out your applications for compliance or
legal purposes. These special regions include:
US Gov Virginia and US Gov Iowa
A physical and logical network-isolated instance of Azure for US government agencies and partners,
operated by screened US persons. Includes additional compliance certifications such as FedRAMP and
DISA. Read more about Azure Government.
China East and China North
These regions are available through a unique partnership between Microsoft and 21Vianet, whereby
Microsoft does not directly maintain the datacenters. See more about Azure China 21Vianet.
Germany Central and Germany Northeast
These regions are available via a data trustee model whereby customer data remains in Germany under
control of T-Systems, a Deutsche Telekom company, acting as the German data trustee.

Region pairs
Each Azure region is paired with another region within the same geography (such as US, Europe, or Asia). This
approach allows for the replication of resources, such as VM storage, across a geography that should reduce the
likelihood of natural disasters, civil unrest, power outages, or physical network outages affecting both regions at
once. Additional advantages of region pairs include:
In the event of a wider Azure outage, one region is prioritized out of every pair to help reduce the time to
restore for applications.
Planned Azure updates are rolled out to paired regions one at a time to minimize downtime and risk of
application outage.
Data continues to reside within the same geography as its pair (except for Brazil South) for tax and law
enforcement jurisdiction purposes.
Examples of region pairs include:
PRIMARY SECONDARY

West US East US

North Europe West Europe

Southeast Asia East Asia

You can see the full list of regional pairs here.

Feature availability
Some services or VM features are only available in certain regions, such as specific VM sizes or storage types.
There are also some global Azure services that do not require you to select a particular region, such as Azure
Active Directory, Traffic Manager, or Azure DNS. To assist you in designing your application environment, you can
check the availability of Azure services across each region. You can also programmatically query the supported VM
sizes and restrictions in each region.

Storage availability
Understanding Azure regions and geographies becomes important when you consider the available storage
replication options. Depending on the storage type, you have different replication options.
Azure Managed Disks
Locally redundant storage (LRS )
Replicates your data three times within the region in which you created your storage account.
Storage account-based disks
Locally redundant storage (LRS )
Replicates your data three times within the region in which you created your storage account.
Zone redundant storage (ZRS )
Replicates your data three times across two to three facilities, either within a single region or across two
regions.
Geo-redundant storage (GRS )
Replicates your data to a secondary region that is hundreds of miles away from the primary region.
Read-access geo-redundant storage (RA-GRS )
Replicates your data to a secondary region, as with GRS, but also then provides read-only access to the
data in the secondary location.
The following table provides a quick overview of the differences between the storage replication types:

REPLICATION
STRATEGY LRS ZRS GRS RA-GRS

Data is replicated No Yes Yes Yes


across multiple
facilities.

Data can be read No No No Yes


from the secondary
location and from the
primary location.
REPLICATION
STRATEGY LRS ZRS GRS RA-GRS

Number of copies of 3 3 6 6
data maintained on
separate nodes.

You can read more about Azure Storage replication options here. For more information about managed disks, see
Azure Managed Disks overview.
Storage costs
Prices vary depending on the storage type and availability that you select.
Azure Managed Disks
Premium Managed Disks are backed by Solid-State Drives (SSDs) and Standard Managed Disks are backed by
regular spinning disks. Both Premium and Standard Managed Disks are charged based on the provisioned
capacity for the disk.
Unmanaged disks
Premium storage is backed by Solid-State Drives (SSDs) and is charged based on the capacity of the disk.
Standard storage is backed by regular spinning disks and is charged based on the in-use capacity and desired
storage availability.
For RA-GRS, there is an additional Geo-Replication Data Transfer charge for the bandwidth of replicating
that data to another Azure region.
See Azure Storage Pricing for pricing information on the different storage types and availability options.
Availability options for virtual machines in Azure
1/19/2020 • 5 minutes to read • Edit Online

This article provides you with an overview of the availability features of Azure virtual machines (VMs).

High availability
Workloads are typically spread across different virtual machines to gain high throughput, performance, and to
create redundancy in case a VM is impacted due to an update or other event.
There are few options that Azure provides to achieve High Availability. First let’s talk about basic constructs.
Availability zones
Availability zones expand the level of control you have to maintain the availability of the applications and data on
your VMs. An Availability Zone is a physically separate zone, within an Azure region. There are three Availability
Zones per supported Azure region.
Each Availability Zone has a distinct power source, network, and cooling. By architecting your solutions to use
replicated VMs in zones, you can protect your apps and data from the loss of a datacenter. If one zone is
compromised, then replicated apps and data are instantly available in another zone.

Learn more about deploying a Windows or Linux VM in an Availability Zone.


Fault domains
A fault domain is a logical group of underlying hardware that share a common power source and network switch,
similar to a rack within an on-premises datacenter.
Update domains
An update domain is a logical group of underlying hardware that can undergo maintenance or be rebooted at the
same time.
This approach ensures that at least one instance of your application always remains running as the Azure platform
undergoes periodic maintenance. The order of update domains being rebooted may not proceed sequentially
during maintenance, but only one update domain is rebooted at a time.

Virtual Machines Scale Sets


Azure virtual machine scale sets let you create and manage a group of load balanced VMs. The number of VM
instances can automatically increase or decrease in response to demand or a defined schedule. Scale sets provide
high availability to your applications, and allow you to centrally manage, configure, and update many VMs. We
recommended that two or more VMs are created within a scale set to provide for a highly available application and
to meet the 99.95% Azure SLA. There is no cost for the scale set itself, you only pay for each VM instance that you
create. When a single VM is using Azure premium SSDs, the Azure SLA applies for unplanned maintenance
events. Virtual machines in a scale set can be deployed across multiple update domains and fault domains to
maximize availability and resilience to outages due to data center outages, and planned or unplanned maintenance
events. Virtual machines in a scale set can also be deployed into a single Availability zone, or regionally. Availability
zone deployment options may differ based on the orchestration mode.
Preview: Orchestration mode Preview
Virtual machines scale sets allow you to specify orchestration mode. With the virtual machine scale set
orchestration mode (preview ), you can now choose whether the scale set should orchestrate virtual machines
which are created explicitly outside of a scale set configuration model, or virtual machine instances created
implicitly based on the configuration model. Choose the orchestration mode that VM orchestration model allows
you group explicitly defined Virtual Machines together in a region or in an availability zone. Virtual machines
deployed in an Availability Zone provides zonal isolation to VMs are they are bound to the availability zone
boundary and are not subjected to any failures that may occur in other availability zone in the region.

“ORCHESTRATIONMODE”: “VM” “ORCHESTRATIONMODE”: “SCALESETVM”


(VIRTUALMACHINE) (VIRTUALMACHINESCALESETVM)

VM configuration model None. VirtualMachineProfile is Required. VirtualMachineProfile is


undefined in the scale set model. populated in the scale set model.

Adding new VM to Scale Set VMs are explicitly added to the scale set VMs are implicitly created and added to
when the VM is created. the scale set based on the VM
configuration model, instance count,
and AutoScaling rules.

Availability Zones Supports regional deployment or VMs Supports regional deployment or


in one Availability Zone multiple Availability Zones; Can define
the zone balancing strategy

Fault domains Can define fault domains count. 2 or 3 Can define 1, 2, or 3 fault domains for
based on regional support and 5 for non-zonal deployments, and 5 for
Availability zone. The assigned VM fault Availability zone deployments. The
domain will persist with VM lifecycle, assigned VM fault domain does not
including deallocate and restart. persist with VM lifecycle, virtual
machines are assigned a fault domain at
time of allocation.

Update domains N/A. Update domains are automatically N/A. Update domains are automatically
mapped to fault domains mapped to fault domains

Fault domains and update domains


Virtual machine scale sets simplify designing for high availability by aligning fault domains and update domains.
You will only have to define fault domains count for the scale set. The number of fault domains available to the
scale sets may vary by region. See Manage the availability of virtual machines in Azure.

Availability sets
An availability set is a logical grouping of VMs within a datacenter that allows Azure to understand how your
application is built to provide for redundancy and availability. We recommended that two or more VMs are created
within an availability set to provide for a highly available application and to meet the 99.95% Azure SLA. There is
no cost for the Availability Set itself, you only pay for each VM instance that you create. When a single VM is using
Azure premium SSDs, the Azure SLA applies for unplanned maintenance events.
In an availability set, VMs are automatically distributed across these fault domains. This approach limits the impact
of potential physical hardware failures, network outages, or power interruptions.
For VMs using Azure Managed Disks, VMs are aligned with managed disk fault domains when using a managed
availability set. This alignment ensures that all the managed disks attached to a VM are within the same managed
disk fault domain.
Only VMs with managed disks can be created in a managed availability set. The number of managed disk fault
domains varies by region - either two or three managed disk fault domains per region. You can read more about
these managed disk fault domains for Linux VMs or Windows VMs.

VMs within an availability set are also automatically distributed across update domains.

Next steps
You can now start to use these availability and redundancy features to build your Azure environment. For best
practices information, see Azure availability best practices.
Co-locate resource for improved latency
10/30/2019 • 3 minutes to read • Edit Online

When deploying your application in Azure, spreading instances across regions or availability zones creates network
latency, which may impact the overall performance of your application.

Proximity placement groups


Placing VMs in a single region reduces the physical distance between the instances. Placing them within a single
availability zone will also bring them physically closer together. However, as the Azure footprint grows, a single
availability zone may span multiple physical data centers, which may result in a network latency impacting your
application.
To get VMs as close as possible, achieving the lowest possible latency, you should deploy them within a proximity
placement group.
A proximity placement group is a logical grouping used to make sure that Azure compute resources are physically
located close to each other. Proximity placement groups are useful for workloads where low latency is a
requirement.
Low latency between stand-alone VMs.
Low Latency between VMs in a single availability set or a virtual machine scale set.
Low latency between stand-alone VMs, VMs in multiple Availability Sets, or multiple scale sets. You can have
multiple compute resources in a single placement group to bring together a multi-tiered application.
Low latency between multiple application tiers using different hardware types. For example, running the
backend using M -series in an availability set and the front end on a D -series instance, in a scale set, in a single
proximity placement group.
Using Proximity Placement Groups
A proximity placement group is a new resource type in Azure. You need to create one before using it with other
resources. Once created, it could be used with virtual machines, availability sets, or virtual machine scale sets. You
specify a proximity placement group when creating compute resources providing the proximity placement group
ID.
You can also move an existing resource into a proximity placement group. When moving a resource into a
proximity placement group, you should stop (deallocate) the asset first since it will be redeployed potentially into a
different data center in the region so satisfy the colocation constraint.
In the case of availability sets and virtual machine scale sets, you should set the proximity placement group at the
resource level rather than the individual virtual machines.
A proximity placement group is a colocation constraint rather than a pinning mechanism. It is pinned to a specific
data center with the deployment of the first resource to use it. Once all resources using the proximity placement
group have been stopped (deallocated) or deleted, it is no longer pinned. Therefore, when using a proximity
placement group with multiple VM series, it is important to specify all the required types upfront in a template
when possible or follow a deployment sequence which will improve your chances for a successful deployment. If
your deployment fails, restart the deployment with the VM size which has failed as the first size to be deployed.

Best practices
For the lowest latency, use proximity placement groups together with accelerated networking. For more
information, see Create a Linux virtual machine with Accelerated Networking or Create a Windows virtual
machine with Accelerated Networking.
Deploy all VM sizes in a single template. In order to avoid landing on hardware that doesn't support all the VM
SKUs and sizes you require, include all of the application tiers in a single template so that they will all be
deployed at the same time.
If you are scripting your deployment using PowerShell, CLI or the SDK, you may get an allocation error
OverconstrainedAllocationRequest . In this case, you should stop/deallocate all the existing VMs, and change the
sequence in the deployment script to begin with the VM SKU/sizes that failed.
When reusing an existing placement group from which VMs were deleted, wait for the deletion to fully
complete before adding VMs to it.
If latency is your first priority, put VMs in a proximity placement group and the entire solution in an availability
zone. But, if resiliency is your top priority, spread your instances across multiple availability zones (a single
proximity placement group cannot span zones).

Next steps
Deploy a VM to a proximity placement group using Azure PowerShell.
Learn how to test network latency.
Learn how to optimize network throughput.
Learn how to use proximity placement groups with SAP applications.
Optimize network throughput for Azure virtual
machines
1/6/2020 • 3 minutes to read • Edit Online

Azure virtual machines (VM ) have default network settings that can be further optimized for network
throughput. This article describes how to optimize network throughput for Microsoft Azure Windows and Linux
VMs, including major distributions such as Ubuntu, CentOS, and Red Hat.

Windows VM
If your Windows VM supports Accelerated Networking, enabling that feature would be the optimal
configuration for throughput. For all other Windows VMs, using Receive Side Scaling (RSS ) can reach higher
maximal throughput than a VM without RSS. RSS may be disabled by default in a Windows VM. To determine
whether RSS is enabled, and enable it if it's currently disabled, complete the following steps:
1. See if RSS is enabled for a network adapter with the Get-NetAdapterRss PowerShell command. In the
following example output returned from the Get-NetAdapterRss , RSS is not enabled.

Name : Ethernet
InterfaceDescription : Microsoft Hyper-V Network Adapter
Enabled : False

2. To enable RSS, enter the following command:

Get-NetAdapter | % {Enable-NetAdapterRss -Name $_.Name}

The previous command does not have an output. The command changed NIC settings, causing
temporary connectivity loss for about one minute. A Reconnecting dialog box appears during the
connectivity loss. Connectivity is typically restored after the third attempt.
3. Confirm that RSS is enabled in the VM by entering the Get-NetAdapterRss command again. If successful,
the following example output is returned:

Name : Ethernet
InterfaceDescription : Microsoft Hyper-V Network Adapter
Enabled : True

Linux VM
RSS is always enabled by default in an Azure Linux VM. Linux kernels released since October 2017 include new
network optimizations options that enable a Linux VM to achieve higher network throughput.
Ubuntu for new deployments
The Ubuntu Azure kernel provides the best network performance on Azure and has been the default kernel
since September 21, 2017. In order to get this kernel, first install the latest supported version of 16.04-LTS, as
follows:
"Publisher": "Canonical",
"Offer": "UbuntuServer",
"Sku": "16.04-LTS",
"Version": "latest"

After the creation is complete, enter the following commands to get the latest updates. These steps also work
for VMs currently running the Ubuntu Azure kernel.

#run as root or preface with sudo


apt-get -y update
apt-get -y upgrade
apt-get -y dist-upgrade

The following optional command set may be helpful for existing Ubuntu deployments that already have the
Azure kernel but that have failed to further updates with errors.

#optional steps may be helpful in existing deployments with the Azure kernel
#run as root or preface with sudo
apt-get -f install
apt-get --fix-missing install
apt-get clean
apt-get -y update
apt-get -y upgrade
apt-get -y dist-upgrade

Ubuntu Azure kernel upgrade for existing VMs


Significant throughput performance can be achieved by upgrading to the Azure Linux kernel. To verify whether
you have this kernel, check your kernel version.

#Azure kernel name ends with "-azure"


uname -r

#sample output on Azure kernel:


#4.13.0-1007-azure

If your VM does not have the Azure kernel, the version number usually begins with "4.4." If the VM does not
have the Azure kernel, run the following commands as root:

#run as root or preface with sudo


apt-get update
apt-get upgrade -y
apt-get dist-upgrade -y
apt-get install "linux-azure"
reboot

CentOS
In order to get the latest optimizations, it is best to create a VM with the latest supported version by specifying
the following parameters:

"Publisher": "OpenLogic",
"Offer": "CentOS",
"Sku": "7.4",
"Version": "latest"

New and existing VMs can benefit from installing the latest Linux Integration Services (LIS ). The throughput
optimization is in LIS, starting from 4.2.2-2, although later versions contain further improvements. Enter the
following commands to install the latest LIS:

sudo yum update


sudo reboot
sudo yum install microsoft-hyper-v

Red Hat
In order to get the optimizations, it is best to create a VM with the latest supported version by specifying the
following parameters:

"Publisher": "RedHat"
"Offer": "RHEL"
"Sku": "7-RAW"
"Version": "latest"

New and existing VMs can benefit from installing the latest Linux Integration Services (LIS ). The throughput
optimization is in LIS, starting from 4.2. Enter the following commands to download and install LIS:

wget https://aka.ms/lis
tar xvf lis
cd LISISO
sudo ./install.sh #or upgrade.sh if prior LIS was previously installed

Learn more about Linux Integration Services Version 4.2 for Hyper-V by viewing the download page.

Next steps
See the optimized result with Bandwidth/Throughput testing Azure VM for your scenario.
Read about how bandwidth is allocated to virtual machines
Learn more with Azure Virtual Network frequently asked questions (FAQ )
Sizes for Windows virtual machines in Azure
2/25/2020 • 2 minutes to read • Edit Online

This article describes the available sizes and options for the Azure virtual machines you can use to run your
Windows apps and workloads. It also provides deployment considerations to be aware of when you're planning
to use these resources. This article is also available for Linux virtual machines.

TYPE SIZES DESCRIPTION

General purpose B, Dsv3, Dv3, Dasv4, Dav4, DSv2, Dv2, Balanced CPU-to-memory ratio. Ideal
Av2, DC for testing and development, small to
medium databases, and low to
medium traffic web servers.

Compute optimized Fsv2 High CPU-to-memory ratio. Good for


medium traffic web servers, network
appliances, batch processes, and
application servers.

Memory optimized Esv3, Ev3, Easv4, Eav4, Mv2, M, DSv2, High memory-to-CPU ratio. Great for
Dv2 relational database servers, medium to
large caches, and in-memory analytics.

Storage optimized Lsv2 High disk throughput and IO ideal for


Big Data, SQL, NoSQL databases, data
warehousing and large transactional
databases.

GPU NC, NCv2, NCv3, ND, NDv2 (Preview), Specialized virtual machines targeted
NV, NVv3, NVv4 for heavy graphic rendering and video
editing, as well as model training and
inferencing (ND) with deep learning.
Available with single or multiple GPUs.

High performance compute HB, HC, H Our fastest and most powerful CPU
virtual machines with optional high-
throughput network interfaces
(RDMA).

For information about pricing of the various sizes, see Virtual Machines Pricing.
To see general limits on Azure VMs, see Azure subscription and service limits, quotas, and constraints.
Storage costs are calculated separately based on used pages in the storage account. For details, Azure
Storage Pricing.
Learn more about how Azure compute units (ACU ) can help you compare compute performance across
Azure SKUs.

REST API
For information on using the REST API to query for VM sizes, see the following:
List available virtual machine sizes for resizing
List available virtual machine sizes for a subscription
List available virtual machine sizes in an availability set

ACU
Learn more about how Azure compute units (ACU ) can help you compare compute performance across Azure
SKUs.

Benchmark scores
Learn more about compute performance for Windows VMs using the CoreMark benchmark scores.

Next steps
Learn more about the different VM sizes that are available:
General purpose
Compute optimized
Memory optimized
Storage optimized
GPU optimized
High performance compute
Check the Previous generation page for A Standard, Dv1 (D1-4 and D11-14 v1), and A8-A11 series
Support for generation 2 VMs on Azure
2/12/2020 • 6 minutes to read • Edit Online

Support for generation 2 virtual machines (VMs) is now available on Azure. You can't change a virtual machine's
generation after you've created it, so review the considerations on this page before you choose a generation.
Generation 2 VMs support key features that aren't supported in generation 1 VMs. These features include
increased memory, Intel Software Guard Extensions (Intel SGX), and virtualized persistent memory (vPMEM ).
Generation 2 VMs running on-premises, have some features that aren't supported in Azure yet. For more
information, see the Features and capabilities section.
Generation 2 VMs use the new UEFI-based boot architecture rather than the BIOS -based architecture used by
generation 1 VMs. Compared to generation 1 VMs, generation 2 VMs might have improved boot and installation
times. For an overview of generation 2 VMs and some of the differences between generation 1 and generation 2,
see Should I create a generation 1 or 2 virtual machine in Hyper-V?.

Generation 2 VM sizes
Generation 1 VMs are supported by all VM sizes in Azure (except for Mv2-series VMs). Azure now offers
generation 2 support for the following selected VM series:
B -series
DC -series
Dsv2-series and Dsv3-series
Esv3-series
Fsv2-series
GS -series
HB -series
HC -series
Ls-series and Lsv2-series
Mv2-series
NCv2-series and NCv3-series
ND -series
NVv3-series

NOTE
The usage of generation 2 VM images for Mv2-series VMs is generally available since the Mv2-series works with generation
2 VM images exclusively. Generation 1 VM images are not supported on Mv2-series VMs.

Generation 2 VM images in Azure Marketplace


Generation 2 VMs support the following Marketplace images:
Windows Server 2019, 2016, 2012 R2, 2012
Windows 10
SUSE Linux Enterprise Server 15 SP1
SUSE Linux Enterprise Server 12 SP4
Ubuntu Server 16.04, 18.04, 19.04, 19.10
RHEL 8.0, 7.6, 7.5, 7.4, 7.0
Cent OS 8.0

On-premises vs. Azure generation 2 VMs


Azure doesn't currently support some of the features that on-premises Hyper-V supports for generation 2 VMs.

GENERATION 2 FEATURE ON-PREMISES HYPER-V AZURE

Secure boot ✔

Shielded VM ✔

vTPM ✔

Virtualization-based security (VBS) ✔

VHDX format ✔

Features and capabilities


Generation 1 vs. generation 2 features
FEATURE GENERATION 1 GENERATION 2

Boot PCAT UEFI

Disk controllers IDE SCSI

VM sizes All VM sizes Only VMs that support premium


storage

Generation 1 vs. generation 2 capabilities


CAPABILITY GENERATION 1 GENERATION 2

OS disk > 2 TB ✔

Custom disk/image/swap OS ✔ ✔

Virtual machine scale set support ✔ ✔

Azure Site Recovery ✔ ✔

Backup/restore ✔ ✔

Shared image gallery ✔ ✔

Azure disk encryption ✔

Creating a generation 2 VM
Marketplace image
In the Azure portal or Azure CLI, you can create generation 2 VMs from a Marketplace image that supports UEFI
boot.
Azure portal
Below are the steps to create a generation 2 (Gen2) VM in Azure portal.
1. Sign in to the Azure portal at https://portal.azure.com.
2. Select Create a resource.
3. Click See all from the Azure Marketplace on the left.
4. Select an image which supports Gen2.
5. Click Create.
6. In the Advanced tab, under the VM generation section, select the Gen 2 option.
7. In the Basics tab, Under Instance details, go to Size and open the Select a VM size blade.
8. Select a supported generation 2 VM.
9. Go through the Azure portal creation flow to finish creating the VM.

PowerShell
You can also use PowerShell to create a VM by directly referencing the generation 1 or generation 2 SKU.
For example, use the following PowerShell cmdlet to get a list of the SKUs in the WindowsServer offer.

Get-AzVMImageSku -Location westus2 -PublisherName MicrosoftWindowsServer -Offer WindowsServer

Alternatively, you can use the Azure CLI to see any available generation 2 images, listed by Publisher.

az vm image list --publisher Canonical --sku gen2 --output table --all

If you're creating a VM with Windows Server 2012 as the OS, then you will select either the generation 1 (BIOS ) or
generation 2 (UEFI) VM SKU, which looks like this:

2012-Datacenter
2012-datacenter-gensecond

See the Features and capabilities section for a current list of supported Marketplace images.
Managed image or managed disk
You can create a generation 2 VM from a managed image or managed disk in the same way you would create a
generation 1 VM.
Virtual machine scale sets
You can also create generation 2 VMs by using virtual machine scale sets. In the Azure CLI, use Azure scale sets to
create generation 2 VMs.

Frequently asked questions


Are generation 2 VMs available in all Azure regions?
Yes. But not all generation 2 VM sizes are available in every region. The availability of the generation 2 VM
depends on the availability of the VM size.
Is there a price difference between generation 1 and generation 2 VMs?
No.
I have a .vhd file from my on-premises generation 2 VM. Can I use that .vhd file to create a
generation 2 VM in Azure? Yes, you can bring your generation 2 .vhd file to Azure and use that to create a
generation 2 VM. Use the following steps to do so:
1. Upload the .vhd to a storage account in the same region where you'd like to create your VM.
2. Create a managed disk from the .vhd file. Set the Hyper-V Generation property to V2. The following
PowerShell commands set Hyper-V Generation property when creating managed disk.

$sourceUri = 'https://xyzstorage.blob.core.windows.net/vhd/abcd.vhd'. #<Provide location to your


uploaded .vhd file>
$osDiskName = 'gen2Diskfrmgenvhd' #<Provide a name for your disk>
$diskconfig = New-AzDiskConfig -Location '<location>' -DiskSizeGB 127 -AccountType Standard_LRS -
OsType Windows -HyperVGeneration "V2" -SourceUri $sourceUri -CreateOption 'Import'
New-AzDisk -DiskName $osDiskName -ResourceGroupName '<Your Resource Group>' -Disk $diskconfig

3. Once the disk is available, create a VM by attaching this disk. The VM created will be a generation 2
VM. When the generation 2 VM is created, you can optionally generalize the image of this VM. By
generalizing the image, you can use it to create multiple VMs.
How do I increase the OS disk size?
OS disks larger than 2 TB are new to generation 2 VMs. By default, OS disks are smaller than 2 TB for
generation 2 VMs. You can increase the disk size up to a recommended maximum of 4 TB. Use the Azure
CLI or the Azure portal to increase the OS disk size. For information about how to expand disks
programmatically, see Resize a disk.
To increase the OS disk size from the Azure portal:
1. In the Azure portal, go to the VM properties page.
2. To shut down and deallocate the VM, select the Stop button.
3. In the Disks section, select the OS disk you want to increase.
4. In the Disks section, select Configuration, and update the Size to the value you want.
5. Go back to the VM properties page and Start the VM.
You might see a warning for OS disks larger than 2 TB. The warning doesn't apply to generation 2 VMs.
However, OS disk sizes larger than 4 TB are not recommended.
Do generation 2 VMs support accelerated networking?
Yes. For more information, see Create a VM with accelerated networking.
Is VHDX supported on generation 2?
No, generation 2 VMs support only VHD.
Do generation 2 VMs support Azure Ultra Disk Storage?
Yes.
Can I migrate a VM from generation 1 to generation 2?
No, you can't change the generation of a VM after you create it. If you need to switch between VM
generations, create a new VM of a different generation.
Why is my VM size not enabled in the size selector when I try to create a Gen2 VM?
This may be solved by doing the following:
1. Verify that the VM generation property is set to Gen 2 in the Advanced tab.
2. Verify you are searching for a VM size which supports Gen2 VMs.

Next steps
Learn about generation 2 virtual machines in Hyper-V.
Learn how to prepare a VHD to upload from on-premises systems to Azure.
General purpose virtual machine sizes
2/25/2020 • 2 minutes to read • Edit Online

General purpose VM sizes provide balanced CPU -to-memory ratio. Ideal for testing and development, small to
medium databases, and low to medium traffic web servers. This article provides information about the
offerings for general purpose computing.
The Av2-series VMs can be deployed on a variety of hardware types and processors. A-series VMs have
CPU performance and memory configurations best suited for entry level workloads like development
and test. The size is throttled, based upon the hardware, to offer consistent processor performance for
the running instance, regardless of the hardware it is deployed on. To determine the physical hardware
on which this size is deployed, query the virtual hardware from within the Virtual Machine. Example use
cases include development and test servers, low traffic web servers, small to medium databases, proof-
of-concepts, and code repositories.
B -series burstable VMs are ideal for workloads that do not need the full performance of the CPU
continuously, like web servers, small databases and development and test environments. These
workloads typically have burstable performance requirements. The B -Series provides these customers
the ability to purchase a VM size with a price conscious baseline performance that allows the VM
instance to build up credits when the VM is utilizing less than its base performance. When the VM has
accumulated credit, the VM can burst above the VM’s baseline using up to 100% of the CPU when your
application requires the higher CPU performance.
Dav4 and Dasv4-series are new sizes utilizing AMD’s 2.35Ghz EPYC TM 7452 processor in a multi-
threaded configuration with up to 256 MB L3 cache dedicating 8 GB of that L3 cache to every 8 cores
increasing customer options for running their general purpose workloads. The Dav4-series and Dasv4-
series have the same memory and disk configurations as the D & Dsv3-series.
The DCv2-series can help protect the confidentiality and integrity of your data and code while it’s
processed in the public cloud. These machines are backed by the latest generation of Intel XEON E -
2288G Processor with SGX technology. With the Intel Turbo Boost Technology these machines can go
up to 5.0GHz. DCv2 series instances enable customers to build secure enclave-based applications to
protect their code and data while it’s in use.
Dv2 and Dsv2-series VMs, a follow -on to the original D -series, features a more powerful CPU and
optimal CPU -to-memory configuration making them suitable for most production workloads. The Dv2-
series is about 35% faster than the D -series. Dv2-series runs on the Intel® Xeon® 8171M 2.1GHz
(Skylake), Intel® Xeon® E5-2673 v4 2.3 GHz (Broadwell), or the Intel® Xeon® E5-2673 v3 2.4 GHz
(Haswell) processors with the Intel Turbo Boost Technology 2.0. The Dv2-series has the same memory
and disk configurations as the D -series.
Dv3 and Dsv3-series VMs run on the Intel® Xeon® 8171M 2.1GHz (Skylake), Intel® Xeon® E5-2673
v4 2.3 GHz (Broadwell), or the Intel® Xeon® E5-2673 v3 2.4 GHz (Haswell) processors in a hyper-
threaded configuration, providing a better value proposition for most general purpose workloads.
Memory has been expanded (from ~3.5 GiB/vCPU to 4 GiB/vCPU ) while disk and network limits have
been adjusted on a per core basis to align with the move to hyperthreading. The Dv3-series no longer
has the high memory VM sizes of the D/Dv2-series, those have been moved to the memory optimized
Ev3 and Esv3-series.
Example D -series use cases include enterprise-grade applications, relational databases, in-memory caching,
and analytics.
Other sizes
Compute optimized
Memory optimized
Storage optimized
GPU optimized
High performance compute
Previous generations

Next steps
Learn more about how Azure compute units (ACU ) can help you compare compute performance across Azure
SKUs.
Av2-series
2/20/2020 • 2 minutes to read • Edit Online

The Av2-series VMs can be deployed on a variety of hardware types and processors. Av2-series VMs have CPU
performance and memory configurations best suited for entry level workloads like development and test. The size
is throttled to offer consistent processor performance for the running instance, regardless of the hardware it is
deployed on. To determine the physical hardware on which this size is deployed, query the virtual hardware from
within the Virtual Machine. Some example use cases include development and test servers, low traffic web
servers, small to medium databases, proof-of-concepts, and code repositories.
ACU: 100
Premium Storage: Not Supported
Premium Storage caching: Not Supported

MAX TEMP
STORAGE MAX
THROUGHPUT: NICS/EXPECTED
IOPS/READ MAX DATA NETWORK
TEMP STORAGE MBPS/WRITE DISKS/THROU BANDWIDTH
SIZE VCPU MEMORY: GIB (SSD) GIB MBPS GHPUT: IOPS (MBPS)

Standard_A1_ 1 2 10 1000/20/10 2/2x500 2/250


v2

Standard_A2_ 2 4 20 2000/40/20 4/4x500 2/500


v2

Standard_A4_ 4 8 40 4000/80/40 8/8x500 4/1000


v2

Standard_A8_ 8 16 80 8000/160/80 16/16x500 8/2000


v2

Standard_A2 2 16 20 2000/40/20 4/4x500 2/500


m_v2

Standard_A4 4 32 40 4000/80/40 8/8x500 4/1000


m_v2

Standard_A8 8 64 80 8000/160/80 16/16x500 8/2000


m_v2

Size table definitions


Storage capacity is shown in units of GiB or 1024^3 bytes. When you compare disks measured in GB
(1000^3 bytes) to disks measured in GiB (1024^3) remember that capacity numbers given in GiB may
appear smaller. For example, 1023 GiB = 1098.4 GB.
Disk throughput is measured in input/output operations per second (IOPS ) and MBps where MBps = 10^6
bytes/sec.
Data disks can operate in cached or uncached modes. For cached data disk operation, the host cache mode
is set to ReadOnly or ReadWrite. For uncached data disk operation, the host cache mode is set to None.
If you want to get the best performance for your VMs, you should limit the number of data disks to two
disks per vCPU.
Expected network bandwidth is the maximum aggregated bandwidth allocated per VM type across all
NICs, for all destinations. For more information, see Virtual machine network bandwidth.
Upper limits aren't guaranteed. Limits offer guidance for selecting the right VM type for the intended
application. Actual network performance will depend on several factors including network congestion,
application loads, and network settings. For information on optimizing network throughput, see Optimize
network throughput for Azure virtual machines. To achieve the expected network performance on Linux or
Windows, you may need to select a specific version or optimize your VM. For more information, see
Bandwidth/Throughput testing (NTTTCP ).

Other sizes
General purpose
Memory optimized
Storage optimized
GPU optimized
High performance compute
Previous generations

Next steps
Learn more about how Azure compute units (ACU ) can help you compare compute performance across Azure
SKUs.
B-series burstable virtual machine sizes
2/20/2020 • 6 minutes to read • Edit Online

The B -series VMs are ideal for workloads that do not need the full performance of the CPU continuously, like web
servers, proof of concepts, small databases and development build environments. These workloads typically have
burstable performance requirements. The B -series provides you with the ability to purchase a VM size with
baseline performance and the VM instance builds up credits when it is using less than its baseline. When the VM
has accumulated credit, the VM can burst above the baseline using up to 100% of the vCPU when your application
requires higher CPU performance.
The B -series comes in the following VM sizes:
Premium Storage: Supported
Premium Storage caching: Not Supported

MAX
CACH
ED
AND MAX
TEMP UNCA
STOR CHED
AGE DISK
TEMP BASE MAX CREDI MAX THRO THRO
STOR CPU CPU INITI TS BANK UGHP UGHP
MEM AGE PERF PERF AL BANK ED MAX UT: UT:
ORY: (SSD) OF OF CREDI ED/H CREDI DATA IOPS/ IOPS/ MAX
SIZE VCPU GIB GIB VM VM TS OUR TS DISKS MBPS MBPS NICS

Stand 1 0.5 4 5% 100% 30 3 72 2 200/ 160/ 2


ard_B 10 10
1ls1

Stand 1 1 4 10% 100% 30 6 144 2 400/ 320/ 2


ard_B 10 10
1s

Stand 1 2 4 20% 100% 30 12 288 2 800/ 640/ 2


ard_B 10 10
1ms

Stand 2 4 8 40% 200% 60 24 576 4 1600 1280 3


ard_B /15 /15
2s

Stand 2 8 16 60% 200% 60 36 864 4 2400 1920 3


ard_B /22.5 /22.5
2ms

Stand 4 16 32 90% 400% 120 54 1296 8 3600 2880 4


ard_B /35 /35
4ms

Stand 8 32 64 135% 800% 240 81 1944 16 4320 4320 4


ard_B /50 /50
8ms
MAX
CACH
ED
AND MAX
TEMP UNCA
STOR CHED
AGE DISK
TEMP BASE MAX CREDI MAX THRO THRO
STOR CPU CPU INITI TS BANK UGHP UGHP
MEM AGE PERF PERF AL BANK ED MAX UT: UT:
ORY: (SSD) OF OF CREDI ED/H CREDI DATA IOPS/ IOPS/ MAX
SIZE VCPU GIB GIB VM VM TS OUR TS DISKS MBPS MBPS NICS

Stand 12 48 96 202% 1200 360 121 2909 16 6480 4320 6


ard_B % /75 /50
12ms

Stand 16 64 128 270% 1600 480 162 3888 32 8640 4320 8


ard_B % /100 /50
16ms

Stand 20 80 160 337% 2000 600 203 4860 32 1080 4320 8


ard_B % 0/12 /50
20ms 5

1 B1ls is supported only on Linux

Workload example
Consider an office check-in/out application. The application needs CPU bursts during business hours, but not a lot
of computing power during off hours. In this example, the workload requires a 16vCPU virtual machine with
64GiB of RAM to work efficiently.
The table shows the hourly traffic data and the chart is a visual representation of that traffic.
B16 characteristics:
Max CPU perf: 16vCPU * 100% = 1600%
Baseline: 270%

CREDITS
SCENARIO TIME CPU USAGE (%) ACCUMULATED 1 CREDITS AVAILABLE

B16ms Deployment Deployment Deployment 480 (Initial Credits) 480

No traffic 0:00 0 162 642


CREDITS
SCENARIO TIME CPU USAGE (%) ACCUMULATED CREDITS AVAILABLE

No traffic 1:00 0 162 804

No traffic 2:00 0 162 966

No traffic 3:00 0 162 1128

No traffic 4:00 0 162 1290

No traffic 5:00 0 162 1452

Low Traffic 6:00 270 0 1452

Employees come to 7:00 1280 -606 846


office (app needs 80%
vCPU)

Employees continue 8:00 1280 -606 240


coming to office (app
needs 80% vCPU)

Low Traffic 9:00 270 0 240

Low Traffic 10:00 100 102 342

Low Traffic 11:00 50 132 474

Low Traffic 12:00 100 102 576

Low Traffic 13:00 100 102 678

Low Traffic 14:00 50 132 810

Low Traffic 15:00 100 102 912

Low Traffic 16:00 100 102 1014

Employees checking 17:00 1600 -798 216


out (app needs 100%
vCPU)

Low Traffic 18:00 270 0 216

Low Traffic 19:00 270 0 216

Low Traffic 20:00 50 132 348

Low Traffic 21:00 50 132 480

No traffic 22:00 0 162 642

No traffic 23:00 0 162 804


1
1 Credits accumulated/credits used in an hour is equivalent to:
((Base CPU perf of VM - CPU Usage) / 100) * 60 minutes .

For a D16s_v3 which has 16 vCPUs and 64 GiB of memory the hourly rate is $0.936 per hour (monthly $673.92)
and for B16ms with 16 vCPUs and 64 GiB memory the rate is $0.794 per hour (monthly $547.86). This results in
15% savings!

Q&A
Q: How do you get 135% baseline performance from a VM?
A: The 135% is shared amongst the 8 vCPU’s that make up the VM size. For example, if your application uses 4 of
the 8 cores working on batch processing and each of those 4 vCPU’s are running at 30% utilization the total
amount of VM CPU performance would equal 120%. Meaning that your VM would be building credit time based
on the 15% delta from your baseline performance. But it also means that when you have credits available that
same VM can use 100% of all 8 vCPU’s giving that VM a Max CPU performance of 800%.
Q: How can I monitor my credit balance and consumption
A: We will be introducing 2 new metrics in the coming weeks, the Credit metric will allow you to view how many
credits your VM has banked and the ConsumedCredit metric will show how many CPU credits your VM has
consumed from the bank. You will be able to view these metrics from the metrics pane in the portal or
programmatically through the Azure Monitor APIs.
For more information on how to access the metrics data for Azure, see Overview of metrics in Microsoft Azure.
Q: How are credits accumulated?
A: The VM accumulation and consumption rates are set such that a VM running at exactly its base performance
level will have neither a net accumulation or consumption of bursting credits. A VM will have a net increase in
credits whenever it is running below its base performance level and will have a net decrease in credits whenever
the VM is utilizing the CPU more than its base performance level.
Example: I deploy a VM using the B1ms size for my small time and attendance database application. This size
allows my application to use up to 20% of a vCPU as my baseline, which is 0.2 credits per minute I can use or
bank.
My application is busy at the beginning and end of my employees work day, between 7:00-9:00 AM and 4:00 -
6:00PM. During the other 20 hours of the day, my application is typically at idle, only using 10% of the vCPU. For
the non-peak hours, I earn 0.2 credits per minute but only consume 0.l credits per minute, so my VM will bank 0.1
x 60 = 6 credits per hour. For the 20 hours that I am off-peak, I will bank 120 credits.
During peak hours my application averages 60% vCPU utilization, I still earn 0.2 credits per minute but I consume
0.6 credits per minute, for a net cost of 0.4 credits a minute or 0.4 x 60 = 24 credits per hour. I have 4 hours per day
of peak usage, so it costs 4 x 24 = 96 credits for my peak usage.
If I take the 120 credits I earned off-peak and subtract the 96 credits I used for my peak times, I bank an additional
24 credits per day that I can use for other bursts of activity.
Q: How can I calculate credits accumulated and used?
A: You can use the following formula:
(Base CPU perf of VM - CPU Usage) / 100 = Credits bank or use per minute
e.g in above instance your baseline is 20% and if you use 10% of the CPU you are accumulating (20%-10%)/100 =
0.1 credit per minute.
Q: Does the B -Series support Premium Storage data disks?
A: Yes, all B -Series sizes support Premium Storage data disks.
Q: Why is my remaining credit set to 0 after a redeploy or a stop/start?
A : When a VM is “REDPLOYED” and the VM moves to another node, the accumulated credit is lost. If the VM is
stopped/started, but remains on the same node, the VM retains the accumulated credit. Whenever the VM starts
fresh on a node, it gets an initial credit, for Standard_B8ms it is 240 mins.
Q: What happens if I deploy an unsupported OS image on B1ls?
A : B1ls only supports Linux images and if you deploy any another OS image you might not get the best customer
experience.

Other sizes
General purpose
Compute optimized
Memory optimized
Storage optimized
GPU optimized
High performance compute

Next steps
Learn more about how Azure compute units (ACU ) can help you compare compute performance across Azure
SKUs.
Preview: DCv2-series
2/25/2020 • 2 minutes to read • Edit Online

The DCv2-series can help protect the confidentiality and integrity of your data and code while it’s processed in the
public cloud. These machines are backed by the latest generation of Intel XEON E -2288G Processor with SGX
technology. With the Intel Turbo Boost Technology these machines can go up to 5.0GHz. DCv2 series instances
enable customers to build secure enclave-based applications to protect their code and data while it’s in use.
Example use cases include confidential multiparty data sharing, fraud detection, anti-money laundering,
blockchain, confidential usage analytics, intelligence analysis and confidential machine learning.
Premium Storage: Supported*
Premium Storage caching: Supported*
*Except for Standard_DC8_v2

MAX
CACHED AND
TEMP
STORAGE MAX
THROUGHP UNCACHED MAX NICS /
UT: IOPS / DISK EXPECTED
TEMP MBPS THROUGHP NETWORK
MEMORY: STORAGE MAX DATA (CACHE SIZE UT: IOPS / BANDWIDTH
SIZE VCPU GIB (SSD) GIB DISKS IN GIB) MBPS (MBPS)

Standard_D 1 4 50 1 2000/16 1600/24 2


C1s_v2 (21)

Standard_D 2 8 100 2 4000/32 3200/48 2


C2s_v2 (43)

Standard_D 4 16 200 4 8000/64 6400/96 2


C4s_v2 (86)

Standard_D 8 32 400 8 16000/128 12800/192 2


C8_v2 (172)

DCv2-series VMs are generation 2 VMs and only support Gen2 images.

Other sizes
General purpose
Memory optimized
Storage optimized
GPU optimized
High performance compute
Previous generations

Next steps
Learn more about how Azure compute units (ACU ) can help you compare compute performance across Azure
SKUs.
Dv2 and DSv2-series
2/20/2020 • 2 minutes to read • Edit Online

The Dv2 and Dsv2-series, a follow -on to the original D -series, feature a more powerful CPU and optimal CPU -to-
memory configuration making them suitable for most production workloads. The Dv2-series is about 35% faster
than the D -series. Dv2-series runs on the Intel® Xeon® 8171M 2.1GHz (Skylake), Intel® Xeon® E5-2673 v4 2.3
GHz (Broadwell), or the Intel® Xeon® E5-2673 v3 2.4 GHz (Haswell) processors with the Intel Turbo Boost
Technology 2.0. The Dv2-series has the same memory and disk configurations as the D -series.

Dv2-series
Dv2-series sizes run on the Intel® Xeon® 8171M 2.1GHz (Skylake) or the the Intel® Xeon® E5-2673 v4 2.3 GHz
(Broadwell) or the Intel® Xeon® E5-2673 v3 2.4 GHz (Haswell) processors with Intel Turbo Boost Technology 2.0.
ACU: 210-250
Premium Storage: Not Supported
Premium Storage caching: Not Supported

MAX TEMP
STORAGE MAX
THROUGHP NICS/EXPECT
UT: ED
TEMP IOPS/READ NETWORK
MEMORY: STORAGE MBPS/WRIT MAX DATA THROUGHP BANDWIDTH
SIZE VCPU GIB (SSD) GIB E MBPS DISKS UT: IOPS (MBPS)

Standard_D 1 3.5 50 3000/46/23 4 4x500 2/750


1_v2

Standard_D 2 7 100 6000/93/46 8 8x500 2/1500


2_v2

Standard_D 4 14 200 12000/187/ 16 16x500 4/3000


3_v2 93

Standard_D 8 28 400 24000/375/ 32 32x500 8/6000


4_v2 187

Standard_D 16 56 800 48000/750/ 64 64x500 8/12000


5_v2 375

DSv2-series
DSv2-series sizes run on the Intel® Xeon® 8171M 2.1GHz (Skylake) or the the Intel® Xeon® E5-2673 v4 2.3
GHz (Broadwell) or the Intel® Xeon® E5-2673 v3 2.4 GHz (Haswell) processors with Intel Turbo Boost
Technology 2.0 and use premium storage.
ACU: 210-250
Premium Storage: Supported
Premium Storage caching: Supported
MAX
CACHED
AND TEMP
STORAGE MAX MAX
THROUGHP UNCACHED NICS/EXPECT
UT: DISK ED
TEMP IOPS/MBPS THROUGHP NETWORK
MEMORY: STORAGE MAX DATA (CACHE SIZE UT: BANDWIDTH
SIZE VCPU GIB (SSD) GIB DISKS IN GIB) IOPS/MBPS (MBPS)

Standard_D 1 3.5 7 4 4000/32 3200/48 2/750


S1_v2 (43)

Standard_D 2 7 14 8 8000/64 6400/96 2/1500


S2_v2 (86)

Standard_D 4 14 28 16 16000/128 12800/192 4/3000


S3_v2 (172)

Standard_D 8 28 56 32 32000/256 25600/384 8/6000


S4_v2 (344)

Standard_D 16 56 112 64 64000/512 51200/768 8/12000


S5_v2 (688)

Size table definitions


Storage capacity is shown in units of GiB or 1024^3 bytes. When you compare disks measured in GB
(1000^3 bytes) to disks measured in GiB (1024^3) remember that capacity numbers given in GiB may
appear smaller. For example, 1023 GiB = 1098.4 GB.
Disk throughput is measured in input/output operations per second (IOPS ) and MBps where MBps = 10^6
bytes/sec.
Data disks can operate in cached or uncached modes. For cached data disk operation, the host cache mode
is set to ReadOnly or ReadWrite. For uncached data disk operation, the host cache mode is set to None.
If you want to get the best performance for your VMs, you should limit the number of data disks to two
disks per vCPU.
Expected network bandwidth is the maximum aggregated bandwidth allocated per VM type across all
NICs, for all destinations. For more information, see Virtual machine network bandwidth.
Upper limits aren't guaranteed. Limits offer guidance for selecting the right VM type for the intended
application. Actual network performance will depend on several factors including network congestion,
application loads, and network settings. For information on optimizing network throughput, see Optimize
network throughput for Azure virtual machines. To achieve the expected network performance on Linux or
Windows, you may need to select a specific version or optimize your VM. For more information, see
Bandwidth/Throughput testing (NTTTCP ).

Other sizes
General purpose
Memory optimized
Storage optimized
GPU optimized
High performance compute
Previous generations

Next steps
Learn more about how Azure compute units (ACU ) can help you compare compute performance across Azure
SKUs.
Dv3 and Dsv3-series
2/20/2020 • 3 minutes to read • Edit Online

The Dv3-series runs on the Intel® Xeon® 8171M 2.1GHz (Skylake), Intel® Xeon® E5-2673 v4 2.3 GHz
(Broadwell), or the Intel® Xeon® E5-2673 v3 2.4 GHz (Haswell) processors in a hyper-threaded configuration,
providing a better value proposition for most general purpose workloads. Memory has been expanded (from ~3.5
GiB/vCPU to 4 GiB/vCPU ) while disk and network limits have been adjusted on a per core basis to align with the
move to hyperthreading. The Dv3-series no longer has the high memory VM sizes of the D/Dv2-series, those
have been moved to the memory optimized Ev3 and Esv3-series.
Example D -series use cases include enterprise-grade applications, relational databases, in-memory caching, and
analytics.

Dv3-series
Dv3-series sizes run on the Intel® Xeon® 8171M 2.1GHz (Skylake), Intel® Xeon® E5-2673 v4 2.3 GHz
(Broadwell), or the Intel® Xeon® E5-2673 v3 2.4 GHz (Haswell) processors with Intel Turbo Boost Technology
2.0. The Dv3-series sizes offer a combination of vCPU, memory, and temporary storage for most production
workloads.
Data disk storage is billed separately from virtual machines. To use premium storage disks, use the Dsv3 sizes.
The pricing and billing meters for Dsv3 sizes are the same as Dv3-series.
Dv3-series VMs feature Intel® Hyper-Threading Technology.
ACU: 160-190
Premium Storage: Not Supported
Premium Storage caching: Not Supported

MAX TEMP
STORAGE
THROUGHPUT:
IOPS/READ MAX
TEMP STORAGE MAX DATA MBPS/WRITE NICS/NETWOR
SIZE VCPU MEMORY: GIB (SSD) GIB DISKS MBPS K BANDWIDTH

Standard_D2_ 2 8 50 4 3000/46/23 2/1000


v3

Standard_D4_ 4 16 100 8 6000/93/46 2/2000


v3

Standard_D8_ 8 32 200 16 12000/187/9 4/4000


v3 3

Standard_D16 16 64 400 32 24000/375/1 8/8000


_v3 87

Standard_D32 32 128 800 32 48000/750/3 8/16000


_v3 75
MAX TEMP
STORAGE
THROUGHPUT:
IOPS/READ MAX
TEMP STORAGE MAX DATA MBPS/WRITE NICS/NETWOR
SIZE VCPU MEMORY: GIB (SSD) GIB DISKS MBPS K BANDWIDTH

Standard_D48 48 192 1200 32 96000/1000/ 8/24000


_v3 500

Standard_D64 64 256 1600 32 96000/1000/ 8/30000


_v3 500

Dsv3-series
Dsv3-series sizes run on the Intel® Xeon® 8171M 2.1GHz (Skylake), Intel® Xeon® E5-2673 v4 2.3 GHz
(Broadwell), or the Intel® Xeon® E5-2673 v3 2.4 GHz (Haswell) processors with Intel Turbo Boost Technology
2.0 and use premium storage. The Dsv3-series sizes offer a combination of vCPU, memory, and temporary
storage for most production workloads.
Dsv3-series VMs feature Intel® Hyper-Threading Technology.
ACU: 160-190
Premium Storage: Supported
Premium Storage caching: Supported

MAX
CACHED
AND TEMP
STORAGE MAX MAX
THROUGHP UNCACHED NICS/EXPECT
UT: DISK ED
TEMP IOPS/MBPS THROUGHP NETWORK
MEMORY: STORAGE MAX DATA (CACHE SIZE UT: BANDWIDT
SIZE VCPU GIB (SSD) GIB DISKS IN GIB) IOPS/MBPS H (MBPS)

Standard_D 2 8 16 4 4000/32 3200/48 2/1000


2s_v3 (50)

Standard_D 4 16 32 8 8000/64 6400/96 2/2000


4s_v3 (100)

Standard_D 8 32 64 16 16000/128 12800/192 4/4000


8s_v3 (200)

Standard_D 16 64 128 32 32000/256 25600/384 8/8000


16s_v3 (400)

Standard_D 32 128 256 32 64000/512 51200/768 8/16000


32s_v3 (800)

Standard_D 48 192 384 32 96000/768 76800/115 8/24000


48s_v3 (1200) 2

Standard_D 64 256 512 32 128000/10 80000/120 8/30000


64s_v3 24 (1600) 0
Size table definitions
Storage capacity is shown in units of GiB or 1024^3 bytes. When you compare disks measured in GB
(1000^3 bytes) to disks measured in GiB (1024^3) remember that capacity numbers given in GiB may
appear smaller. For example, 1023 GiB = 1098.4 GB.
Disk throughput is measured in input/output operations per second (IOPS ) and MBps where MBps =
10^6 bytes/sec.
Data disks can operate in cached or uncached modes. For cached data disk operation, the host cache mode
is set to ReadOnly or ReadWrite. For uncached data disk operation, the host cache mode is set to None.
If you want to get the best performance for your VMs, you should limit the number of data disks to two
disks per vCPU.
Expected network bandwidth is the maximum aggregated bandwidth allocated per VM type across all
NICs, for all destinations. For more information, see Virtual machine network bandwidth.
Upper limits aren't guaranteed. Limits offer guidance for selecting the right VM type for the intended
application. Actual network performance will depend on several factors including network congestion,
application loads, and network settings. For information on optimizing network throughput, see Optimize
network throughput for Azure virtual machines. To achieve the expected network performance on Linux or
Windows, you may need to select a specific version or optimize your VM. For more information, see
Bandwidth/Throughput testing (NTTTCP ).

Other sizes
General purpose
Memory optimized
Storage optimized
GPU optimized
High performance compute
Previous generations

Next steps
Learn more about how Azure compute units (ACU ) can help you compare compute performance across Azure
SKUs.
Dav4 and Dasv4-series
2/20/2020 • 3 minutes to read • Edit Online

The Dav4-series and Dasv4-series are new sizes utilizing AMD’s 2.35Ghz EPYC TM 7452 processor in a multi-
threaded configuration with up to 256 MB L3 cache dedicating 8 GB of that L3 cache to every 8 cores increasing
customer options for running their general purpose workloads. The Dav4-series and Dasv4-series have the same
memory and disk configurations as the D & Dsv3-series.

Dav4-series
ACU: 230-260
Premium Storage: Not Supported
Premium Storage caching: Not Supported
Dav4-series sizes are based on the 2.35Ghz AMD EPYC TM 7452 processor that can achieve a boosted maximum
frequency of 3.35GHz. The Dav4-series sizes offer a combination of vCPU, memory and temporary storage for
most production workloads. Data disk storage is billed separately from virtual machines. To use premium SSD, use
the Dasv4 sizes. The pricing and billing meters for Dasv4 sizes are the same as the Dav4-series.

MAX TEMP
STORAGE MAX NICS /
THROUGHPUT: EXPECTED
IOPS / READ NETWORK
TEMP STORAGE MAX DATA MBPS / WRITE BANDWIDTH
SIZE VCPU MEMORY: GIB (SSD) GIB DISKS MBPS (MBPS)

Standard_D2a 2 8 50 4 3000 / 46 / 2 / 1000


_v4 23

Standard_D4a 4 16 100 8 6000 / 93 / 2 / 2000


_v4 46

Standard_D8a 8 32 200 16 12000 / 187 / 4 / 4000


_v4 93

Standard_D16 16 64 400 32 24000 / 375 / 8 / 8000


a_v4 187

Standard_D32 32 128 800 32 48000 / 750 / 8 / 16000


a_v4 375

Standard_D48 48 192 1200 32


a_v4 **

Standard_D64 64 256 1600 32


a_v4 **

Standard_D96 96 384 2400 32


a_v4 **

**These sizes are in Preview. If you are interested in trying out these larger sizes, sign up at
https://aka.ms/AzureAMDLargeVMPreview.
Dasv4-series
ACU: 230-260
Premium Storage: Supported
Premium Storage caching: Supported
Dasv4-series sizes are based on the 2.35Ghz AMD EPYC TM 7452 processor that can achieve a boosted maximum
frequency of 3.35GHz and use premium SSD. The Dasv4-series sizes offer a combination of vCPU, memory and
temporary storage for most production workloads.

MAX
CACHED AND
TEMP
STORAGE MAX
THROUGHP UNCACHED MAX NICS /
UT: IOPS / DISK EXPECTED
TEMP MBPS THROUGHP NETWORK
MEMORY: STORAGE MAX DATA (CACHE SIZE UT: IOPS / BANDWIDTH
SIZE VCPU GIB (SSD) GIB DISKS IN GIB) MBPS (MBPS)

Standard_D 2 8 16 4 4000 / 32 3200 / 48 2 / 1000


2as_v4 (50)

Standard_D 4 16 32 8 8000 / 64 6400 / 96 2 / 2000


4as_v4 (100)

Standard_D 8 32 64 16 16000 / 12800 / 4 / 4000


8as_v4 128 (200) 192

Standard_D 16 64 128 32 32000 / 25600 / 8 / 8000


16as_v4 255 (400) 384

Standard_D 32 128 256 32 64000 / 51200 / 8 / 16000


32as_v4 510 (800) 768

Standard_D 48 192 384 32


48as_v4 **

Standard_D 64 256 512 32


64as_v4 **

Standard_D 96 384 768 32


96as_v4 **

**These sizes are in Preview. If you are interested in trying out these larger sizes, sign up at
https://aka.ms/AzureAMDLargeVMPreview.

Size table definitions


Storage capacity is shown in units of GiB or 1024^3 bytes. When you compare disks measured in GB
(1000^3 bytes) to disks measured in GiB (1024^3) remember that capacity numbers given in GiB may
appear smaller. For example, 1023 GiB = 1098.4 GB.
Disk throughput is measured in input/output operations per second (IOPS ) and MBps where MBps = 10^6
bytes/sec.
Data disks can operate in cached or uncached modes. For cached data disk operation, the host cache mode
is set to ReadOnly or ReadWrite. For uncached data disk operation, the host cache mode is set to None.
If you want to get the best performance for your VMs, you should limit the number of data disks to two
disks per vCPU.
Expected network bandwidth is the maximum aggregated bandwidth allocated per VM type across all
NICs, for all destinations. For more information, see Virtual machine network bandwidth.
Upper limits aren't guaranteed. Limits offer guidance for selecting the right VM type for the intended
application. Actual network performance will depend on several factors including network congestion,
application loads, and network settings. For information on optimizing network throughput, see Optimize
network throughput for Azure virtual machines. To achieve the expected network performance on Linux or
Windows, you may need to select a specific version or optimize your VM. For more information, see
Bandwidth/Throughput testing (NTTTCP ).

Other sizes
General purpose
Memory optimized
Storage optimized
GPU optimized
High performance compute
Previous generations

Next steps
Learn more about how Azure compute units (ACU ) can help you compare compute performance across Azure
SKUs.
Compute optimized virtual machine sizes
2/20/2020 • 2 minutes to read • Edit Online

Compute optimized VM sizes have a high CPU -to-memory ratio. These sizes are good for medium traffic web
servers, network appliances, batch processes, and application servers. This article provides information about the
number of vCPUs, data disks, and NICs. It also includes information about storage throughput and network
bandwidth for each size in this grouping.
The Fsv2-series is based on the Intel® Xeon® Platinum 8168 processor. It features a sustained all core Turbo
clock speed of 3.4 GHz and a maximum single-core turbo frequency of 3.7 GHz. Intel® AVX-512 instructions are
new on Intel Scalable Processors. These instructions provide up to a 2X performance boost to vector processing
workloads on both single and double precision floating point operations. In other words, they're really fast for any
computational workload.
At a lower per-hour list price, the Fsv2-series is the best value in price-performance in the Azure portfolio based
on the Azure Compute Unit (ACU ) per vCPU.

Other sizes
General purpose
Memory optimized
Storage optimized
GPU optimized
High performance compute
Previous generations

Next steps
Learn more about how Azure compute units (ACU ) can help you compare compute performance across Azure
SKUs.
Fsv2-series
2/20/2020 • 2 minutes to read • Edit Online

The Fsv2-series is based on the Intel® Xeon® Platinum 8168 processor. It features a sustained all core Turbo
clock speed of 3.4 GHz and a maximum single-core turbo frequency of 3.7 GHz. Intel® AVX-512 instructions are
new on Intel Scalable Processors. These instructions provide up to a 2X performance boost to vector processing
workloads on both single and double precision floating point operations. In other words, they're really fast for any
computational workload.
Fsv2-series VMs feature Intel® Hyper-Threading Technology.
ACU: 195 - 210
Premium Storage: Supported
Premium Storage caching: Supported

MAX
CACHED AND
TEMP
STORAGE MAX MAX
THROUGHP UNCACHED NICS/EXPECT
UT: DISK ED
TEMP IOPS/MBPS THROUGHP NETWORK
MEMORY: STORAGE MAX DATA (CACHE SIZE UT: BANDWIDTH
SIZE VCPU'S GIB (SSD) GIB DISKS IN GIB) IOPS/MBPS (MBPS)

Standard_F 2 4 16 4 4000/31 3200/47 2/875


2s_v2 (32)

Standard_F 4 8 32 8 8000/63 6400/95 2/1750


4s_v2 (64)

Standard_F 8 16 64 16 16000/127 12800/190 4/3500


8s_v2 (128)

Standard_F 16 32 128 32 32000/255 25600/380 4/7000


16s_v2 (256)

Standard_F 32 64 256 32 64000/512 51200/750 8/14000


32s_v2 (512)

Standard_F 48 96 384 32 96000/768 76800/110 8/21000


48s_v2 (768) 0

Standard_F 64 128 512 32 128000/10 80000/110 8/28000


64s_v2 24 (1024) 0

Standard_F 72 144 576 32 144000/11 80000/110 8/30000


72s_v21, 2 52 (1520) 0

1 The use of more than 64 vCPU require one of these supported guest operating systems:
Windows Server 2016 or later
Ubuntu 16.04 LTS or later, with Azure tuned kernel (4.15 kernel or later)
SLES 12 SP2 or later
RHEL or CentOS version 6.7 through 6.10, with Microsoft-provided LIS package 4.3.1 (or later) installed
RHEL or CentOS version 7.3, with Microsoft-provided LIS package 4.2.1 (or later) installed
RHEL or CentOS version 7.6 or later
Oracle Linux with UEK4 or later
Debian 9 with the backports kernel, Debian 10 or later
CoreOS with a 4.14 kernel or later
2 Instance is isolated to hardware dedicated to a single customer.

Size table definitions


Storage capacity is shown in units of GiB or 1024^3 bytes. When you compare disks measured in GB
(1000^3 bytes) to disks measured in GiB (1024^3) remember that capacity numbers given in GiB may
appear smaller. For example, 1023 GiB = 1098.4 GB.
Disk throughput is measured in input/output operations per second (IOPS ) and MBps where MBps = 10^6
bytes/sec.
Data disks can operate in cached or uncached modes. For cached data disk operation, the host cache mode
is set to ReadOnly or ReadWrite. For uncached data disk operation, the host cache mode is set to None.
If you want to get the best performance for your VMs, you should limit the number of data disks to two
disks per vCPU.
Expected network bandwidth is the maximum aggregated bandwidth allocated per VM type across all
NICs, for all destinations. For more information, see Virtual machine network bandwidth.
Upper limits aren't guaranteed. Limits offer guidance for selecting the right VM type for the intended
application. Actual network performance will depend on several factors including network congestion,
application loads, and network settings. For information on optimizing network throughput, see Optimize
network throughput for Azure virtual machines. To achieve the expected network performance on Linux or
Windows, you may need to select a specific version or optimize your VM. For more information, see
Bandwidth/Throughput testing (NTTTCP ).

Other sizes
General purpose
Memory optimized
Storage optimized
GPU optimized
High performance compute
Previous generations

Next steps
Learn more about how Azure compute units (ACU ) can help you compare compute performance across Azure
SKUs.
Memory optimized virtual machine sizes
2/20/2020 • 2 minutes to read • Edit Online

Memory optimized VM sizes offer a high memory-to-CPU ratio that are great for relational database servers,
medium to large caches, and in-memory analytics. This article provides information about the number of
vCPUs, data disks and NICs as well as storage throughput and network bandwidth for each size in this
grouping.
Dv2 and DSv2-series, a follow -on to the original D -series, features a more powerful CPU. The Dv2-
series is about 35% faster than the D -series. It runs on the Intel® Xeon® 8171M 2.1 GHz (Skylake) or
the Intel® Xeon® E5-2673 v4 2.3 GHz (Broadwell) or the Intel® Xeon® E5-2673 v3 2.4 GHz
(Haswell) processors, and with the Intel Turbo Boost Technology 2.0. The Dv2-series has the same
memory and disk configurations as the D -series.
Dv2 and DSv2-series are ideal for applications that demand faster vCPUs, better temporary storage
performance, or have higher memory demands. They offer a powerful combination for many
enterprise-grade applications.
The Eav4 and Easv4-series utilize AMD’s 2.35Ghz EPYC TM 7452 processor in a multi-threaded
configuration with up to 256MB L3 cache, increasing options for running most memory optimized
workloads. The Eav4-series and Easv4-series have the same memory and disk configurations as the
Ev3 & Esv3-series.
The Ev3 and Esv3-series Intel® Xeon® 8171M 2.1 GHz (Skylake) or the Intel® Xeon® E5-2673 v4 2.3
GHz (Broadwell) processor in a hyper-threaded configuration, providing a better value proposition for
most general purpose workloads, and bringing the Ev3 into alignment with the general purpose VMs
of most other clouds. Memory has been expanded (from 7 GiB/vCPU to 8 GiB/vCPU ) while disk and
network limits have been adjusted on a per core basis to align with the move to hyper-threading. The
Ev3 is the follow up to the high memory VM sizes of the D/Dv2 families.
The M -series offers a high vCPU count (up to 128 vCPUs) and a large amount of memory (up to 3.8
TiB ). It’s also ideal for extremely large databases or other applications that benefit from high vCPU
counts and large amounts of memory.
The Mv2-series offers the highest vCPU count (up to 416 vCPUs) and largest memory (up to 8.19 TiB )
of any VM in the cloud. It’s ideal for extremely large databases or other applications that benefit from
high vCPU counts and large amounts of memory.
Azure Compute offers virtual machine sizes that are Isolated to a specific hardware type and dedicated to a
single customer. These virtual machine sizes are best suited for workloads that require a high degree of
isolation from other customers for workloads involving elements like compliance and regulatory
requirements. Customers can also choose to further subdivide the resources of these Isolated virtual
machines by using Azure support for nested virtual machines . See the pages for virtual machine families
below for your isolated VM options.

Other sizes
General purpose
Compute optimized
Storage optimized
GPU optimized
High performance compute
Previous generations

Next steps
Learn more about how Azure compute units (ACU ) can help you compare compute performance across
Azure SKUs.
Memory optimized Dv2 and Dsv2-series
2/20/2020 • 3 minutes to read • Edit Online

Dv2 and Dsv2-series, a follow -on to the original D -series, features a more powerful CPU. DSv2-series sizes run on
the Intel® Xeon® 8171M 2.1 GHz (Skylake) or the Intel® Xeon® E5-2673 v4 2.3 GHz (Broadwell) or the Intel®
Xeon® E5-2673 v3 2.4 GHz (Haswell) processors. The Dv2-series has the same memory and disk configurations
as the D -series.

Dv2-series 11-15
Dv2-series sizes run on the Intel® Xeon® 8171M 2.1 GHz (Skylake) or the Intel® Xeon® E5-2673 v4 2.3 GHz
(Broadwell) or the Intel® Xeon® E5-2673 v3 2.4 GHz (Haswell) processors.
ACU: 210 - 250
Premium Storage: Not Supported
Premium Storage caching: Not Supported

MAX TEMP
STORAGE MAX
THROUGHPUT: NICS/EXPECTED
IOPS/READ MAX DATA NETWORK
TEMP STORAGE MBPS/WRITE DISKS/THROU BANDWIDTH
SIZE VCPU MEMORY: GIB (SSD) GIB MBPS GHPUT: IOPS (MBPS)

Standard_D11 2 14 100 6000/93/46 8/8x500 2/1500


_v2

Standard_D12 4 28 200 12000/187/9 16/16x500 4/3000


_v2 3

Standard_D13 8 56 400 24000/375/1 32/32x500 8/6000


_v2 87

Standard_D14 16 112 800 48000/750/3 64/64x500 8/12000


_v2 75

Standard_D15 20 140 1000 60000/937/4 64/64x500 8/25000 2


_v2 1 68

1 Instance is isolated to hardware dedicated to a single customer. 2 25000 Mbps with Accelerated Networking.

DSv2-series 11-15
DSv2-series sizes run on the Intel® Xeon® 8171M 2.1 GHz (Skylake) or the Intel® Xeon® E5-2673 v4 2.3 GHz
(Broadwell) or the Intel® Xeon® E5-2673 v3 2.4 GHz (Haswell) processors.
ACU: 210 - 250 1
Premium Storage: Supported
Premium Storage caching: Supported
MAX
CACHED AND
TEMP
STORAGE MAX MAX
THROUGHP UNCACHED NICS/EXPECT
UT: DISK ED
TEMP IOPS/MBPS THROUGHP NETWORK
(CACHE SIZE
MEMORY: STORAGE MAX DATA UT: BANDWIDTH
SIZE VCPU GIB (SSD) GIB DISKS IN GIB) IOPS/MBPS (MBPS)

Standard_D 2 14 28 8 8000/64 6400/96 2/1500


S11_v2 3 (72)

Standard_D 4 28 56 16 16000/128 12800/192 4/3000


S12_v2 3 (144)

Standard_D 8 56 112 32 32000/256 25600/384 8/6000


S13_v2 3 (288)

Standard_D 16 112 224 64 64000/512 51200/768 8/12000


S14_v2 3 (576)

Standard_D 20 140 280 64 80000/640 64000/960 8/25000 4


S15_v2 2 (720)

1 The maximum disk throughput (IOPS or MBps) possible with a DSv2 series VM may be limited by the number,
size and striping of the attached disk(s). For details, see Designing for high performance. 2 Instance is isolated to
the Intel Haswell based hardware and dedicated to a single customer.
3 Constrained core sizes available.
4 25000 Mbps with Accelerated Networking.

Size table definitions


Storage capacity is shown in units of GiB or 1024^3 bytes. When you compare disks measured in GB
(1000^3 bytes) to disks measured in GiB (1024^3) remember that capacity numbers given in GiB may
appear smaller. For example, 1023 GiB = 1098.4 GB.
Disk throughput is measured in input/output operations per second (IOPS ) and MBps where MBps = 10^6
bytes/sec.
Data disks can operate in cached or uncached modes. For cached data disk operation, the host cache mode
is set to ReadOnly or ReadWrite. For uncached data disk operation, the host cache mode is set to None.
If you want to get the best performance for your VMs, you should limit the number of data disks to two
disks per vCPU.
Expected network bandwidth is the maximum aggregated bandwidth allocated per VM type across all
NICs, for all destinations. For more information, see Virtual machine network bandwidth.
Upper limits aren't guaranteed. Limits offer guidance for selecting the right VM type for the intended
application. Actual network performance will depend on several factors including network congestion,
application loads, and network settings. For information on optimizing network throughput, see Optimize
network throughput for Azure virtual machines. To achieve the expected network performance on Linux or
Windows, you may need to select a specific version or optimize your VM. For more information, see
Bandwidth/Throughput testing (NTTTCP ).

Other sizes
General purpose
Memory optimized
Storage optimized
GPU optimized
High performance compute
Previous generations

Next steps
Learn more about how Azure compute units (ACU ) can help you compare compute performance across Azure
SKUs.
Ev3 and Esv3-series
2/20/2020 • 3 minutes to read • Edit Online

The Ev3 and Esv3-series feature the Intel® Xeon® 8171M 2.1 GHz (Skylake) or the Intel® Xeon® E5-2673 v4
2.3 GHz (Broadwell) processor in a hyper-threaded configuration, providing a better value proposition for most
general purpose workloads, and bringing the Ev3 into alignment with the general purpose VMs of most other
clouds. Memory has been expanded (from 7 GiB/vCPU to 8 GiB/vCPU ) while disk and network limits have been
adjusted on a per core basis to align with the move to hyperthreading. The Ev3 is the follow up to the high
memory VM sizes of the D/Dv2 families.

Ev3-series
Ev3-series instances are based on feature the Intel® Xeon® 8171M 2.1 GHz (Skylake) or the Intel® Xeon® E5-
2673 v4 2.3 GHz (Broadwell) processor and Intel Turbo Boost Technology 2.0. Ev3-series instances are ideal for
memory-intensive enterprise applications.
Data disk storage is billed separately from virtual machines. To use premium storage disks, use the ESv3 sizes. The
pricing and billing meters for ESv3 sizes are the same as Ev3-series.
Ev3-series VM’s feature Intel® Hyper-Threading Technology.
ACU: 160 - 190
Premium Storage: Not Supported
Premium Storage caching: Not Supported

MAX TEMP
STORAGE
THROUGHPUT:
IOPS / READ MAX NICS /
TEMP STORAGE MAX DATA MBPS / WRITE NETWORK
SIZE VCPU MEMORY: GIB (SSD) GIB DISKS MBPS BANDWIDTH

Standard_E2_ 2 16 50 4 3000/46/23 2/1000


v3

Standard_E4_ 4 32 100 8 6000/93/46 2/2000


v3

Standard_E8_ 8 64 200 16 12000/187/9 4/4000


v3 3

Standard_E16 16 128 400 32 24000/375/1 8/8000


_v3 87

Standard_E20 20 160 500 32 30000/469/2 8/10000


_v3 34

Standard_E32 32 256 800 32 48000/750/3 8/16000


_v3 75

Standard_E48 48 384 1200 32 96000/1000/ 8/24000


_v3 500
MAX TEMP
STORAGE
THROUGHPUT:
IOPS / READ MAX NICS /
TEMP STORAGE MAX DATA MBPS / WRITE NETWORK
SIZE VCPU MEMORY: GIB (SSD) GIB DISKS MBPS BANDWIDTH

Standard_E64 64 432 1600 32 96000/1000/ 8/30000


_v3 500

Standard_E64i 64 432 1600 32 96000/1000/ 8/30000


_v3 1,2 500

1 Constrained core sizes available.

2 Instance is isolated to hardware dedicated to a single customer.

Esv3-series
Esv3-series instances are based on feature the Intel® Xeon® 8171M 2.1 GHz (Skylake) or the Intel® Xeon® E5-
2673 v4 2.3 GHz (Broadwell) processor, Intel Turbo Boost Technology 2.0, and use premium storage. Esv3-series
instances are ideal for memory-intensive enterprise applications.
Esv3-series VM’s feature Intel® Hyper-Threading Technology.
ACU: 160-190
Premium Storage: Supported
Premium Storage caching: Supported

MAX
CACHED
AND TEMP
STORAGE MAX MAX
THROUGHP UNCACHED NICS/EXPECT
UT: DISK ED
TEMP IOPS/MBPS THROUGHP NETWORK
MEMORY: STORAGE MAX DATA (CACHE SIZE UT: BANDWIDT
SIZE VCPU GIB (SSD) GIB DISKS IN GIB) IOPS/MBPS H (MBPS)

Standard_E 2 16 32 4 4000/32 3200/48 2/1000


2s_v3 (50)

Standard_E 4 32 64 8 8000/64 6400/96 2/2000


4s_v3 1 (100)

Standard_E 8 64 128 16 16000/128 12800/192 4/4000


8s_v3 1 (200)

Standard_E 16 128 256 32 32000/256 25600/384 8/8000


16s_v3 1 (400)

Standard_E 20 160 320 32 40000/320 32000/480 8/10000


20s_v3 (400)

Standard_E 32 256 512 32 64000/512 51200/768 8/16000


32s_v3 1 (800)

Standard_E 48 384 768 32 96000/768 76800/115 8/24000


48s_v3 1 (1200) 2
MAX
CACHED
AND TEMP
STORAGE MAX MAX
THROUGHP UNCACHED NICS/EXPECT
UT: DISK ED
TEMP IOPS/MBPS THROUGHP NETWORK
MEMORY: STORAGE MAX DATA (CACHE SIZE UT: BANDWIDT
SIZE VCPU GIB (SSD) GIB DISKS IN GIB) IOPS/MBPS H (MBPS)

Standard_E 64 432 864 32 128000/10 80000/120 8/30000


64s_v3 1 24 (1600) 0

Standard_E 64 432 864 32 128000/10 80000/120 8/30000


64is_v3 2 24 (1600) 0

1 Constrained core sizes available.

2 Instance is isolated to hardware dedicated to a single customer.

Size table definitions


Storage capacity is shown in units of GiB or 1024^3 bytes. When you compare disks measured in GB
(1000^3 bytes) to disks measured in GiB (1024^3) remember that capacity numbers given in GiB may
appear smaller. For example, 1023 GiB = 1098.4 GB.
Disk throughput is measured in input/output operations per second (IOPS ) and MBps where MBps =
10^6 bytes/sec.
Data disks can operate in cached or uncached modes. For cached data disk operation, the host cache mode
is set to ReadOnly or ReadWrite. For uncached data disk operation, the host cache mode is set to None.
If you want to get the best performance for your VMs, you should limit the number of data disks to two
disks per vCPU.
Expected network bandwidth is the maximum aggregated bandwidth allocated per VM type across all
NICs, for all destinations. For more information, see Virtual machine network bandwidth.
Upper limits aren't guaranteed. Limits offer guidance for selecting the right VM type for the intended
application. Actual network performance will depend on several factors including network congestion,
application loads, and network settings. For information on optimizing network throughput, see Optimize
network throughput for Azure virtual machines. To achieve the expected network performance on Linux or
Windows, you may need to select a specific version or optimize your VM. For more information, see
Bandwidth/Throughput testing (NTTTCP ).

Other sizes
General purpose
Memory optimized
Storage optimized
GPU optimized
High performance compute
Previous generations
Next steps
Learn more about how Azure compute units (ACU ) can help you compare compute performance across Azure
SKUs.
Eav4 and Easv4-series
2/20/2020 • 3 minutes to read • Edit Online

The Eav4-series and Easv4-series utilize AMD’s 2.35Ghz EPYC TM 7452 processor in a multi-threaded
configuration with up to 256MB L3 cache, increasing options for running most memory optimized workloads. The
Eav4-series and Easv4-series have the same memory and disk configurations as the Ev3 & Esv3-series.

Eav4-series
ACU: 230 - 260
Premium Storage: Not Supported
Premium Storage caching: Not Supported
Eav4-series sizes are based on the 2.35Ghz AMD EPYC TM 7452 processor that can achieve a boosted maximum
frequency of 3.35GHz and use premium SSD. The Eav4-series sizes are ideal for memory-intensive enterprise
applications. Data disk storage is billed separately from virtual machines. To use premium SSD, use the Easv4-
series sizes. The pricing and billing meters for Easv4 sizes are the same as the Eav3-series.

MAX TEMP
STORAGE MAX NICS /
THROUGHPUT: EXPECTED
IOPS / READ NETWORK
TEMP STORAGE MAX DATA MBPS / WRITE BANDWIDTH
SIZE VCPU MEMORY: GIB (SSD) GIB DISKS MBPS (MBPS)

Standard_E2a_ 2 16 50 4 3000 / 46 / 2 / 1000


v4 23

Standard_E4a_ 4 32 100 8 6000 / 93 / 2 / 2000


v4 46

Standard_E8a_ 8 64 200 16 12000 / 187 / 4 / 4000


v4 93

Standard_E16 16 128 400 32 24000 / 375 / 8 / 8000


a_v4 187

Standard_E20 20 160 500 32 30000 / 468 / 8 / 10000


a_v4 234

Standard_E32 32 256 800 32 48000 / 750 / 8 / 16000


a_v4 375

Standard_E48 48 384 1200 32


a_v4 **

Standard_E64 64 512 1600 32


a_v4 **

Standard_E96 96 672 2400 32


a_v4 **

**
**These sizes are in Preview. If you are interested in trying out these larger sizes, sign up at
https://aka.ms/AzureAMDLargeVMPreview.

Easv4-series
ACU: 230 - 260
Premium Storage: Supported
Premium Storage caching: Supported
Easv4-series sizes are based on the 2.35Ghz AMD EPYC TM 7452 processor that can achieve a boosted maximum
frequency of 3.35GHz and use premium SSD. The Easv4-series sizes are ideal for memory-intensive enterprise
applications.

MAX
CACHED AND
TEMP
STORAGE MAX
THROUGHP UNCACHED MAX NICS /
UT: IOPS / DISK EXPECTED
TEMP MBPS THROUGHP NETWORK
MEMORY: STORAGE MAX DATA (CACHE SIZE UT: IOPS / BANDWIDTH
SIZE VCPU GIB (SSD) GIB DISKS IN GIB) MBPS (MBPS)

Standard_E 2 16 32 4 4000 / 32 3200 / 48 2 / 1000


2as_v4 (50)

Standard_E 4 32 64 8 8000 / 64 6400 / 96 2 / 2000


4as_v4 (100)

Standard_E 8 64 128 16 16000 / 12800 / 4 / 4000


8as_v4 128 (200) 192

Standard_E 16 128 256 32 32000 / 25600 / 8 / 8000


16as_v4 255 (400) 384

Standard_E 20 160 320 32 40000 / 32000 / 8 / 10000


20as_v4 320 (500) 480

Standard_E 32 256 512 32 64000 / 51200 / 8 / 16000


32as_v4 510 (800) 768

Standard_E 48 384 768 32


48as_v4 **

Standard_E 64 512 1024 32


64as_v4 **

Standard_E 96 672 1344 32


96as_v4 **

**These sizes are in Preview. If you are interested in trying out these larger sizes, sign up at
https://aka.ms/AzureAMDLargeVMPreview.

Size table definitions


Storage capacity is shown in units of GiB or 1024^3 bytes. When you compare disks measured in GB
(1000^3 bytes) to disks measured in GiB (1024^3) remember that capacity numbers given in GiB may
appear smaller. For example, 1023 GiB = 1098.4 GB.
Disk throughput is measured in input/output operations per second (IOPS ) and MBps where MBps = 10^6
bytes/sec.
Data disks can operate in cached or uncached modes. For cached data disk operation, the host cache mode
is set to ReadOnly or ReadWrite. For uncached data disk operation, the host cache mode is set to None.
If you want to get the best performance for your VMs, you should limit the number of data disks to two
disks per vCPU.
Expected network bandwidth is the maximum aggregated bandwidth allocated per VM type across all
NICs, for all destinations. For more information, see Virtual machine network bandwidth.
Upper limits aren't guaranteed. Limits offer guidance for selecting the right VM type for the intended
application. Actual network performance will depend on several factors including network congestion,
application loads, and network settings. For information on optimizing network throughput, see Optimize
network throughput for Azure virtual machines. To achieve the expected network performance on Linux or
Windows, you may need to select a specific version or optimize your VM. For more information, see
Bandwidth/Throughput testing (NTTTCP ).

Other sizes
General purpose
Memory optimized
Storage optimized
GPU optimized
High performance compute
Previous generations

Next steps
Learn more about how Azure compute units (ACU ) can help you compare compute performance across Azure
SKUs.
M-series
2/20/2020 • 2 minutes to read • Edit Online

The M -series offers a high vCPU count (up to 128 vCPUs) and a large amount of memory (up to 3.8 TiB ). It’s also
ideal for extremely large databases or other applications that benefit from high vCPU counts and large amounts of
memory. M -series sizes are based on the Intel® Xeon® CPU E7-8890 v3 @ 2.50GHz
M -series VM’s feature Intel® Hyper-Threading Technology
ACU: 160-180
Premium Storage: Supported
Premium Storage caching: Supported
Write Accelerator: Supported

MAX
CACHED AND
TEMP
STORAGE MAX MAX
THROUGHP UNCACHED NICS/EXPECT
UT: DISK ED
TEMP IOPS/MBPS THROUGHP NETWORK
MEMORY: STORAGE MAX DATA (CACHE SIZE UT: BANDWIDTH
SIZE VCPU GIB (SSD) GIB DISKS IN GIB) IOPS/MBPS (MBPS)

Standard_M 8 218.75 256 8 10000/100 5000/125 4/2000


8ms 2 (793)

Standard_M 16 437.5 512 16 20000/200 10000/250 8/4000


16ms 2 (1587)

Standard_M 32 192 1024 32 40000/400 20000/500 8/8000


32ts (3174)

Standard_M 32 256 1024 32 40000/400 20000/500 8/8000


32ls (3174)

Standard_M 32 875 1024 32 40000/400 20000/500 8/8000


32ms 2 (3174)

Standard_M 64 1024 2048 64 80000/800 40000/100 8/16000


64s (6348) 0

Standard_M 64 512 2048 64 80000/800 40000/100 8/16000


64ls (6348) 0

Standard_M 64 1792 2048 64 80000/800 40000/100 8/16000


64ms 3 (6348) 0

Standard_M 128 2048 4096 64 160000/16 80000/200 8/30000


128s 1 00 (12696) 0
MAX
CACHED AND
TEMP
STORAGE MAX MAX
THROUGHP UNCACHED NICS/EXPECT
UT: DISK ED
TEMP IOPS/MBPS THROUGHP NETWORK
MEMORY: STORAGE MAX DATA (CACHE SIZE UT: BANDWIDTH
SIZE VCPU GIB (SSD) GIB DISKS IN GIB) IOPS/MBPS (MBPS)

Standard_M 128 3892 4096 64 160000/16 80000/200 8/30000


128ms 1,2,3 00 (12696) 0

Standard_M 64 1024 7168 64 80000/800 40000/100 8/16000


64 (1228) 0

Standard_M 64 1792 7168 64 80000/800 40000/100 8/16000


64m (1228) 0

Standard_M 128 2048 14336 64 250000/16 80000/200 8/32000


128 1 00 (2456) 0

Standard_M 128 3892 14336 64 250000/16 80000/200 8/32000


128m 1 00 (2456) 0

1 More than 64vCPU’s require one of these supported guest OSes: Windows Server 2016, Ubuntu 16.04 LTS,
SLES 12 SP2, and Red Hat Enterprise Linux, CentOS 7.3 or Oracle Linux 7.3 with LIS 4.2.1.
2 Constrained core sizes available.

3 Instance is isolated to hardware dedicated to a single customer.

Size table definitions


Storage capacity is shown in units of GiB or 1024^3 bytes. When you compare disks measured in GB
(1000^3 bytes) to disks measured in GiB (1024^3) remember that capacity numbers given in GiB may
appear smaller. For example, 1023 GiB = 1098.4 GB.
Disk throughput is measured in input/output operations per second (IOPS ) and MBps where MBps = 10^6
bytes/sec.
Data disks can operate in cached or uncached modes. For cached data disk operation, the host cache mode
is set to ReadOnly or ReadWrite. For uncached data disk operation, the host cache mode is set to None.
If you want to get the best performance for your VMs, you should limit the number of data disks to two
disks per vCPU.
Expected network bandwidth is the maximum aggregated bandwidth allocated per VM type across all
NICs, for all destinations. For more information, see Virtual machine network bandwidth.
Upper limits aren't guaranteed. Limits offer guidance for selecting the right VM type for the intended
application. Actual network performance will depend on several factors including network congestion,
application loads, and network settings. For information on optimizing network throughput, see Optimize
network throughput for Azure virtual machines. To achieve the expected network performance on Linux or
Windows, you may need to select a specific version or optimize your VM. For more information, see
Bandwidth/Throughput testing (NTTTCP ).

Other sizes
General purpose
Memory optimized
Storage optimized
GPU optimized
High performance compute
Previous generations

Next steps
Learn more about how Azure compute units (ACU ) can help you compare compute performance across Azure
SKUs.
Mv2-series
2/20/2020 • 2 minutes to read • Edit Online

The Mv2-series features high throughput, low latency platform running on a hyper-threaded Intel® Xeon®
Platinum 8180M 2.5GHz (Skylake) processor with an all core base frequency of 2.5 GHz and a max turbo
frequency of 3.8 GHz. All Mv2-series virtual machine sizes can use both standard and premium persistent disks.
Mv2-series instances are memory optimized VM sizes providing unparalleled computational performance to
support large in-memory databases and workloads, with a high memory-to-CPU ratio that is ideal for relational
database servers, large caches, and in-memory analytics.
Mv2-series VM’s feature Intel® Hyper-Threading Technology
Premium Storage: Supported
Premium Storage caching: Supported
Write Accelerator: Supported

MAX
CACHED AND
TEMP
STORAGE MAX
THROUGHP UNCACHED MAX NICS /
UT: IOPS / DISK EXPECTED
TEMP MBPS THROUGHP NETWORK
MEMORY: STORAGE MAX DATA (CACHE SIZE UT: IOPS / BANDWIDTH
SIZE VCPU GIB (SSD) GIB DISKS IN GIB) MBPS (MBPS)

Standard_M 208 5700 4096 64 80000 / 40000 / 8 / 16000


208ms_v21 800 (7040) 1000

Standard_M 208 2850 4096 64 80000 / 40000 / 8 / 16000


208s_v21 800 (7040) 1000

Standard_M 416 11400 8192 64 250000 / 80000 / 8 / 32000


416ms_v21, 1600 2000
2 (14080)

Standard_M 416 5700 8192 64 250000 / 80000 / 8 / 32000


416s_v21, 2 1600 2000
(14080)

1 Mv2 -series VMs are generation 2 only. If you're using Linux, see Support for generation 2 VMs on Azure for
instructions on how to find and select an image.
2 For
the M416ms_v2 and M416s_v2 sizes, note that there is initial support for the following image only: “GEN2:
SUSE Linux Enterprise Server (SLES ) 12 SP4 for SAP Applications."

Size table definitions


Storage capacity is shown in units of GiB or 1024^3 bytes. When you compare disks measured in GB
(1000^3 bytes) to disks measured in GiB (1024^3) remember that capacity numbers given in GiB may
appear smaller. For example, 1023 GiB = 1098.4 GB.
Disk throughput is measured in input/output operations per second (IOPS ) and MBps where MBps = 10^6
bytes/sec.
Data disks can operate in cached or uncached modes. For cached data disk operation, the host cache mode
is set to ReadOnly or ReadWrite. For uncached data disk operation, the host cache mode is set to None.
If you want to get the best performance for your VMs, you should limit the number of data disks to two
disks per vCPU.
Expected network bandwidth is the maximum aggregated bandwidth allocated per VM type across all
NICs, for all destinations. For more information, see Virtual machine network bandwidth.
Upper limits aren't guaranteed. Limits offer guidance for selecting the right VM type for the intended
application. Actual network performance will depend on several factors including network congestion,
application loads, and network settings. For information on optimizing network throughput, see Optimize
network throughput for Azure virtual machines. To achieve the expected network performance on Linux or
Windows, you may need to select a specific version or optimize your VM. For more information, see
Bandwidth/Throughput testing (NTTTCP ).

Other sizes
General purpose
Memory optimized
Storage optimized
GPU optimized
High performance compute
Previous generations

Next steps
Learn more about how Azure compute units (ACU ) can help you compare compute performance across Azure
SKUs.
Constrained vCPU capable VM sizes
11/13/2019 • 2 minutes to read • Edit Online

Some database workloads like SQL Server or Oracle require high memory, storage, and I/O bandwidth, but not a
high core count. Many database workloads are not CPU -intensive. Azure offers certain VM sizes where you can
constrain the VM vCPU count to reduce the cost of software licensing, while maintaining the same memory,
storage, and I/O bandwidth.
The vCPU count can be constrained to one half or one quarter of the original VM size. These new VM sizes have a
suffix that specifies the number of active vCPUs to make them easier for you to identify.
For example, the current VM size Standard_GS5 comes with 32 vCPUs, 448 GB RAM, 64 disks (up to 256 TB ), and
80,000 IOPs or 2 GB/s of I/O bandwidth. The new VM sizes Standard_GS5-16 and Standard_GS5-8 comes with
16 and 8 active vCPUs respectively, while maintaining the rest of the specs of the Standard_GS5 for memory,
storage, and I/O bandwidth.
The licensing fees charged for SQL Server or Oracle are constrained to the new vCPU count, and other products
should be charged based on the new vCPU count. This results in a 50% to 75% increase in the ratio of the VM
specs to active (billable) vCPUs. These new VM sizes allow customer workloads to use the same memory, storage,
and I/O bandwidth while optimizing their software licensing cost. At this time, the compute cost, which includes OS
licensing, remains the same one as the original size. For more information, see Azure VM sizes for more cost-
effective database workloads.

NAME VCPU SPECS

Standard_M8-2ms 2 Same as M8ms

Standard_M8-4ms 4 Same as M8ms

Standard_M16-4ms 4 Same as M16ms

Standard_M16-8ms 8 Same as M16ms

Standard_M32-8ms 8 Same as M32ms

Standard_M32-16ms 16 Same as M32ms

Standard_M64-32ms 32 Same as M64ms

Standard_M64-16ms 16 Same as M64ms

Standard_M128-64ms 64 Same as M128ms

Standard_M128-32ms 32 Same as M128ms

Standard_E4-2s_v3 2 Same as E4s_v3

Standard_E8-4s_v3 4 Same as E8s_v3

Standard_E8-2s_v3 2 Same as E8s_v3


NAME VCPU SPECS

Standard_E16-8s_v3 8 Same as E16s_v3

Standard_E16-4s_v3 4 Same as E16s_v3

Standard_E32-16s_v3 16 Same as E32s_v3

Standard_E32-8s_v3 8 Same as E32s_v3

Standard_E64-32s_v3 32 Same as E64s_v3

Standard_E64-16s_v3 16 Same as E64s_v3

Standard_GS4-8 8 Same as GS4

Standard_GS4-4 4 Same as GS4

Standard_GS5-16 16 Same as GS5

Standard_GS5-8 8 Same as GS5

Standard_DS11-1_v2 1 Same as DS11_v2

Standard_DS12-2_v2 2 Same as DS12_v2

Standard_DS12-1_v2 1 Same as DS12_v2

Standard_DS13-4_v2 4 Same as DS13_v2

Standard_DS13-2_v2 2 Same as DS13_v2

Standard_DS14-8_v2 8 Same as DS14_v2

Standard_DS14-4_v2 4 Same as DS14_v2

Other sizes
Compute optimized
Memory optimized
Storage optimized
GPU
High performance compute

Next steps
Learn more about how Azure compute units (ACU ) can help you compare compute performance across Azure
SKUs.
Storage optimized virtual machine sizes
2/20/2020 • 2 minutes to read • Edit Online

Storage optimized VM sizes offer high disk throughput and IO, and are ideal for Big Data, SQL, NoSQL
databases, data warehousing, and large transactional databases. Examples include Cassandra, MongoDB,
Cloudera, and Redis. This article provides information about the number of vCPUs, data disks, and NICs as
well as local storage throughput and network bandwidth for each optimized size.
The Lsv2-series features high throughput, low latency, directly mapped local NVMe storage running on the
AMD EPYC TM 7551 processor with an all core boost of 2.55GHz and a max boost of 3.0GHz. The Lsv2-series
VMs come in sizes from 8 to 80 vCPU in a simultaneous multi-threading configuration. There is 8 GiB of
memory per vCPU, and one 1.92TB NVMe SSD M.2 device per 8 vCPUs, with up to 19.2TB (10x1.92TB )
available on the L80s v2.

Other sizes
General purpose
Compute optimized
Memory optimized
GPU optimized
High performance compute
Previous generations

Next steps
Learn more about how Azure compute units (ACU ) can help you compare compute performance across
Azure SKUs.
Learn how to optimize performance on the Lsv2-series virtual machines for Windows or Linux.
Lsv2-series
2/24/2020 • 3 minutes to read • Edit Online

The Lsv2-series features high throughput, low latency, directly mapped local NVMe storage running on the AMD
EPYC TM 7551 processor with an all core boost of 2.55GHz and a max boost of 3.0GHz. The Lsv2-series VMs come
in sizes from 8 to 80 vCPU in a simultaneous multi-threading configuration. There is 8 GiB of memory per vCPU,
and one 1.92TB NVMe SSD M.2 device per 8 vCPUs, with up to 19.2TB (10x1.92TB ) available on the L80s v2.

NOTE
The Lsv2-series VMs are optimized to use the local disk on the node attached directly to the VM rather than using durable
data disks. This allows for greater IOPs / throughput for your workloads. The Lsv2 and Ls-series do not support the creation
of a local cache to increase the IOPs achievable by durable data disks.
The high throughput and IOPs of the local disk makes the Lsv2-series VMs ideal for NoSQL stores such as Apache Cassandra
and MongoDB which replicate data across multiple VMs to achieve persistence in the event of the failure of a single VM.
To learn more, see Optimize performance on the Lsv2-series virtual machines for Windows or Linux.

ACU: 150-175
Premium Storage: Supported
Premium Storage caching: Not Supported

MAX
NVME UNCACHE
DISK D DATA MAX NICS
THROUGH DISK /
PUT3 THROUGH EXPECTED
TEMP (READ PUT NETWORK
MEMORY DISK 1 NVME IOPS/MBP (IOPS/MBP MAX DATA BANDWID
SIZE VCPU (GIB) (GIB) DISKS 2 S) S)4 DISKS TH (MBPS)

Standard_ 8 64 80 1x1.92 TB 400000/2 8000/160 16 2 / 3200


L8s_v2 000

Standard_ 16 128 160 2x1.92 TB 800000/4 16000/32 32 4 / 6400


L16s_v2 000 0

Standard_ 32 256 320 4x1.92 TB 1.5M/800 32000/64 32 8 / 12800


L32s_v2 0 0

Standard_ 48 384 480 6x1.92 TB 2.2M/140 48000/96 32 8/


L48s_v2 00 0 16000+

Standard_ 64 512 640 8x1.92 TB 2.9M/160 64000/12 32 8/


L64s_v2 00 80 16000+

Standard_ 80 640 800 10x1.92T 3.8M/200 80000/14 32 8/


L80s_v25 B 00 00 16000+

1 Lsv2 -series
VMs have a standard SCSI based temp resource disk for OS paging/swap file use (D: on Windows,
/dev/sdb on Linux). This disk provides 80 GiB of storage, 4,000 IOPS, and 80 MBps transfer rate for every 8
vCPUs (e.g. Standard_L80s_v2 provides 800 GiB at 40,000 IOPS and 800 MBPS ). This ensures the NVMe drives
can be fully dedicated to application use. This disk is Ephemeral, and all data will be lost on stop/deallocate.
2 Local NVMe Disks are ephemeral, data will be lost on these disks if you stop/deallocate your VM.
3 Hyper -V NVMe Direct technology provides unthrottled access to local NVMe drives mapped securely into the
guest VM space. Achieving maximum performance requires using either the latest WS2019 build or Ubuntu 18.04
or 16.04 from the Azure Marketplace. Write performance varies based on IO size, drive load, and capacity
utilization.
4 Lsv2 -series
VMs do not provide host cache for data disk as it does not benefit the Lsv2 workloads. However,
Lsv2 VMs can accommodate Azure’s Ephemeral VM OS disk option (up to 30 GiB ).
5 VMs with more than 64 vCPUs require one of these supported guest operating systems:
Windows Server 2016 or later
Ubuntu 16.04 LTS or later, with Azure tuned kernel (4.15 kernel or later)
SLES 12 SP2 or later
RHEL or CentOS version 6.7 through 6.10, with Microsoft-provided LIS package 4.3.1 (or later) installed
RHEL or CentOS version 7.3, with Microsoft-provided LIS package 4.2.1 (or later) installed
RHEL or CentOS version 7.6 or later
Oracle Linux with UEK4 or later
Debian 9 with the backports kernel, Debian 10 or later
CoreOS with a 4.14 kernel or later

Size table definitions


Storage capacity is shown in units of GiB or 1024^3 bytes. When comparing disks measured in GB (1000^3
bytes) to disks measured in GiB (1024^3) remember that capacity numbers given in GiB may appear smaller.
For example, 1023 GiB = 1098.4 GB
Disk throughput is measured in input/output operations per second (IOPS ) and MBps where MBps = 10^6
bytes/sec.
If you want to get the best performance for your VMs, you should limit the number of data disks to 2 disks per
vCPU.
Expected network bandwidth is the maximum aggregated bandwidth allocated per VM type across all NICs,
for all destinations. Upper limits are not guaranteed, but are intended to provide guidance for selecting the right
VM type for the intended application. Actual network performance will depend on a variety of factors including
network congestion, application loads, and network settings. For information on optimizing network
throughput, see Optimizing network throughput for Windows and Linux. To achieve the expected network
performance on Linux or Windows, it may be necessary to select a specific version or optimize your VM. For
more information, see How to reliably test for virtual machine throughput.

Next steps
Learn more about how Azure compute units (ACU ) can help you compare compute performance across Azure
SKUs.
Optimize performance on the Lsv2-series virtual
machines
11/13/2019 • 5 minutes to read • Edit Online

Lsv2-series virtual machines support a variety of workloads that need high I/O and throughput on local storage
across a wide range of applications and industries. The Lsv2-series is ideal for Big Data, SQL, NoSQL databases,
data warehousing and large transactional databases, including Cassandra, MongoDB, Cloudera, and Redis.
The design of the Lsv2-series Virtual Machines (VMs) maximizes the AMD EPYC™ 7551 processor to provide the
best performance between the processor, memory, NVMe devices, and the VMs. In addition to maximizing the
hardware performance, Lsv2-series VMs are designed to work with the needs of Windows and Linux operating
systems for better performance with the hardware and the software.
Tuning the software and hardware resulted in the optimized version of Windows Server 2019 Datacenter, released
in early December 2018 to the Azure Marketplace, which supports maximum performance on the NVMe devices
in Lsv2-series VMs.
This article provides tips and suggestions to ensure your workloads and applications achieve the maximum
performance designed into the VMs. The information on this page will be continuously updated as more Lsv2
optimized images are added to the Azure Marketplace.

AMD EYPC™ chipset architecture


Lsv2-series VMs use AMD EYPC™ server processors based on the Zen microarchitecture. AMD developed Infinity
Fabric (IF ) for EYPC™ as scalable interconnect for its NUMA model that could be used for on-die, on-package, and
multi-package communications. Compared with QPI (Quick-Path Interconnect) and UPI (Ultra-Path Interconnect)
used on Intel modern monolithic-die processors, AMD’s many-NUMA small-die architecture may bring both
performance benefits as well as challenges. The actual impact of memory bandwidth and latency constraints could
vary depending on the type of workloads running.

Tips for maximizing performance


The hardware that powers the Lsv2-series VMs utilizes NVMe devices with eight I/O Queue Pairs (QP )s.
Every NVMe device I/O queue is actually a pair: a submission queue and a completion queue. The NVMe
driver is set up to optimize the utilization of these eight I/O QPs by distributing I/O’s in a round robin
schedule. To gain max performance, run eight jobs per device to match.
Avoid mixing NVMe admin commands (for example, NVMe SMART info query, etc.) with NVMe I/O
commands during active workloads. Lsv2 NVMe devices are backed by Hyper-V NVMe Direct technology,
which switches into “slow mode” whenever any NVMe admin commands are pending. Lsv2 users could see
a dramatic performance drop in NVMe I/O performance if that happens.
Lsv2 users should not rely on device NUMA information (all 0) reported from within the VM for data drives
to decide the NUMA affinity for their apps. The recommended way for better performance is to spread
workloads across CPUs if possible.
The maximum supported queue depth per I/O queue pair for Lsv2 VM NVMe device is 1024 (vs. Amazon
i3 QD 32 limit). Lsv2 users should limit their (synthetic) benchmarking workloads to queue depth 1024 or
lower to avoid triggering queue full conditions, which can reduce performance.
Utilizing local NVMe storage
Local storage on the 1.92 TB NVMe disk on all Lsv2 VMs is ephemeral. During a successful standard reboot of the
VM, the data on the local NVMe disk will persist. The data will not persist on the NVMe if the VM is redeployed,
de-allocated, or deleted. Data will not persist if another issue causes the VM, or the hardware it is running on, to
become unhealthy. When this happens, any data on the old host is securely erased.
There will also be cases when the VM needs to be moved to a different host machine, for example, during a
planned maintenance operation. Planned maintenance operations and some hardware failures can be anticipated
with Scheduled Events. Scheduled Events should be used to stay updated on any predicted maintenance and
recovery operations.
In the case that a planned maintenance event requires the VM to be recreated on a new host with empty local
disks, the data will need to be resynchronized (again, with any data on the old host being securely erased). This
occurs because Lsv2-series VMs do not currently support live migration on the local NVMe disk.
There are two modes for planned maintenance.
Standard VM customer-controlled maintenance
The VM is moved to an updated host during a 30-day window.
Lsv2 local storage data could be lost, so backing-up data prior to the event is recommended.
Automatic maintenance
Occurs if the customer does not execute customer-controlled maintenance, or in the event of emergency
procedures such as a security zero-day event.
Intended to preserve customer data, but there is a small risk of a VM freeze or reboot.
Lsv2 local storage data could be lost, so backing-up data prior to the event is recommended.
For any upcoming service events, use the controlled maintenance process to select a time most convenient to you
for the update. Prior to the event, you may back up your data in premium storage. After the maintenance event
completes, you can return your data to the refreshed Lsv2 VMs local NVMe storage.
Scenarios that maintain data on local NVMe disks include:
The VM is running and healthy.
The VM is rebooted in place (by you or Azure).
The VM is paused (stopped without de-allocation).
The majority of the planned maintenance servicing operations.
Scenarios that securely erase data to protect the customer include:
The VM is redeployed, stopped (de-allocated), or deleted (by you).
The VM becomes unhealthy and has to service heal to another node due to a hardware issue.
A small number of the planned maintenance servicing operations that requires the VM to be reallocated to
another host for servicing.
To learn more about options for backing up data in local storage, see Backup and disaster recovery for Azure IaaS
disks.

Frequently asked questions


How do I start deploying Lsv2-series VMs?
Much like any other VM, use the Portal, Azure CLI, or PowerShell to create a VM.
Will a single NVMe disk failure cause all VMs on the host to fail?
If a disk failure is detected on the hardware node, the hardware is in a failed state. When this occurs, all VMs
on the node are automatically de-allocated and moved to a healthy node. For Lsv2-series VMs, this means
that the customer’s data on the failing node is also securely erased and will need to be recreated by the
customer on the new node. As noted, before live migration becomes available on Lsv2, the data on the
failing node will be proactively moved with the VMs as they are transferred to another node.
Do I need to make polling adjustments in Windows in Windows Server 2012 or Windows Server
2016?
NVMe polling is only available on Windows Server 2019 on Azure.
Can I switch back to a traditional interrupt service routine (ISR) model?
Lsv2-series VMs are optimized for NVMe polling. Updates are continuously provided to improve polling
performance.
Can I adjust the polling settings in Windows Server 2019?
The polling settings are not user adjustable.

Next steps
See specifications for all VMs optimized for storage performance on Azure
2 minutes to read
NC-series
2/20/2020 • 2 minutes to read • Edit Online

NC -series VMs are powered by the NVIDIA Tesla K80 card and the Intel Xeon E5-2690 v3 (Haswell) processor.
Users can crunch through data faster by leveraging CUDA for energy exploration applications, crash simulations,
ray traced rendering, deep learning, and more. The NC24r configuration provides a low latency, high-throughput
network interface optimized for tightly coupled parallel computing workloads.
Premium Storage: Not Supported
Premium Storage caching: Not Supported

TEMP GPU
MEMORY: STORAGE MEMORY: MAX DATA
SIZE VCPU GIB (SSD) GIB GPU GIB DISKS MAX NICS

Standard_N 6 56 340 1 12 24 1
C6

Standard_N 12 112 680 2 24 48 2


C12

Standard_N 24 224 1440 4 48 64 4


C24

Standard_N 24 224 1440 4 48 64 4


C24r*

1 GPU = one-half K80 card.


*RDMA capable

Size table definitions


Storage capacity is shown in units of GiB or 1024^3 bytes. When you compare disks measured in GB
(1000^3 bytes) to disks measured in GiB (1024^3) remember that capacity numbers given in GiB may
appear smaller. For example, 1023 GiB = 1098.4 GB.
Disk throughput is measured in input/output operations per second (IOPS ) and MBps where MBps = 10^6
bytes/sec.
Data disks can operate in cached or uncached modes. For cached data disk operation, the host cache mode
is set to ReadOnly or ReadWrite. For uncached data disk operation, the host cache mode is set to None.
If you want to get the best performance for your VMs, you should limit the number of data disks to two
disks per vCPU.
Expected network bandwidth is the maximum aggregated bandwidth allocated per VM type across all
NICs, for all destinations. For more information, see Virtual machine network bandwidth.
Upper limits aren't guaranteed. Limits offer guidance for selecting the right VM type for the intended
application. Actual network performance will depend on several factors including network congestion,
application loads, and network settings. For information on optimizing network throughput, see Optimize
network throughput for Azure virtual machines. To achieve the expected network performance on Linux or
Windows, you may need to select a specific version or optimize your VM. For more information, see
Bandwidth/Throughput testing (NTTTCP ).

Supported operating systems and drivers


To take advantage of the GPU capabilities of Azure N -series VMs, NVIDIA GPU drivers must be installed.
The NVIDIA GPU Driver Extension installs appropriate NVIDIA CUDA or GRID drivers on an N -series VM. Install
or manage the extension using the Azure portal or tools such as Azure PowerShell or Azure Resource Manager
templates. See the NVIDIA GPU Driver Extension documentation for supported operating systems and
deployment steps. For general information about VM extensions, see Azure virtual machine extensions and
features.
If you choose to install NVIDIA GPU drivers manually, see N -series GPU driver setup for Windows or N -series
GPU driver setup for Linux for supported operating systems, drivers, installation, and verification steps.

Other sizes
General purpose
Memory optimized
Storage optimized
GPU optimized
High performance compute
Previous generations

Next steps
Learn more about how Azure compute units (ACU ) can help you compare compute performance across Azure
SKUs.
NCv2-series
2/20/2020 • 2 minutes to read • Edit Online

NCv2-series VMs are powered by NVIDIA Tesla P100 GPUs. These GPUs can provide more than 2x the
computational performance of the NC -series. Customers can take advantage of these updated GPUs for traditional
HPC workloads such as reservoir modeling, DNA sequencing, protein analysis, Monte Carlo simulations, and
others. In addition to the GPUs, the NCv2-series VMs are also powered by Intel Xeon E5-2690 v4 (Broadwell)
CPUs.
The NC24rs v2 configuration provides a low latency, high-throughput network interface optimized for tightly
coupled parallel computing workloads.
Premium Storage: Supported
Premium Storage caching: Supported

IMPORTANT
For this VM series, the vCPU (core) quota in your subscription is initially set to 0 in each region. Request a vCPU quota
increase for this series in an available region.

MAX
UNCACHED
DISK
THROUGH
TEMP GPU PUT:
MEMORY: STORAGE MEMORY: MAX DATA IOPS/MBP
SIZE VCPU GIB (SSD) GIB GPU GIB DISKS S MAX NICS

Standard_ 6 112 736 1 16 12 20000/20 4


NC6s_v2 0

Standard_ 12 224 1474 2 32 24 40000/40 8


NC12s_v2 0

Standard_ 24 448 2948 4 64 32 80000/80 8


NC24s_v2 0

Standard_ 24 448 2948 4 64 32 80000/80 8


NC24rs_v 0
2*

1 GPU = one P100 card.


*RDMA capable

Size table definitions


Storage capacity is shown in units of GiB or 1024^3 bytes. When you compare disks measured in GB
(1000^3 bytes) to disks measured in GiB (1024^3) remember that capacity numbers given in GiB may
appear smaller. For example, 1023 GiB = 1098.4 GB.
Disk throughput is measured in input/output operations per second (IOPS ) and MBps where MBps = 10^6
bytes/sec.
Data disks can operate in cached or uncached modes. For cached data disk operation, the host cache mode
is set to ReadOnly or ReadWrite. For uncached data disk operation, the host cache mode is set to None.
If you want to get the best performance for your VMs, you should limit the number of data disks to two
disks per vCPU.
Expected network bandwidth is the maximum aggregated bandwidth allocated per VM type across all
NICs, for all destinations. For more information, see Virtual machine network bandwidth.
Upper limits aren't guaranteed. Limits offer guidance for selecting the right VM type for the intended
application. Actual network performance will depend on several factors including network congestion,
application loads, and network settings. For information on optimizing network throughput, see Optimize
network throughput for Azure virtual machines. To achieve the expected network performance on Linux or
Windows, you may need to select a specific version or optimize your VM. For more information, see
Bandwidth/Throughput testing (NTTTCP ).

Supported operating systems and drivers


To take advantage of the GPU capabilities of Azure N -series VMs, NVIDIA GPU drivers must be installed.
The NVIDIA GPU Driver Extension installs appropriate NVIDIA CUDA or GRID drivers on an N -series VM. Install
or manage the extension using the Azure portal or tools such as Azure PowerShell or Azure Resource Manager
templates. See the NVIDIA GPU Driver Extension documentation for supported operating systems and
deployment steps. For general information about VM extensions, see Azure virtual machine extensions and
features.
If you choose to install NVIDIA GPU drivers manually, see N -series GPU driver setup for Windows or N -series
GPU driver setup for Linux for supported operating systems, drivers, installation, and verification steps.

Other sizes
General purpose
Memory optimized
Storage optimized
GPU optimized
High performance compute
Previous generations

Next steps
Learn more about how Azure compute units (ACU ) can help you compare compute performance across Azure
SKUs.
NCv3-series
2/20/2020 • 2 minutes to read • Edit Online

NCv3-series VMs are powered by NVIDIA Tesla V100 GPUs. These GPUs can provide 1.5x the computational
performance of the NCv2-series. Customers can take advantage of these updated GPUs for traditional HPC
workloads such as reservoir modeling, DNA sequencing, protein analysis, Monte Carlo simulations, and others.
The NC24rs v3 configuration provides a low latency, high-throughput network interface optimized for tightly
coupled parallel computing workloads. In addition to the GPUs, the NCv3-series VMs are also powered by Intel
Xeon E5-2690 v4 (Broadwell) CPUs.
Premium Storage: Supported
Premium Storage caching: Supported

IMPORTANT
For this VM series, the vCPU (core) quota in your subscription is initially set to 0 in each region. Request a vCPU quota
increase for this series in an available region.

MAX
UNCACHED
DISK
THROUGH
TEMP GPU PUT:
MEMORY: STORAGE MEMORY: MAX DATA IOPS/MBP
SIZE VCPU GIB (SSD) GIB GPU GIB DISKS S MAX NICS

Standard_ 6 112 736 1 16 12 20000/20 4


NC6s_v3 0

Standard_ 12 224 1474 2 32 24 40000/40 8


NC12s_v3 0

Standard_ 24 448 2948 4 64 32 80000/80 8


NC24s_v3 0

Standard_ 24 448 2948 4 64 32 80000/80 8


NC24rs_v 0
3*

1 GPU = one V100 card.


*RDMA capable

Size table definitions


Storage capacity is shown in units of GiB or 1024^3 bytes. When you compare disks measured in GB
(1000^3 bytes) to disks measured in GiB (1024^3) remember that capacity numbers given in GiB may
appear smaller. For example, 1023 GiB = 1098.4 GB.
Disk throughput is measured in input/output operations per second (IOPS ) and MBps where MBps = 10^6
bytes/sec.
Data disks can operate in cached or uncached modes. For cached data disk operation, the host cache mode
is set to ReadOnly or ReadWrite. For uncached data disk operation, the host cache mode is set to None.
If you want to get the best performance for your VMs, you should limit the number of data disks to two
disks per vCPU.
Expected network bandwidth is the maximum aggregated bandwidth allocated per VM type across all
NICs, for all destinations. For more information, see Virtual machine network bandwidth.
Upper limits aren't guaranteed. Limits offer guidance for selecting the right VM type for the intended
application. Actual network performance will depend on several factors including network congestion,
application loads, and network settings. For information on optimizing network throughput, see Optimize
network throughput for Azure virtual machines. To achieve the expected network performance on Linux or
Windows, you may need to select a specific version or optimize your VM. For more information, see
Bandwidth/Throughput testing (NTTTCP ).

Supported operating systems and drivers


To take advantage of the GPU capabilities of Azure N -series VMs, NVIDIA GPU drivers must be installed.
The NVIDIA GPU Driver Extension installs appropriate NVIDIA CUDA or GRID drivers on an N -series VM. Install
or manage the extension using the Azure portal or tools such as Azure PowerShell or Azure Resource Manager
templates. See the NVIDIA GPU Driver Extension documentation for supported operating systems and
deployment steps. For general information about VM extensions, see Azure virtual machine extensions and
features.
If you choose to install NVIDIA GPU drivers manually, see N -series GPU driver setup for Windows or N -series
GPU driver setup for Linux for supported operating systems, drivers, installation, and verification steps.

Other sizes
General purpose
Memory optimized
Storage optimized
GPU optimized
High performance compute
Previous generations

Next steps
Learn more about how Azure compute units (ACU ) can help you compare compute performance across Azure
SKUs.
ND-series
2/20/2020 • 3 minutes to read • Edit Online

The ND -series virtual machines are a new addition to the GPU family designed for AI, and Deep Learning
workloads. They offer excellent performance for training and inference. ND instances are powered by NVIDIA
Tesla P40 GPUs and Intel Xeon E5-2690 v4 (Broadwell) CPUs. These instances provide excellent performance for
single-precision floating point operations, for AI workloads utilizing Microsoft Cognitive Toolkit, TensorFlow, Caffe,
and other frameworks. The ND -series also offers a much larger GPU memory size (24 GB ), enabling to fit much
larger neural net models. Like the NC -series, the ND -series offers a configuration with a secondary low -latency,
high-throughput network through RDMA, and InfiniBand connectivity so you can run large-scale training jobs
spanning many GPUs.
Premium Storage: Supported
Premium Storage caching: Supported

IMPORTANT
For this VM series, the vCPU (core) quota per region in your subscription is initially set to 0. Request a vCPU quota increase
for this series in an available region.

MAX
UNCACHED
DISK
THROUGH
TEMP GPU PUT:
MEMORY: STORAGE MEMORY: MAX DATA IOPS/MBP
SIZE VCPU GIB (SSD) GIB GPU GIB DISKS S MAX NICS

Standard_ 6 112 736 1 24 12 20000/20 4


ND6s 0

Standard_ 12 224 1474 2 48 24 40000/40 8


ND12s 0

Standard_ 24 448 2948 4 96 32 80000/80 8


ND24s 0

Standard_ 24 448 2948 4 96 32 80000/80 8


ND24rs* 0

1 GPU = one P40 card.


*RDMA capable

Size table definitions


Storage capacity is shown in units of GiB or 1024^3 bytes. When you compare disks measured in GB
(1000^3 bytes) to disks measured in GiB (1024^3) remember that capacity numbers given in GiB may
appear smaller. For example, 1023 GiB = 1098.4 GB.
Disk throughput is measured in input/output operations per second (IOPS ) and MBps where MBps = 10^6
bytes/sec.
Data disks can operate in cached or uncached modes. For cached data disk operation, the host cache mode
is set to ReadOnly or ReadWrite. For uncached data disk operation, the host cache mode is set to None.
If you want to get the best performance for your VMs, you should limit the number of data disks to two
disks per vCPU.
Expected network bandwidth is the maximum aggregated bandwidth allocated per VM type across all
NICs, for all destinations. For more information, see Virtual machine network bandwidth.
Upper limits aren't guaranteed. Limits offer guidance for selecting the right VM type for the intended
application. Actual network performance will depend on several factors including network congestion,
application loads, and network settings. For information on optimizing network throughput, see Optimize
network throughput for Azure virtual machines. To achieve the expected network performance on Linux or
Windows, you may need to select a specific version or optimize your VM. For more information, see
Bandwidth/Throughput testing (NTTTCP ).

Supported operating systems and drivers


To take advantage of the GPU capabilities of Azure N -series VMs, NVIDIA GPU drivers must be installed.
The NVIDIA GPU Driver Extension installs appropriate NVIDIA CUDA or GRID drivers on an N -series VM. Install
or manage the extension using the Azure portal or tools such as Azure PowerShell or Azure Resource Manager
templates. See the NVIDIA GPU Driver Extension documentation for supported operating systems and
deployment steps. For general information about VM extensions, see Azure virtual machine extensions and
features.
If you choose to install NVIDIA GPU drivers manually, see N -series GPU driver setup for Windows or N -series
GPU driver setup for Linux for supported operating systems, drivers, installation, and verification steps.

Other sizes
General purpose
Memory optimized
Storage optimized
GPU optimized
High performance compute
Previous generations

Next steps
Learn more about how Azure compute units (ACU ) can help you compare compute performance across Azure
SKUs.
Updated NDv2-series (Preview)
2/25/2020 • 3 minutes to read • Edit Online

The NDv2-series virtual machine is a new addition to the GPU family designed for the needs of the most
demanding GPU -accelerated AI, machine learning, simulation, and HPC workloads.
NDv2 is powered by 8 NVIDIA Tesla V100 NVLINK-connected GPUs, each with 32 GB of GPU memory. Each
NDv2 VM also has 40 non-HyperThreaded Intel Xeon Platinum 8168 (Skylake) cores and 672 GiB of system
memory.
NDv2 instances provide excellent performance for HPC and AI workloads utilizing CUDA GPU -optimized
computation kernels, and the many AI, ML, and analytics tools that support GPU acceleration 'out-of-box,' such as
TensorFlow, Pytorch, Caffe, RAPIDS, and other frameworks.
Critically, the NDv2 is built for both computationally intense scale-up (harnessing 8 GPUs per VM ) and scale-out
(harnessing multiple VMs working together) workloads. The NDv2 series now supports 100-Gigabit InfiniBand
EDR backend networking, similar to that available on the HB series of HPC VM, to allow high-performance
clustering for parallel scenarios including distributed training for AI and ML. This backend network supports all
major InfiniBand protocols, including those employed by NVIDIA’s NCCL2 libraries, allowing for seamless
clustering of GPUs.

NOTE
When enabling InfiniBand on the ND40rs_v2 VM, please use the 4.7-1.0.0.1 Mellanox OFED driver.
Due to increased GPU memory, the new ND40rs_v2 VM requires the use of Generation 2 VMs and marketplace images.
Sign-up to request early access to the NDv2 virtual machine preview.
Please note: The ND40s_v2 featuring 16 GB of per-GPU memory is no longer available for preview and has been superceded
by the updated ND40rs_v2.

Premium Storage: Supported


Premium Storage caching: Supported
InfiniBand: Supported

MAX
UNCACH
ED DISK MAX
TEMP THROUG NETWOR
STORAGE GPU MAX HPUT: K
MEMORY (SSD): MEMORY DATA IOPS / BANDWI MAX
SIZE VCPU : GIB GIB GPU : GIB DISKS MBPS DTH NICS

Standar 40 672 2948 8 V100 16 32 80000 / 24000 8


d_ND40 32 GB 800 Mbps
rs_v2 (NVLink)

Size table definitions


Storage capacity is shown in units of GiB or 1024^3 bytes. When you compare disks measured in GB
(1000^3 bytes) to disks measured in GiB (1024^3) remember that capacity numbers given in GiB may
appear smaller. For example, 1023 GiB = 1098.4 GB.
Disk throughput is measured in input/output operations per second (IOPS ) and MBps where MBps = 10^6
bytes/sec.
Data disks can operate in cached or uncached modes. For cached data disk operation, the host cache mode
is set to ReadOnly or ReadWrite. For uncached data disk operation, the host cache mode is set to None.
If you want to get the best performance for your VMs, you should limit the number of data disks to two
disks per vCPU.
Expected network bandwidth is the maximum aggregated bandwidth allocated per VM type across all
NICs, for all destinations. For more information, see Virtual machine network bandwidth.
Upper limits aren't guaranteed. Limits offer guidance for selecting the right VM type for the intended
application. Actual network performance will depend on several factors including network congestion,
application loads, and network settings. For information on optimizing network throughput, see Optimize
network throughput for Azure virtual machines. To achieve the expected network performance on Linux or
Windows, you may need to select a specific version or optimize your VM. For more information, see
Bandwidth/Throughput testing (NTTTCP ).

Supported operating systems and drivers


To take advantage of the GPU capabilities of Azure N -series VMs, NVIDIA GPU drivers must be installed.
The NVIDIA GPU Driver Extension installs appropriate NVIDIA CUDA or GRID drivers on an N -series VM. Install
or manage the extension using the Azure portal or tools such as Azure PowerShell or Azure Resource Manager
templates. See the NVIDIA GPU Driver Extension documentation for supported operating systems and
deployment steps. For general information about VM extensions, see Azure virtual machine extensions and
features.
If you choose to install NVIDIA GPU drivers manually, see N -series GPU driver setup for Windows or N -series
GPU driver setup for Linux for supported operating systems, drivers, installation, and verification steps.

Other sizes
General purpose
Memory optimized
Storage optimized
GPU optimized
High performance compute
Previous generations

Next steps
Learn more about how Azure compute units (ACU ) can help you compare compute performance across Azure
SKUs.
NV-series
2/20/2020 • 2 minutes to read • Edit Online

The NV -series virtual machines are powered by NVIDIA Tesla M60 GPUs and NVIDIA GRID technology for
desktop accelerated applications and virtual desktops where customers are able to visualize their data or
simulations. Users are able to visualize their graphics intensive workflows on the NV instances to get superior
graphics capability and additionally run single precision workloads such as encoding and rendering. NV -series
VMs are also powered by Intel Xeon E5-2690 v3 (Haswell) CPUs.
Each GPU in NV instances comes with a GRID license. This license gives you the flexibility to use an NV instance
as a virtual workstation for a single user, or 25 concurrent users can connect to the VM for a virtual application
scenario.
Premium Storage: Not Supported
Premium Storage caching: Not Supported

TEMP
STORAGE GPU MAX VIRTUAL VIRTUAL
MEMORY (SSD) MEMORY DATA MAX WORKST APPLICAT
SIZE VCPU : GIB GIB GPU : GIB DISKS NICS ATIONS IONS

Standar 6 56 340 1 8 24 1 1 25
d_NV6

Standar 12 112 680 2 16 48 2 2 50


d_NV12

Standar 24 224 1440 4 32 64 4 4 100


d_NV24

1 GPU = one-half M60 card.

Size table definitions


Storage capacity is shown in units of GiB or 1024^3 bytes. When you compare disks measured in GB
(1000^3 bytes) to disks measured in GiB (1024^3) remember that capacity numbers given in GiB may
appear smaller. For example, 1023 GiB = 1098.4 GB.
Disk throughput is measured in input/output operations per second (IOPS ) and MBps where MBps = 10^6
bytes/sec.
Data disks can operate in cached or uncached modes. For cached data disk operation, the host cache mode
is set to ReadOnly or ReadWrite. For uncached data disk operation, the host cache mode is set to None.
If you want to get the best performance for your VMs, you should limit the number of data disks to two
disks per vCPU.
Expected network bandwidth is the maximum aggregated bandwidth allocated per VM type across all
NICs, for all destinations. For more information, see Virtual machine network bandwidth.
Upper limits aren't guaranteed. Limits offer guidance for selecting the right VM type for the intended
application. Actual network performance will depend on several factors including network congestion,
application loads, and network settings. For information on optimizing network throughput, see Optimize
network throughput for Azure virtual machines. To achieve the expected network performance on Linux or
Windows, you may need to select a specific version or optimize your VM. For more information, see
Bandwidth/Throughput testing (NTTTCP ).

Supported operating systems and drivers


To take advantage of the GPU capabilities of Azure N -series VMs, NVIDIA GPU drivers must be installed.
The NVIDIA GPU Driver Extension installs appropriate NVIDIA CUDA or GRID drivers on an N -series VM. Install
or manage the extension using the Azure portal or tools such as Azure PowerShell or Azure Resource Manager
templates. See the NVIDIA GPU Driver Extension documentation for supported operating systems and
deployment steps. For general information about VM extensions, see Azure virtual machine extensions and
features.
If you choose to install NVIDIA GPU drivers manually, see N -series GPU driver setup for Windows or N -series
GPU driver setup for Linux for supported operating systems, drivers, installation, and verification steps.

Other sizes
General purpose
Memory optimized
Storage optimized
GPU optimized
High performance compute
Previous generations

Next steps
Learn more about how Azure compute units (ACU ) can help you compare compute performance across Azure
SKUs.
NVv3-series
2/20/2020 • 2 minutes to read • Edit Online

The NVv3-series virtual machines are powered by NVIDIA Tesla M60 GPUs and NVIDIA GRID technology with
Intel E5-2690 v4 (Broadwell) CPUs and Intel Hyper-Threading Technology. These virtual machines are targeted for
GPU accelerated graphics applications and virtual desktops where customers want to visualize their data, simulate
results to view, work on CAD, or render and stream content. Additionally, these virtual machines can run single
precision workloads such as encoding and rendering. NVv3 virtual machines support Premium Storage and come
with twice the system memory (RAM ) when compared with its predecessor NV -series.
Each GPU in NVv3 instances comes with a GRID license. This license gives you the flexibility to use an NV instance
as a virtual workstation for a single user, or 25 concurrent users can connect to the VM for a virtual application
scenario.
Premium Storage caching: Supported

MAX
UNCAC
HED
TEMP DISK VIRTUA
STORA THROU L VIRTUA
GE GPU MAX GHPUT: WORKS L
MEMOR (SSD) MEMOR DATA IOPS/M MAX TATION APPLICA
SIZE VCPU Y: GIB GIB GPU Y: GIB DISKS BPS NICS S TIONS

Standa 12 112 320 1 8 12 20000/ 4 1 25


rd_NV1 200
2s_v3

Standa 24 224 640 2 16 24 40000/ 8 2 50


rd_NV2 400
4s_v3

Standa 48 448 1280 4 32 32 80000/ 8 4 100


rd_NV4 800
8s_v3

1 GPU = one-half M60 card.

Size table definitions


Storage capacity is shown in units of GiB or 1024^3 bytes. When you compare disks measured in GB
(1000^3 bytes) to disks measured in GiB (1024^3) remember that capacity numbers given in GiB may
appear smaller. For example, 1023 GiB = 1098.4 GB.
Disk throughput is measured in input/output operations per second (IOPS ) and MBps where MBps = 10^6
bytes/sec.
Data disks can operate in cached or uncached modes. For cached data disk operation, the host cache mode
is set to ReadOnly or ReadWrite. For uncached data disk operation, the host cache mode is set to None.
If you want to get the best performance for your VMs, you should limit the number of data disks to two
disks per vCPU.
Expected network bandwidth is the maximum aggregated bandwidth allocated per VM type across all
NICs, for all destinations. For more information, see Virtual machine network bandwidth.
Upper limits aren't guaranteed. Limits offer guidance for selecting the right VM type for the intended
application. Actual network performance will depend on several factors including network congestion,
application loads, and network settings. For information on optimizing network throughput, see Optimize
network throughput for Azure virtual machines. To achieve the expected network performance on Linux or
Windows, you may need to select a specific version or optimize your VM. For more information, see
Bandwidth/Throughput testing (NTTTCP ).

Supported operating systems and drivers


To take advantage of the GPU capabilities of Azure N -series VMs, NVIDIA GPU drivers must be installed.
The NVIDIA GPU Driver Extension installs appropriate NVIDIA CUDA or GRID drivers on an N -series VM. Install
or manage the extension using the Azure portal or tools such as Azure PowerShell or Azure Resource Manager
templates. See the NVIDIA GPU Driver Extension documentation for supported operating systems and
deployment steps. For general information about VM extensions, see Azure virtual machine extensions and
features.
If you choose to install NVIDIA GPU drivers manually, see N -series GPU driver setup for Windows or N -series
GPU driver setup for Linux for supported operating systems, drivers, installation, and verification steps.

Other sizes
General purpose
Memory optimized
Storage optimized
GPU optimized
High performance compute
Previous generations

Next steps
Learn more about how Azure compute units (ACU ) can help you compare compute performance across Azure
SKUs.
NVv4-series (Preview)
2/23/2020 • 2 minutes to read • Edit Online

The NVv4-series virtual machines are powered by AMD Radeon Instinct MI25 GPUs and AMD EPYC
7V12(Rome) CPUs. With NVv4-series Azure is introducing virtual machines with partial GPUs. Pick the right sized
virtual machine for GPU accelerated graphics applications and virtual desktops starting at 1/8th of a GPU with 2
GiB frame buffer to a full GPU with 16 GiB frame buffer. NVv4 virtual machines currently support only Windows
guest operating system.
Sign-up and get access to these machines during preview.
Premium Storage: Supported
Premium Storage caching: Supported

TEMP GPU
MEMORY: STORAGE MEMORY: MAX DATA
SIZE VCPU GIB (SSD) GIB GPU GIB DISKS MAX NICS

Standard_N 4 14 88 1/8 2 4 2
V4as_v4

Standard_N 8 28 176 1/4 4 8 4


V8as_v4

Standard_N 16 56 352 1/2 8 16 8


V16as_v4

Standard_N 32 112 704 1 16 32 8


V32as_v4

1 NVv4 -series VMs feature AMD Simultaneous multithreading Technology

Size table definitions


Storage capacity is shown in units of GiB or 1024^3 bytes. When you compare disks measured in GB
(1000^3 bytes) to disks measured in GiB (1024^3) remember that capacity numbers given in GiB may
appear smaller. For example, 1023 GiB = 1098.4 GB.
Disk throughput is measured in input/output operations per second (IOPS ) and MBps where MBps = 10^6
bytes/sec.
Data disks can operate in cached or uncached modes. For cached data disk operation, the host cache mode
is set to ReadOnly or ReadWrite. For uncached data disk operation, the host cache mode is set to None.
If you want to get the best performance for your VMs, you should limit the number of data disks to two
disks per vCPU.
Expected network bandwidth is the maximum aggregated bandwidth allocated per VM type across all
NICs, for all destinations. For more information, see Virtual machine network bandwidth.
Upper limits aren't guaranteed. Limits offer guidance for selecting the right VM type for the intended
application. Actual network performance will depend on several factors including network congestion,
application loads, and network settings. For information on optimizing network throughput, see Optimize
network throughput for Azure virtual machines. To achieve the expected network performance on Linux or
Windows, you may need to select a specific version or optimize your VM. For more information, see
Bandwidth/Throughput testing (NTTTCP ).

Supported operating systems and drivers


To take advantage of the GPU capabilities of Azure N -series VMs running Windows, NVIDIA or AMD GPU drivers
must be installed.
The NVIDIA GPU Driver Extension installs appropriate NVIDIA CUDA or GRID drivers on a Windows N -series
VM. Install or manage the extension using the Azure portal or tools such as Azure PowerShell or Azure Resource
Manager templates. See the NVIDIA GPU Driver Extension documentation for supported operating systems and
deployment steps. For general information about VM extensions, see Azure virtual machine extensions and
features.
If you choose to install NVIDIA GPU drivers manually, see N -series GPU driver setup for Windows for supported
operating systems, drivers, installation, and verification steps.
To install AMD GPU drivers manually, see N -series AMD GPU driver setup for Windows for supported operating
systems, drivers, installation, and verification steps.

Other sizes
General purpose
Memory optimized
Storage optimized
GPU optimized
High performance compute
Previous generations

Next steps
Learn more about how Azure compute units (ACU ) can help you compare compute performance across Azure
SKUs.
Install NVIDIA GPU drivers on N-series VMs running
Windows
11/13/2019 • 3 minutes to read • Edit Online

To take advantage of the GPU capabilities of Azure N -series VMs running Windows, NVIDIA GPU drivers must be
installed. The NVIDIA GPU Driver Extension installs appropriate NVIDIA CUDA or GRID drivers on an N -series
VM. Install or manage the extension using the Azure portal or tools such as Azure PowerShell or Azure Resource
Manager templates. See the NVIDIA GPU Driver Extension documentation for supported operating systems and
deployment steps.
If you choose to install GPU drivers manually, this article provides supported operating systems, drivers, and
installation and verification steps. Manual driver setup information is also available for Linux VMs.
For basic specs, storage capacities, and disk details, see GPU Windows VM sizes.

Supported operating systems and drivers


NVIDIA Tesla (CUDA ) drivers
NVIDIA Tesla (CUDA) drivers for NC, NCv2, NCv3, ND, and NDv2-series VMs (optional for NV -series) are
supported only on the operating systems listed in the following table. Driver download links are current at time of
publication. For the latest drivers, visit the NVIDIA website.

TIP
As an alternative to manual CUDA driver installation on a Windows Server VM, you can deploy an Azure Data Science Virtual
Machine image. The DSVM editions for Windows Server 2016 pre-install NVIDIA CUDA drivers, the CUDA Deep Neural
Network Library, and other tools.

OS DRIVER

Windows Server 2016 398.75 (.exe)

Windows Server 2012 R2 398.75 (.exe)

NVIDIA GRID drivers


Microsoft redistributes NVIDIA GRID driver installers for NV and NVv3-series VMs used as virtual workstations
or for virtual applications. Install only these GRID drivers on Azure NV -series VMs, only on the operating systems
listed in the following table. These drivers include licensing for GRID Virtual GPU Software in Azure. You do not
need to set up a NVIDIA vGPU software license server.
Please note that the Nvidia extension will always install the latest driver. We provide links to the previous version
here for customers, who have dependency on an older version.
For Windows Server 2019, Windows Server 2016, and Windows 10(up to build 1909):
GRID 10.1 (442.06) (.exe)
GRID 10.0 (441.66) (.exe)
For Windows Server 2012 R2, Windows Server 2008 R2, Windows 8, and Windows 7:
GRID 10.1 (442.06) (.exe)
GRID 10.0 (441.66) (.exe)

Driver installation
1. Connect by Remote Desktop to each N -series VM.
2. Download, extract, and install the supported driver for your Windows operating system.
After GRID driver installation on a VM, a restart is required. After CUDA driver installation, a restart is not
required.

Verify driver installation


Please note that the Nvidia Control panel is only accessible with the GRID driver installation. If you have installed
CUDA drivers then the Nvidia control panel will not be visible.
You can verify driver installation in Device Manager. The following example shows successful configuration of the
Tesla K80 card on an Azure NC VM.

To query the GPU device state, run the nvidia-smi command-line utility installed with the driver.
1. Open a command prompt and change to the C:\Program Files\NVIDIA Corporation\NVSMI directory.
2. Run nvidia-smi . If the driver is installed, you will see output similar to the following. The GPU -Util shows
0% unless you are currently running a GPU workload on the VM. Your driver version and GPU details may
be different from the ones shown.
RDMA network connectivity
RDMA network connectivity can be enabled on RDMA-capable N -series VMs such as NC24r deployed in the
same availability set or in a single placement group in a virtual machine scale set. The HpcVmDrivers extension
must be added to install Windows network device drivers that enable RDMA connectivity. To add the VM extension
to an RDMA-enabled N -series VM, use Azure PowerShell cmdlets for Azure Resource Manager.
To install the latest version 1.1 HpcVMDrivers extension on an existing RDMA-capable VM named myVM in the
West US region:

Set-AzVMExtension -ResourceGroupName "myResourceGroup" -Location "westus" -VMName "myVM" -ExtensionName


"HpcVmDrivers" -Publisher "Microsoft.HpcCompute" -Type "HpcVmDrivers" -TypeHandlerVersion "1.1"

For more information, see Virtual machine extensions and features for Windows.
The RDMA network supports Message Passing Interface (MPI) traffic for applications running with Microsoft MPI
or Intel MPI 5.x.

Next steps
Developers building GPU -accelerated applications for the NVIDIA Tesla GPUs can also download and install
the latest CUDA Toolkit. For more information, see the CUDA Installation Guide.
Install AMD GPU drivers on N-series VMs running
Windows
2/12/2020 • 2 minutes to read • Edit Online

To take advantage of the GPU capabilities of the new Azure NVv4 series VMs running Windows, AMD GPU
drivers must be installed. The AMD driver extension will be available in the coming weeks. This article provides
supported operating systems, drivers, and manual installation and verification steps.
For basic specs, storage capacities, and disk details, see GPU Windows VM sizes.

Supported operating systems and drivers


OS DRIVER

Windows 10 EVD - Build 1903 19.Q4.1 (.exe)

Windows 10 - Build 1809

Windows Server 2016

Windows Server 2019

Driver installation
1. Connect by Remote Desktop to each NVv4-series VM.
2. Download and extract the driver setup files. Navigate to the folder and run 'setup.exe' to install the
supported driver for your Windows operating system.

Verify driver installation


You can verify driver installation in Device Manager. The following example shows successful configuration of the
Radeon Instinct MI25 card on an Azure NVv4 VM.
You can use dxdiag to verify the GPU display properties including the video RAM. The following example shows a
1/8th partition of the Radeon Instinct MI25 card on an Azure NVv4 VM.
High performance compute VM sizes
2/20/2020 • 6 minutes to read • Edit Online

Azure H-series virtual machines (VMs) are designed to deliver leadership-class performance, MPI
scalability, and cost efficiency for a variety of real-world HPC workloads.
HBv2-series VMs feature 200 Gb/sec Mellanox HDR InfiniBand, while both HB and HC -series VMs feature
100 Gb/sec Mellanox EDR InfiniBand. Each of these VM types are connected in a non-blocking fat tree for
optimized and consistent RDMA performance. HBv2 VMs support Adaptive Routing and the Dynamic
Connected Transport (DCT, in additional to standard RC and UD transports). These features enhance
application performance, scalability, and consistency, and usage of them is strongly recommended.
HB -series VMs are optimized for applications driven by memory bandwidth, such as fluid dynamics, explicit
finite element analysis, and weather modeling. HB VMs feature 60 AMD EPYC 7551 processor cores, 4 GB
of RAM per CPU core, and no hyperthreading. The AMD EPYC platform provides more than 260 GB/sec of
memory bandwidth.
HC -series VMs are optimized for applications driven by dense computation, such as implicit finite element
analysis, molecular dynamics, and computational chemistry. HC VMs feature 44 Intel Xeon Platinum 8168
processor cores, 8 GB of RAM per CPU core, and no hyperthreading. The Intel Xeon Platinum platform
supports Intel’s rich ecosystem of software tools such as the Intel Math Kernel Library.
H-series VMs are optimized for applications driven by high CPU frequencies or large memory per core
requirements. H-series VMs feature 8 or 16 Intel Xeon E5 2667 v3 processor cores, 7 or 14 GB of RAM per
CPU core, and no hyperthreading. H-series features 56 Gb/sec Mellanox FDR InfiniBand in a non-blocking
fat tree configuration for consistent RDMA performance. H-series VMs support Intel MPI 5.x and MS -MPI.

Deployment considerations
Azure subscription – To deploy more than a few compute-intensive instances, consider a pay-as-
you-go subscription or other purchase options. If you're using an Azure free account, you can use
only a limited number of Azure compute cores.
Pricing and availability - These VM sizes are offered only in the Standard pricing tier. Check
Products available by region for availability in Azure regions.
Cores quota – You might need to increase the cores quota in your Azure subscription from the
default value. Your subscription might also limit the number of cores you can deploy in certain VM
size families, including the H-series. To request a quota increase, open an online customer support
request at no charge. (Default limits may vary depending on your subscription category.)

NOTE
Contact Azure Support if you have large-scale capacity needs. Azure quotas are credit limits, not capacity
guarantees. Regardless of your quota, you are only charged for cores that you use.

Virtual network – An Azure virtual network is not required to use the compute-intensive instances.
However, for many deployments you need at least a cloud-based Azure virtual network, or a site-to-
site connection if you need to access on-premises resources. When needed, create a new virtual
network to deploy the instances. Adding compute-intensive VMs to a virtual network in an affinity
group is not supported.
Resizing – Because of their specialized hardware, you can only resize compute-intensive instances
within the same size family (H-series or compute-intensive A-series). For example, you can only
resize an H-series VM from one H-series size to another. In addition, resizing from a non-compute-
intensive size to a compute-intensive size is not supported.

RDMA-capable instances
A subset of the compute-intensive instances (A8, A9, H16r, H16mr, HB and HC ) feature a network interface
for remote direct memory access (RDMA) connectivity. Selected N -series sizes designated with 'r' such as
the NC24rs configurations (NC24rs_v2 and NC24rs_v3) are also RDMA-capable. This interface is in
addition to the standard Azure network interface available to other VM sizes.
This interface allows the RDMA-capable instances to communicate over an InfiniBand (IB ) network,
operating at EDR rates for HB, HC, FDR rates for H16r, H16mr, and RDMA-capable N -series virtual
machines, and QDR rates for A8 and A9 virtual machines. These RDMA capabilities can boost the
scalability and performance of certain Message Passing Interface (MPI) applications. For more information
on speed, see the details in the tables on this page.

NOTE
In Azure, IP over IB is only supported on the SR-IOV enabled VMs (SR-IOV for InfiniBand, currently HB and HC).
RDMA over IB is supported for all RDMA-capable instances.

Operating system - Windows Server 2016 on all the above HPC series VMs. Windows Server 2012
R2, Windows Server 2012 are also supported on the non-SR -IOV enabled VMs (hence excluding HB
and HC ).
MPI - The SR -IOV enabled VM sizes on Azure (HB, HC ) allow almost any flavor of MPI to be used
with Mellanox OFED. On non-SR -IOV enabled VMs, supported MPI implementations use the
Microsoft Network Direct (ND ) interface to communicate between instances. Hence, only Microsoft
MPI (MS -MPI) 2012 R2 or later and Intel MPI 5.x versions are supported. Later versions (2017,
2018) of the Intel MPI runtime library may or may not be compatible with the Azure RDMA drivers.
InfiniBandDriverWindows VM extension - On RDMA-capable VMs, add the
InfiniBandDriverWindows extension to enable InfiniBand. This Windows VM extension installs
Windows Network Direct drivers (on non-SR -IOV VMs) or Mellanox OFED drivers (on SR -IOV
VMs) for RDMA connectivity. In certain deployments of A8 and A9 instances, the HpcVmDrivers
extension is added automatically. Note that the HpcVmDrivers VM extension is being deprecated; it
will not be updated. To add the VM extension to a VM, you can use Azure PowerShell cmdlets.
The following command installs the latest version 1.0 InfiniBandDriverWindows extension on an
existing RDMA-capable VM named myVM deployed in the resource group named
myResourceGroup in the West US region:

Set-AzVMExtension -ResourceGroupName "myResourceGroup" -Location "westus" -VMName "myVM" -


ExtensionName "InfiniBandDriverWindows" -Publisher "Microsoft.HpcCompute" -Type
"InfiniBandDriverWindows" -TypeHandlerVersion "1.0"

Alternatively, VM extensions can be included in Azure Resource Manager templates for easy
deployment, with the following JSON element:
"properties":{
"publisher": "Microsoft.HpcCompute",
"type": "InfiniBandDriverWindows",
"typeHandlerVersion": "1.0",
}

The following command installs the latest version 1.0 InfiniBandDriverWindows extension on all
RDMA-capable VMs in an existing VM scale set named myVMSS deployed in the resource group
named myResourceGroup:

$VMSS = Get-AzVmss -ResourceGroupName "myResourceGroup" -VMScaleSetName "myVMSS"


Add-AzVmssExtension -VirtualMachineScaleSet $VMSS -Name "InfiniBandDriverWindows" -Publisher
"Microsoft.HpcCompute" -Type "InfiniBandDriverWindows" -TypeHandlerVersion "1.0"
Update-AzVmss -ResourceGroupName "myResourceGroup" -VMScaleSetName "MyVMSS" -
VirtualMachineScaleSet $VMSS
Update-AzVmssInstance -ResourceGroupName "myResourceGroup" -VMScaleSetName "myVMSS" -InstanceId
"*"

For more information, see Virtual machine extensions and features. You can also work with
extensions for VMs deployed in the classic deployment model.
RDMA network address space - The RDMA network in Azure reserves the address space
172.16.0.0/16. To run MPI applications on instances deployed in an Azure virtual network, make sure
that the virtual network address space does not overlap the RDMA network.

Cluster configuration options


Azure provides several options to create clusters of Windows HPC VMs that can communicate using the
RDMA network, including:
Virtual machines - Deploy the RDMA-capable HPC VMs in the same availability set (when you use
the Azure Resource Manager deployment model). If you use the classic deployment model, deploy
the VMs in the same cloud service.
Virtual machine scale sets - In a virtual machine scale set, ensure that you limit the deployment to
a single placement group. For example, in a Resource Manager template, set the
singlePlacementGroup property to true .

MPI among virtual machines - If MPI communication if required between virtual machines (VMs),
ensure that the VMs are in the same availability set or the virtual machine same scale set.
Azure CycleCloud - Create an HPC cluster in Azure CycleCloud to run MPI jobs on Windows
nodes.
Azure Batch - Create an Azure Batch pool to run MPI workloads on Windows Server compute
nodes. For more information, see Use RDMA-capable or GPU -enabled instances in Batch pools. Also
see the Batch Shipyard project, for running container-based workloads on Batch.
Microsoft HPC Pack - HPC Pack includes a runtime environment for MS -MPI that uses the Azure
RDMA network when deployed on RDMA-capable Linux VMs. For example deployments, see Set up
a Linux RDMA cluster with HPC Pack to run MPI applications.

Other sizes
General purpose
Compute optimized
Memory optimized
Storage optimized
GPU optimized
Previous generations

Next steps
For checklists to use the compute-intensive instances with HPC Pack on Windows Server, see Set up
a Linux RDMA cluster with HPC Pack to run MPI applications.
To use compute-intensive instances when running MPI applications with Azure Batch, see Use multi-
instance tasks to run Message Passing Interface (MPI) applications in Azure Batch.
Learn more about how Azure compute units (ACU ) can help you compare compute performance
across Azure SKUs.
H-series
2/20/2020 • 2 minutes to read • Edit Online

H-series VMs are optimized for applications driven by high CPU frequencies or large memory per core
requirements. H-series VMs feature 8 or 16 Intel Xeon E5 2667 v3 processor cores, up to 14 GB of RAM per CPU
core, and no hyperthreading. H-series features 56 Gb/sec Mellanox FDR InfiniBand in a non-blocking fat tree
configuration for consistent RDMA performance. H-series VMs support Intel MPI 5.x and MS -MPI.
ACU: 290-300
Premium Storage: Not Supported
Premium Storage Caching: Not Supported

ALL- SINGL
CORE E- RDM
MEM BASE S CORE A
ORY CPU FREQ FREQ PERF
BAND FREQ UENC UENC ORM TEMP MAX
PROC MEM WIDT UENC Y Y ANCE MPI STOR MAX ETHE
ESSO ORY H Y (GHZ, (GHZ, (GB/S SUPP AGE DATA RNET
SIZE VCPU R (GB) GB/S (GHZ) PEAK) PEAK) ) ORT (GB) DISKS NICS

Stand 8 Intel 56 40 3.2 3.3 3.6 - Intel 1000 32 2


ard_ Xeon 5.x,
H8 E5 MS-
2667 MPI
v3

Stand 16 Intel 112 80 3.2 3.3 3.6 - Intel 2000 64 4


ard_ Xeon 5.x,
H16 E5 MS-
2667 MPI
v3

Stand 8 Intel 112 40 3.2 3.3 3.6 - Intel 1000 32 2


ard_ Xeon 5.x,
H8m E5 MS-
2667 MPI
v3

Stand 16 Intel 224 80 3.2 3.3 3.6 - Intel 2000 64 4


ard_ Xeon 5.x,
H16 E5 MS-
m 2667 MPI
v3

Stand 16 Intel 112 80 3.2 3.3 3.6 56 Intel 2000 64 4


ard_ Xeon 5.x,
H16r E5 MS-
1 2667 MPI
v3
ALL- SINGL
CORE E- RDM
MEM BASE S CORE A
ORY CPU FREQ FREQ PERF
BAND FREQ UENC UENC ORM TEMP MAX
PROC MEM WIDT UENC Y Y ANCE MPI STOR MAX ETHE
ESSO ORY H Y (GHZ, (GHZ, (GB/S SUPP AGE DATA RNET
SIZE VCPU R (GB) GB/S (GHZ) PEAK) PEAK) ) ORT (GB) DISKS NICS

Stand 16 Intel 224 80 3.2 3.3 3.6 56 Intel 2000 64 4


ard_ Xeon 5.x,
H16 E5 MS-
mr 1 2667 MPI
v3

1 For MPI applications, dedicated RDMA backend network is enabled by FDR InfiniBand network.

Size table definitions


Storage capacity is shown in units of GiB or 1024^3 bytes. When you compare disks measured in GB
(1000^3 bytes) to disks measured in GiB (1024^3) remember that capacity numbers given in GiB may
appear smaller. For example, 1023 GiB = 1098.4 GB.
Disk throughput is measured in input/output operations per second (IOPS ) and MBps where MBps = 10^6
bytes/sec.
Data disks can operate in cached or uncached modes. For cached data disk operation, the host cache mode
is set to ReadOnly or ReadWrite. For uncached data disk operation, the host cache mode is set to None.
If you want to get the best performance for your VMs, you should limit the number of data disks to two
disks per vCPU.
Expected network bandwidth is the maximum aggregated bandwidth allocated per VM type across all
NICs, for all destinations. For more information, see Virtual machine network bandwidth.
Upper limits aren't guaranteed. Limits offer guidance for selecting the right VM type for the intended
application. Actual network performance will depend on several factors including network congestion,
application loads, and network settings. For information on optimizing network throughput, see Optimize
network throughput for Azure virtual machines. To achieve the expected network performance on Linux or
Windows, you may need to select a specific version or optimize your VM. For more information, see
Bandwidth/Throughput testing (NTTTCP ).

Other sizes
General purpose
Memory optimized
Storage optimized
GPU optimized
High performance compute
Previous generations

Next steps
Learn more about how Azure compute units (ACU ) can help you compare compute performance across Azure
SKUs.
HB-series
2/20/2020 • 2 minutes to read • Edit Online

HB -series VMs are optimized for applications driven by memory bandwidth, such as fluid dynamics, explicit finite
element analysis, and weather modeling. HB VMs feature 60 AMD EPYC 7551 processor cores, 4 GB of RAM per
CPU core, and no simultaneous multithreading. An HB VM provides up to 260 GB/sec of memory bandwidth.
ACU: 199-216
Premium Storage: Supported
Premium Storage Caching: Supported

ALL- SINGL
CORE E- RDM
MEM BASE S CORE A
ORY CPU FREQ FREQ PERF
BAND FREQ UENC UENC ORM TEMP MAX
PROC MEM WIDT UENC Y Y ANCE MPI STOR MAX ETHE
ESSO ORY H Y (GHZ, (GHZ, (GB/S SUPP AGE DATA RNET
SIZE VCPU R (GB) GB/S (GHZ) PEAK) PEAK) ) ORT (GB) DISKS NICS

Stand 60 AMD 240 263 2.0 2.55 2.55 100 All 700 4 1
ard_ EPYC
HB60 7551
rs

Size table definitions


Storage capacity is shown in units of GiB or 1024^3 bytes. When you compare disks measured in GB
(1000^3 bytes) to disks measured in GiB (1024^3) remember that capacity numbers given in GiB may
appear smaller. For example, 1023 GiB = 1098.4 GB.
Disk throughput is measured in input/output operations per second (IOPS ) and MBps where MBps = 10^6
bytes/sec.
Data disks can operate in cached or uncached modes. For cached data disk operation, the host cache mode
is set to ReadOnly or ReadWrite. For uncached data disk operation, the host cache mode is set to None.
If you want to get the best performance for your VMs, you should limit the number of data disks to two
disks per vCPU.
Expected network bandwidth is the maximum aggregated bandwidth allocated per VM type across all
NICs, for all destinations. For more information, see Virtual machine network bandwidth.
Upper limits aren't guaranteed. Limits offer guidance for selecting the right VM type for the intended
application. Actual network performance will depend on several factors including network congestion,
application loads, and network settings. For information on optimizing network throughput, see Optimize
network throughput for Azure virtual machines. To achieve the expected network performance on Linux or
Windows, you may need to select a specific version or optimize your VM. For more information, see
Bandwidth/Throughput testing (NTTTCP ).

Other sizes
General purpose
Memory optimized
Storage optimized
GPU optimized
High performance compute
Previous generations

Next steps
Learn more about how Azure compute units (ACU ) can help you compare compute performance across Azure
SKUs.
HBv2-series
2/20/2020 • 2 minutes to read • Edit Online

HBv2-series VMs are optimized for applications driven by memory bandwidth, such as fluid dynamics, finite
element analysis, and reservoir simulation. HBv2 VMs feature 120 AMD EPYC 7742 processor cores, 4 GB of
RAM per CPU core, and no simultaneous multithreading. Each HBv2 VM provides up to 340 GB/sec of memory
bandwidth, and up to 4 teraFLOPS of FP64 compute.
Premium Storage: Supported

ALL- SINGL
CORE E- RDM
MEM BASE S CORE A
ORY CPU FREQ FREQ PERF
BAND FREQ UENC UENC ORM TEMP MAX
PROC MEM WIDT UENC Y Y ANCE MPI STOR MAX ETHER
ESSO ORY H Y (GHZ, (GHZ, (GB/S SUPP AGE DATA NET
SIZE VCPU R (GB) GB/S (GHZ) PEAK) PEAK) ) ORT (GB) DISKS NICS

Stand 120 AMD 480 350 2.45 3.1 3.3 200 All 480 8 1
ard_ EPYC +
HB12 7V12 960
0rs_v
2

Size table definitions


Storage capacity is shown in units of GiB or 1024^3 bytes. When you compare disks measured in GB
(1000^3 bytes) to disks measured in GiB (1024^3) remember that capacity numbers given in GiB may
appear smaller. For example, 1023 GiB = 1098.4 GB.
Disk throughput is measured in input/output operations per second (IOPS ) and MBps where MBps = 10^6
bytes/sec.
Data disks can operate in cached or uncached modes. For cached data disk operation, the host cache mode
is set to ReadOnly or ReadWrite. For uncached data disk operation, the host cache mode is set to None.
If you want to get the best performance for your VMs, you should limit the number of data disks to two
disks per vCPU.
Expected network bandwidth is the maximum aggregated bandwidth allocated per VM type across all
NICs, for all destinations. For more information, see Virtual machine network bandwidth.
Upper limits aren't guaranteed. Limits offer guidance for selecting the right VM type for the intended
application. Actual network performance will depend on several factors including network congestion,
application loads, and network settings. For information on optimizing network throughput, see Optimize
network throughput for Azure virtual machines. To achieve the expected network performance on Linux or
Windows, you may need to select a specific version or optimize your VM. For more information, see
Bandwidth/Throughput testing (NTTTCP ).

Other sizes
General purpose
Memory optimized
Storage optimized
GPU optimized
High performance compute
Previous generations

Next steps
Learn more about how Azure compute units (ACU ) can help you compare compute performance across Azure
SKUs.
HC-series
2/20/2020 • 2 minutes to read • Edit Online

HC -series VMs are optimized for applications driven by dense computation, such as implicit finite element
analysis, molecular dynamics, and computational chemistry. HC VMs feature 44 Intel Xeon Platinum 8168
processor cores, 8 GB of RAM per CPU core, and no hyperthreading. The Intel Xeon Platinum platform supports
Intel’s rich ecosystem of software tools such as the Intel Math Kernel Library.
ACU: 297-315
Premium Storage: Supported
Premium Storage Caching: Supported

ALL- SINGL
CORE E- RDM
MEM BASE S CORE A
ORY CPU FREQ FREQ PERF
BAND FREQ UENC UENC ORM TEMP MAX
PROC MEM WIDT UENC Y Y ANCE MPI STOR MAX ETHE
ESSO ORY H Y (GHZ, (GHZ, (GB/S SUPP AGE DATA RNET
SIZE VCPU R (GB) GB/S (GHZ) PEAK) PEAK) ) ORT (GB) DISKS NICS

Stand 44 Intel 352 191 2.7 3.4 3.7 100 All 700 4 1
ard_ Xeon
HC44 Platin
rs um
8168

Size table definitions


Storage capacity is shown in units of GiB or 1024^3 bytes. When you compare disks measured in GB
(1000^3 bytes) to disks measured in GiB (1024^3) remember that capacity numbers given in GiB may
appear smaller. For example, 1023 GiB = 1098.4 GB.
Disk throughput is measured in input/output operations per second (IOPS ) and MBps where MBps = 10^6
bytes/sec.
Data disks can operate in cached or uncached modes. For cached data disk operation, the host cache mode
is set to ReadOnly or ReadWrite. For uncached data disk operation, the host cache mode is set to None.
If you want to get the best performance for your VMs, you should limit the number of data disks to two
disks per vCPU.
Expected network bandwidth is the maximum aggregated bandwidth allocated per VM type across all
NICs, for all destinations. For more information, see Virtual machine network bandwidth.
Upper limits aren't guaranteed. Limits offer guidance for selecting the right VM type for the intended
application. Actual network performance will depend on several factors including network congestion,
application loads, and network settings. For information on optimizing network throughput, see Optimize
network throughput for Azure virtual machines. To achieve the expected network performance on Linux or
Windows, you may need to select a specific version or optimize your VM. For more information, see
Bandwidth/Throughput testing (NTTTCP ).

Other sizes
General purpose
Memory optimized
Storage optimized
GPU optimized
High performance compute
Previous generations

Next steps
Learn more about how Azure compute units (ACU ) can help you compare compute performance across Azure
SKUs.
Save costs with Azure Reserved VM Instances
11/12/2019 • 7 minutes to read • Edit Online

When you commit to an Azure reserved VM instance you can save money. The reservation discount is applied
automatically to the number of running virtual machines that match the reservation scope and attributes. You don't
need to assign a reservation to a virtual machine to get the discounts. A reserved instance purchase covers only the
compute part of your VM usage. For Windows VMs, the usage meter is split into two separate meters. There's a
compute meter, which is same as the Linux meter, and a Windows IP meter. The charges that you see when you
make the purchase are only for the compute costs. Charges don't include Windows software costs. For more
information about software costs, see Software costs not included with Azure Reserved VM Instances.

Determine the right VM size before you buy


Before you buy a reservation, you should determine the size of the VM that you need. The following sections will
help you determine the right VM size.
Use reservation recommendations
You can use reservation recommendations to help determine the reservations you should purchase.
Purchase recommendations and recommended quantity are show when you purchase a VM reserved instance
in the Azure portal.
Azure Advisor provides purchase recommendations for individual subscriptions.
You can use the APIs to get purchase recommendations for both shared scope and single subscription scope.
For more information, see Reserved instance purchase recommendation APIs for enterprise customers.
For Enterprise Agreement (EA) and Microsoft Customer Agreement (MCA) customers, purchase
recommendations for shared and single subscription scopes are available with the Azure Consumption Insights
Power BI content pack.
Services that get VM reservation discounts
Your VM reservations can apply to VM usage emitted from multiple services - not just for your VM deployments.
Resources that get reservation discounts change depending on the instance size flexibility setting.
Instance size flexibility setting
The instance size flexibility setting determines which services get the reserved instance discounts.
Whether the setting is on or off, reservation discounts automatically apply to any matching VM usage when the
ConsumedService is Microsoft.Compute . So, check your usage data for the ConsumedService value. Some examples
include:
Virtual machines
Virtual machine scale sets
Container service
Azure Batch deployments (in user subscriptions mode)
Azure Kubernetes Service (AKS )
Service Fabric
When the setting is on, reservation discounts automatically apply to matching VM usage when the
ConsumedService is any of the following items:
Microsoft.Compute
Microsoft.ClassicCompute
Microsoft.Batch
Microsoft.MachineLearningServices
Microsoft.Kusto
Check the ConsumedService value in your usage data to determine if the usage is eligible for reservation discounts.
For more information about instance size flexibility, see Virtual machine size flexibility with Reserved VM Instances.
Analyze your usage information
Analyze your usage information to help determine which reservations you should purchase.
Usage data is available in the usage file and APIs. Use them together to determine which reservation to purchase.
Check for VM instances that have high usage on daily basis to determine the quantity of reservations to purchase.
Avoid the Meter subcategory and Product fields in usage data. They don't distinguish between VM sizes that use
premium storage. If you use these fields to determine the VM size for reservation purchase, you may buy the
wrong size. Then you won't get the reservation discount you expect. Instead, refer to the AdditionalInfo field in
your usage file or usage API to determine the correct VM size.
Purchase restriction considerations
Reserved VM Instances are available for most VM sizes with some exceptions. Reservation discounts don't apply
for the following VMs:
VM series - A-series, Av2-series, or G -series.
Preview or Promo VMs - Any VM -series or size that is in preview or uses promotional meter.
Clouds - Reservations aren't available for purchase in Germany or China regions.
Insufficient quota - A reservation that is scoped to a single subscription must have vCPU quota available
in the subscription for the new RI. For example, if the target subscription has a quota limit of 10 vCPUs for
D -Series, then you can't buy a reservation for 11 Standard_D1 instances. The quota check for reservations
includes the VMs already deployed in the subscription. For example, if the subscription has a quota of 10
vCPUs for D -Series and has two standard_D1 instances deployed, then you can buy a reservation for 10
standard_D1 instances in this subscription. You can create quote increase request to resolve this issue.
Capacity restrictions - In rare circumstances, Azure limits the purchase of new reservations for subset of
VM sizes, because of low capacity in a region.

Buy a Reserved VM Instance


You can buy a reserved VM instance in the Azure portal. Pay for the reservation up front or with monthly
payments. These requirements apply to buying a reserved VM instance:
You must be in an Owner role for at least one EA subscription or a subscription with a pay-as-you-go rate.
For EA subscriptions, the Add Reserved Instances option must be enabled in the EA portal. Or, if that setting
is disabled, you must be an EA Admin for the subscription.
For the Cloud Solution Provider (CSP ) program, only the admin agents or sales agents can buy reservations.
To buy an instance:
1. Sign in to the Azure portal.
2. Select All services > Reservations.
3. Select Add to purchase a new reservation and then click Virtual machine.
4. Enter required fields. Running VM instances that match the attributes you select qualify to get the reservation
discount. The actual number of your VM instances that get the discount depend on the scope and quantity
selected.
If you have an EA agreement, you can use the Add more option to quickly add additional instances. The option
isn't available for other subscription types.

FIELD DESCRIPTION

Subscription The subscription used to pay for the reservation. The payment
method on the subscription is charged the costs for the
reservation. The subscription type must be an enterprise
agreement (offer numbers: MS-AZR-0017P or MS-AZR-
0148P) or Microsoft Customer Agreement or an individual
subscription with pay-as-you-go rates (offer numbers: MS-
AZR-0003P or MS-AZR-0023P). The charges are deducted
from the monetary commitment balance, if available, or
charged as overage. For a subscription with pay-as-you-go
rates, the charges are billed to the credit card or invoice
payment method on the subscription.

Scope The reservation’s scope can cover one subscription or multiple


subscriptions (shared scope). If you select:
Single resource group scope — Applies the
reservation discount to the matching resources in the
selected resource group only.
Single subscription scope — Applies the reservation
discount to the matching resources in the selected
subscription.
Shared scope — Applies the reservation discount to
matching resources in eligible subscriptions that are in
the billing context. For EA customers, the billing context
is the enrollment. For individual subscriptions with pay-
as-you-go rates, the billing scope is all eligible
subscriptions created by the account administrator.

Region The Azure region that’s covered by the reservation.

VM Size The size of the VM instances.

Optimize for VM instance size flexibility is selected by default. Click


Advanced settings to change the instance size flexibility value
to apply the reservation discount to other VMs in the same
VM size group. Capacity priority prioritizes data center
capacity for your deployments. It offers additional confidence
in your ability to launch the VM instances when you need
them. Capacity priority is only available when the reservation
scope is single subscription.

Term One year or three years.

Quantity The number of instances being purchased within the


reservation. The quantity is the number of running VM
instances that can get the billing discount. For example, if you
are running 10 Standard_D2 VMs in the East US, then you
would specify quantity as 10 to maximize the benefit for all
running VMs.

Usage data and reservation utilization


Your usage data has an effective price of zero for the usage that gets a reservation discount. You can see which VM
instance received the reservation discount for each reservation.
For more information about how reservation discounts appear in usage data, see Understand Azure reservation
usage for your Enterprise enrollment if you are an EA customer. If you have an individual subscription, see
Understand Azure reservation usage for your Pay-As-You-Go subscription.

Change a reservation after purchase


You can make the following types of changes to a reservation after purchase:
Update reservation scope
Instance size flexibility (if applicable)
Ownership
You can also split a reservation into smaller chunks and merge already split reservations. None of the changes
cause a new commercial transaction or change the end date of the reservation.
You can't make the following types of changes after purchase, directly:
An existing reservation’s region
SKU
Quantity
Duration
However, you can exchange a reservation if you want to make changes.

Cancel, exchange, or refund reservations


You can cancel, exchange, or refund reservations with certain limitations. For more information, see Self-service
exchanges and refunds for Azure Reservations.

Need help? Contact us.


If you have questions or need help, create a support request.

Next steps
To learn how to manage a reservation, see Manage Azure Reservations.
To learn more about Azure Reservations, see the following articles:
What are Azure Reservations?
Manage Reservations in Azure
Understand how the reservation discount is applied
Understand reservation usage for a subscription with pay-as-you-go rates
Understand reservation usage for your Enterprise enrollment
Windows software costs not included with reservations
Azure Reservations in Partner Center Cloud Solution Provider (CSP ) program
2 minutes to read
Virtual machine size flexibility with Reserved VM
Instances
2/19/2020 • 2 minutes to read • Edit Online

When you buy a Reserved VM Instance, you can choose to optimize for instance size flexibility or capacity priority.
For more information about setting or changing the optimize setting for reserved VM instances, see Change the
optimize setting for reserved VM instances.
With a reserved virtual machine instance that's optimized for instance size flexibility, the reservation you buy can
apply to the virtual machines (VMs) sizes in the same instance size flexibility group. For example, if you buy a
reservation for a VM size that's listed in the DSv2 Series, like Standard_DS5_v2, the reservation discount can apply
to the other four sizes that are listed in that same instance size flexibility group:
Standard_DS1_v2
Standard_DS2_v2
Standard_DS3_v2
Standard_DS4_v2
But that reservation discount doesn't apply to VMs sizes that are listed in different instance size flexibility groups,
like SKUs in DSv2 Series High Memory: Standard_DS11_v2, Standard_DS12_v2, and so on.
Within the instance size flexibility group, the number of VMs the reservation discount applies to depends on the
VM size you pick when you buy a reservation. It also depends on the sizes of the VMs that you have running. The
ratio column compares the relative footprint for each VM size in that instance size flexibility group. Use the ratio
value to calculate how the reservation discount applies to the VMs you have running.

Examples
The following examples use the sizes and ratios in the DSv2-series table.
You buy a reserved VM instance with the size Standard_DS4_v2 where the ratio or relative footprint compared to
the other sizes in that series is 8.
Scenario 1: Run eight Standard_DS1_v2 sized VMs with a ratio of 1. Your reservation discount applies to all
eight of those VMs.
Scenario 2: Run two Standard_DS2_v2 sized VMs with a ratio of 2 each. Also run a Standard_DS3_v2 sized VM
with a ratio of 4. The total footprint is 2+2+4=8. So your reservation discount applies to all three of those VMs.
Scenario 3: Run one Standard_DS5_v2 with a ratio of 16. Your reservation discount applies to half that VM's
compute cost.
The following sections show what sizes are in the same size series group when you buy a reserved VM instance
optimized for instance size flexibility.

Instance size flexibility ratio for VMs


CSV below has the instance size flexibility groups, ArmSkuName and the ratios.
Instance size flexibility ratios
We will keep the file URL and the schema fixed so you can consume this file programmatically. The data will also be
available through API soon.
Preview: Use Spot VMs in Azure
12/3/2019 • 4 minutes to read • Edit Online

Using Spot VMs allows you to take advantage of our unused capacity at a significant cost savings. At any point in
time when Azure needs the capacity back, the Azure infrastructure will evict Spot VMs. Therefore, Spot VMs are
great for workloads that can handle interruptions like batch processing jobs, dev/test environments, large compute
workloads, and more.
The amount of available capacity can vary based on size, region, time of day, and more. When deploying Spot
VMs, Azure will allocate the VMs if there is capacity available, but there is no SLA for these VMs. A Spot VM offers
no high availability guarantees. At any point in time when Azure needs the capacity back, the Azure infrastructure
will evict Spot VMs with 30 seconds notice.

IMPORTANT
Spot instances are currently in public preview. This preview version is not recommended for production workloads. Certain
features might not be supported or might have constrained capabilities. For more information, see Supplemental Terms of
Use for Microsoft Azure Previews.

Eviction policy
VMs can be evicted based on capacity or the max price you set. For virtual machines, the eviction policy is set to
Deallocate which moves your evicted VMs to the stopped-deallocated state, allowing you to redeploy the evicted
VMs at a later time. However, reallocating Spot VMs will be dependent on there being available Spot capacity. The
deallocated VMs will count against your spot vCPU quota and you will be charged for your underlying disks.
Users can opt-in to receive in-VM notifications through Azure Scheduled Events. This will notify you if your VMs
are being evicted and you will have 30 seconds to finish any jobs and perform shutdown tasks prior to the eviction.

OPTION OUTCOME

Max price is set to >= the current price. VM is deployed if capacity and quota are available.

Max price is set to < the current price. The VM is not deployed. You will get an error message that
the max price needs to be >= current price.

Restarting a stop/deallocate VM if the max price is >= the If there is capacity and quota, then the VM is deployed.
current price

Restarting a stop/deallocate VM if the max price is < the You will get an error message that the max price needs to be
current price >= current price.

Price for the VM has gone up and is now > the max price. The VM gets evicted. You get a 30s notification before actual
eviction.

After eviction the price for the VM goes back to being < the The VM will not be automatically re-started. You can restart
max price. the VM yourself, and it will be charged at the current price.
OPTION OUTCOME

If the max price is set to -1 The VM will not be evicted for pricing reasons. The max price
will be the current price, up to the price for standard VMs. You
will never be charged above the standard price.

Changing the max price You need to deallocate the VM to change the max price.
Deallocate the VM, set t a new max price, then update the
VM.

Limitations
The following VM sizes are not supported for Spot VMs:
B -series
Promo versions of any size (like Dv2, NV, NC, H promo sizes)
Spot VMs can't currently use ephemeral OS disks.
Spot VMs can be deployed to any region, except Microsoft Azure China 21Vianet.

Pricing
Pricing for Spot VMs is variable, based on region and SKU. For more information, see VM pricing for Linux and
Windows.
With variable pricing, you have option to set a max price, in US dollars (USD ), using up to 5 decimal places. For
example, the value 0.98765 would be a max price of $0.98765 USD per hour. If you set the max price to be -1 , the
VM won't be evicted based on price. The price for the VM will be the current price for spot or the price for a
standard VM, which ever is less, as long as there is capacity and quota available.

Frequently asked questions


Q: Once created, is a Spot VM the same as regular standard VM?
A: Yes, except there is no SLA for Spot VMs and they can be evicted at any time.
Q: What to do when you get evicted, but still need capacity?
A: We recommend you use standard VMs instead of Spot VMs if you need capacity right away.
Q: How is quota managed for Spot VMs?
A: Spot VMs will have a separate quota pool. Spot quota will be shared between VMs and scale-set instances. For
more information, see Azure subscription and service limits, quotas, and constraints.
Q: Can I request for additional quota for Spot?
A: Yes, you will be able to submit the request to increase your quota for Spot VMs through the standard quota
request process.
Q: What channels support Spot VMs?
A: See the table below for Spot VM availability.

AZURE CHANNELS AZURE SPOT VMS AVAILABILITY

Enterprise Agreement Yes


AZURE CHANNELS AZURE SPOT VMS AVAILABILITY

Pay As You Go Yes

Cloud Service Provider (CSP) Contact your partner

Benefits Not available

Sponsored Not available

Free Trial Not available

Q: Where can I post questions?


A: You can post and tag your question with azure-spot at Q&A.

Next steps
Use the portal, CLI or PowerShell to deploy Spot VMs.
You can also deploy a scale set with Spot VM instances.
If you encounter an error, see Error codes.
Previous generations of virtual machine sizes
2/25/2020 • 11 minutes to read • Edit Online

This section provides information on previous generations of virtual machine sizes. These sizes can still be
used, but there are newer generations available.

F-series
F -series is based on the 2.4 GHz Intel Xeon® E5-2673 v3 (Haswell) processor, which can achieve clock
speeds as high as 3.1 GHz with the Intel Turbo Boost Technology 2.0. This is the same CPU performance
as the Dv2-series of VMs.
F -series VMs are an excellent choice for workloads that demand faster CPUs but do not need as much
memory or temporary storage per vCPU. Workloads such as analytics, gaming servers, web servers, and
batch processing will benefit from the value of the F -series.
ACU: 210 - 250
Premium Storage: Not Supported
Premium Storage caching: Not Supported

MAX TEMP
STORAGE MAX
THROUGHPU MAX DATA NICS/EXPECTE
TEMP T: IOPS/READ DISKS/THRO D NETWORK
STORAGE MBPS/WRITE UGHPUT: BANDWIDTH
SIZE VCPU MEMORY: GIB (SSD) GIB MBPS IOPS (MBPS)

Standard_F1 1 2 16 3000/46/23 4/4x500 2/750

Standard_F2 2 4 32 6000/93/46 8/8x500 2/1500

Standard_F4 4 8 64 12000/187/ 16/16x500 4/3000


93

Standard_F8 8 16 128 24000/375/ 32/32x500 8/6000


187

Standard_F1 16 32 256 48000/750/ 64/64x500 8/12000


6 375

Fs-series 1
The Fs-series provides all the advantages of the F -series, in addition to Premium storage.
ACU: 210 - 250
Premium Storage: Supported
Premium Storage caching: Supported
MAX
CACHED
AND TEMP
STORAGE
THROUGHP MAX MAX
UT: UNCACHED NICS/EXPEC
IOPS/MBPS DISK TED
TEMP (CACHE THROUGHP NETWORK
MEMORY: STORAGE MAX DATA SIZE IN UT: BANDWIDT
SIZE VCPU GIB (SSD) GIB DISKS GIB) IOPS/MBPS H (MBPS)

Standard_ 1 2 4 4 4000/32 3200/48 2/750


F1s (12)

Standard_ 2 4 8 8 8000/64 6400/96 2/1500


F2s (24)

Standard_ 4 8 16 16 16000/12 12800/19 4/3000


F4s 8 (48) 2

Standard_ 8 16 32 32 32000/25 25600/38 8/6000


F8s 6 (96) 4

Standard_ 16 32 64 64 64000/51 51200/76 8/12000


F16s 2 (192) 8

MBps = 10^6 bytes per second, and GiB = 1024^3 bytes.


1 The maximum disk throughput (IOPS or MBps) possible with a Fs series VM may be limited by the
number, size, and striping of the attached disk(s). For details, see designing for high performance for
Windows or Linux.

NVv2-series
Newer size recommendation: NVv3-series
The NVv2-series virtual machines are powered by NVIDIA Tesla M60 GPUs and NVIDIA GRID
technology with Intel Broadwell CPUs. These virtual machines are targeted for GPU accelerated graphics
applications and virtual desktops where customers want to visualize their data, simulate results to view,
work on CAD, or render and stream content. Additionally, these virtual machines can run single precision
workloads such as encoding and rendering. NVv2 virtual machines support Premium Storage and come
with twice the system memory (RAM ) when compared with its predecessor NV -series.
Each GPU in NVv2 instances comes with a GRID license. This license gives you the flexibility to use an NV
instance as a virtual workstation for a single user, or 25 concurrent users can connect to the VM for a
virtual application scenario.

VIRTUA
TEMP L VIRTUA
STORAG GPU MAX WORKS L
MEMOR E (SSD) MEMOR DATA MAX TATION APPLICA
SIZE VCPU Y: GIB GIB GPU Y: GIB DISKS NICS S TIONS

Standar 6 112 320 1 8 12 4 1 25


d_NV6s
_v2

Standar 12 224 640 2 16 24 8 2 50


d_NV1
2s_v2
VIRTUA
TEMP L VIRTUA
STORAG GPU MAX WORKS L
MEMOR E (SSD) MEMOR DATA MAX TATION APPLICA
SIZE VCPU Y: GIB GIB GPU Y: GIB DISKS NICS S TIONS

Standar 24 448 1280 4 32 32 8 4 100


d_NV2
4s_v2

Size table definitions


Storage capacity is shown in units of GiB or 1024^3 bytes. When you compare disks measured in
GB (1000^3 bytes) to disks measured in GiB (1024^3) remember that capacity numbers given in
GiB may appear smaller. For example, 1023 GiB = 1098.4 GB.
Disk throughput is measured in input/output operations per second (IOPS ) and MBps where MBps
= 10^6 bytes/sec.
Data disks can operate in cached or uncached modes. For cached data disk operation, the host
cache mode is set to ReadOnly or ReadWrite. For uncached data disk operation, the host cache
mode is set to None.
If you want to get the best performance for your VMs, you should limit the number of data disks to
two disks per vCPU.
Expected network bandwidth is the maximum aggregated bandwidth allocated per VM type
across all NICs, for all destinations. For more information, see Virtual machine network bandwidth.
Upper limits aren't guaranteed. Limits offer guidance for selecting the right VM type for the
intended application. Actual network performance will depend on several factors including network
congestion, application loads, and network settings. For information on optimizing network
throughput, see Optimize network throughput for Azure virtual machines. To achieve the expected
network performance on Linux or Windows, you may need to select a specific version or optimize
your VM. For more information, see Bandwidth/Throughput testing (NTTTCP ).

Older generations of virtual machine sizes


This section provides information on older generations of virtual machine sizes. These sizes are still
supported but will not receive additional capacity. There are newer or alternative sizes that are generally
available. Please refer to Sizes for Linux virtual machines in Azure to choose the VM sizes that will best fit
your need.
For more information on resizing a Windows VM, see Resize a Linux VM.

Basic A
Newer size recommendation: Av2-series
Premium Storage: Not Supported
Premium Storage caching: Not Supported
The basic tier sizes are primarily for development workloads and other applications that don't require load
balancing, auto-scaling, or memory-intensive virtual machines.
MAX MAX. DATA MAX. IOPS
SIZE – TEMPORARY DISKS (1023 (300 PER
SIZE\NAME VCPU MEMORY NICS (MAX) DISK SIZE GB EACH) DISK)

A0\Basic_A0 1 768 MB 2 20 GB 1 1x300

A1\Basic_A1 1 1.75 GB 2 40 GB 2 2x300

A2\Basic_A2 2 3.5 GB 2 60 GB 4 4x300

A3\Basic_A3 4 7 GB 2 120 GB 8 8x300

A4\Basic_A4 8 14 GB 2 240 GB 16 16x300

Standard A0 - A4 using CLI and PowerShell


In the classic deployment model, some VM size names are slightly different in CLI and PowerShell:
Standard_A0 is ExtraSmall
Standard_A1 is Small
Standard_A2 is Medium
Standard_A3 is Large
Standard_A4 is ExtraLarge
A -series
Newer size recommendation: Av2-series
ACU: 50-100
Premium Storage: Not Supported
Premium Storage caching: Not Supported

MAX
MAX DATA NICS/EXPECTE
TEMP DISK D NETWORK
STORAGE MAX DATA THROUGHPU BANDWIDTH
SIZE VCPU MEMORY: GIB (HDD): GIB DISKS T: IOPS (MBPS)

Standard_A0 1 0.768 20 1 1x500 2/100


1

Standard_A1 1 1.75 70 2 2x500 2/500

Standard_A2 2 3.5 135 4 4x500 2/500

Standard_A3 4 7 285 8 8x500 2/1000

Standard_A4 8 14 605 16 16x500 4/2000

Standard_A5 2 14 135 4 4x500 2/500

Standard_A6 4 28 285 8 8x500 2/1000

Standard_A7 8 56 605 16 16x500 4/2000

1
1 The A0 size is over-subscribed on the physical hardware. For this specific size only, other customer
deployments may impact the performance of your running workload. The relative performance is outlined
below as the expected baseline, subject to an approximate variability of 15 percent.

A -series - compute -intensive instances


Newer size recommendation: Av2-series
ACU: 225
Premium Storage: Not Supported
Premium Storage caching: Not Supported
The A8-A11 and H-series sizes are also known as compute-intensive instances. The hardware that runs
these sizes is designed and optimized for compute-intensive and network-intensive applications, including
high-performance computing (HPC ) cluster applications, modeling, and simulations. The A8-A11 series
uses Intel Xeon E5-2670 @ 2.6 GHZ and the H-series uses Intel Xeon E5-2667 v3 @ 3.2 GHz.

MAX DATA
TEMP DISK
STORAGE MAX DATA THROUGHPU
SIZE VCPU MEMORY: GIB (HDD): GIB DISKS T: IOPS MAX NICS

Standard_A8 8 56 382 32 32x500 2


1

Standard_A9 16 112 382 64 64x500 4


1

Standard_A1 8 56 382 32 32x500 2


0

Standard_A1 16 112 382 64 64x500 4


1

1For MPI applications, dedicated RDMA backend network is enabled by FDR InfiniBand network, which
delivers ultra-low -latency and high bandwidth.

D-series
Newer size recommendation: Dv3-series
ACU: 160-250 1
Premium Storage: Not Supported
Premium Storage caching: Not Supported

MAX TEMP
STORAGE MAX
THROUGHPU MAX DATA NICS/EXPECTE
TEMP T: IOPS/READ DISKS/THRO D NETWORK
STORAGE MBPS/WRITE UGHPUT: BANDWIDTH
SIZE VCPU MEMORY: GIB (SSD) GIB MBPS IOPS (MBPS)

Standard_D1 1 3.5 50 3000/46/23 4/4x500 2/500


MAX TEMP
STORAGE MAX
THROUGHPU MAX DATA NICS/EXPECTE
TEMP T: IOPS/READ DISKS/THRO D NETWORK
STORAGE MBPS/WRITE UGHPUT: BANDWIDTH
SIZE VCPU MEMORY: GIB (SSD) GIB MBPS IOPS (MBPS)

Standard_D2 2 7 100 6000/93/46 8/8x500 2/1000

Standard_D3 4 14 200 12000/187/ 16/16x500 4/2000


93

Standard_D4 8 28 400 24000/375/ 32/32x500 8/4000


187

1 VMFamily can run on one of the following CPU's: 2.2 GHz Intel Xeon® E5-2660 v2, 2.4 GHz Intel
Xeon® E5-2673 v3 (Haswell) or 2.3 GHz Intel XEON® E5-2673 v4 (Broadwell)

D-series - memory optimized


Newer size recommendation: Dv3-series
ACU: 160-250 1
Premium Storage: Not Supported
Premium Storage caching: Not Supported

MAX TEMP
STORAGE MAX
THROUGHPU MAX DATA NICS/EXPECTE
TEMP T: IOPS/READ DISKS/THRO D NETWORK
STORAGE MBPS/WRITE UGHPUT: BANDWIDTH
SIZE VCPU MEMORY: GIB (SSD) GIB MBPS IOPS (MBPS)

Standard_D1 2 14 100 6000/93/46 8/8x500 2/1000


1

Standard_D1 4 28 200 12000/187/ 16/16x500 4/2000


2 93

Standard_D1 8 56 400 24000/375/ 32/32x500 8/4000


3 187

Standard_D1 16 112 800 48000/750/ 64/64x500 8/8000


4 375

1 VMFamily can run on one of the following CPU's: 2.2 GHz Intel Xeon® E5-2660 v2, 2.4 GHz Intel
Xeon® E5-2673 v3 (Haswell) or 2.3 GHz Intel XEON® E5-2673 v4 (Broadwell)

Preview: DC-series
Premium Storage: Supported
Premium Storage caching: Supported
The DC -series uses the latest generation of 3.7GHz Intel XEON E -2176G Processor with SGX technology,
and with the Intel Turbo Boost Technology can go up to 4.7GHz.

MAX
CACHED
AND TEMP
STORAGE
THROUGHP MAX
UT: IOPS / UNCACHED MAX NICS /
MBPS DISK EXPECTED
TEMP (CACHE THROUGHP NETWORK
MEMORY: STORAGE MAX DATA SIZE IN UT: IOPS / BANDWIDT
SIZE VCPU GIB (SSD) GIB DISKS GIB) MBPS H (MBPS)

Standard_ 2 8 100 2 4000 / 32 3200 /48 2 / 1500


DC2s (43)

Standard_ 4 16 200 4 8000 / 64 6400 /96 2 / 3000


DC4s (86)

IMPORTANT
DC-series VMs are generation 2 VMs and only support Gen2 images.

DS -series
Newer size recommendation: Dsv3-series
ACU: 160-250 1
Premium Storage: Supported
Premium Storage caching: Supported

MAX
CACHED
AND TEMP
STORAGE
THROUGHP MAX MAX
UT: UNCACHED NICS/EXPEC
IOPS/MBPS DISK TED
TEMP (CACHE THROUGHP NETWORK
MEMORY: STORAGE MAX DATA SIZE IN UT: BANDWIDT
SIZE VCPU GIB (SSD) GIB DISKS GIB) IOPS/MBPS H (MBPS)

Standard_ 1 3.5 7 4 4000/32 3200/32 2/500


DS1 (43)

Standard_ 2 7 14 8 8000/64 6400/64 2/1000


DS2 (86)

Standard_ 4 14 28 16 16000/12 12800/12 4/2000


DS3 8 (172) 8

Standard_ 8 28 56 32 32000/25 25600/25 8/4000


DS4 6 (344) 6

1 VMFamily can run on one of the following CPU's: 2.2 GHz Intel Xeon® E5-2660 v2, 2.4 GHz Intel
Xeon® E5-2673 v3 (Haswell) or 2.3 GHz Intel XEON® E5-2673 v4 (Broadwell)

DS -series - memory optimized


Newer size recommendation: Dsv3-series
ACU: 160-250 1,2
Premium Storage: Supported
Premium Storage caching: Supported

MAX
CACHED
AND TEMP
STORAGE
THROUGHP MAX MAX
UT: UNCACHED NICS/EXPEC
IOPS/MBPS DISK TED
TEMP (CACHE THROUGHP NETWORK
MEMORY: STORAGE MAX DATA SIZE IN UT: BANDWIDT
SIZE VCPU GIB (SSD) GIB DISKS GIB) IOPS/MBPS H (MBPS)

Standard_ 2 14 28 8 8000/64 6400/64 2/1000


DS11 (72)

Standard_ 4 28 56 16 16000/12 12800/12 4/2000


DS12 8 (144) 8

Standard_ 8 56 112 32 32000/25 25600/25 8/4000


DS13 6 (288) 6

Standard_ 16 112 224 64 64000/51 51200/51 8/8000


DS14 2 (576) 2

1 The maximum disk throughput (IOPS or MBps) possible with a DS series VM may be limited by the
number, size and striping of the attached disk(s). For details, see designing for high performance for
Windows or Linux. 2 VM Family can run on one of the following CPU's: 2.2 GHz Intel Xeon® E5-2660 v2,
2.4 GHz Intel Xeon® E5-2673 v3 (Haswell) or 2.3 GHz Intel XEON® E5-2673 v4 (Broadwell)

Ls-series
The Ls-series offers up to 32 vCPUs, using the Intel® Xeon® processor E5 v3 family. The Ls-series gets
the same CPU performance as the G/GS -Series and comes with 8 GiB of memory per vCPU.
The Ls-series does not support the creation of a local cache to increase the IOPS achievable by durable
data disks. The high throughput and IOPS of the local disk makes Ls-series VMs ideal for NoSQL stores
such as Apache Cassandra and MongoDB which replicate data across multiple VMs to achieve persistence
in the event of the failure of a single VM.
ACU: 180-240
Premium Storage: Supported
Premium Storage caching: Not Supported

MAX
MAX TEMP UNCACHED MAX
STORAGE DISK NICS/EXPEC
THROUGHP THROUGHP TED
TEMP UT UT NETWORK
MEMORY STORAGE MAX DATA (IOPS/MBP (IOPS/MBP BANDWIDT
SIZE VCPU (GIB) (GIB) DISKS S) S) H (MBPS)

Standard_ 4 32 678 16 20000/20 5000/125 2/4000


L4s 0
MAX
MAX TEMP UNCACHED MAX
STORAGE DISK NICS/EXPEC
THROUGHP THROUGHP TED
TEMP UT UT NETWORK
MEMORY STORAGE MAX DATA (IOPS/MBP (IOPS/MBP BANDWIDT
SIZE VCPU (GIB) (GIB) DISKS S) S) H (MBPS)

Standard_ 8 64 1388 32 40000/40 10000/25 4/8000


L8s 0 0

Standard_ 16 128 2807 64 80000/80 20000/50 8/16000


L16s 0 0

Standard_ 32 256 5630 64 160000/1 40000/10 8/20000


L32s 1 600 00

The maximum disk throughput possible with Ls-series VMs may be limited by the number, size, and
striping of any attached disks. For details, see designing for high performance for Windows or Linux.
1 Instance is isolated to hardware dedicated to a single customer.

GS -series
ACU: 180 - 240 1
Premium Storage: Supported
Premium Storage caching: Supported

MAX
CACHED
AND TEMP
STORAGE
THROUGHP MAX MAX
UT: IOPS / UNCACHED NICS/EXPEC
MBPS DISK TED
TEMP (CACHE THROUGHP NETWORK
MEMORY: STORAGE MAX DATA SIZE IN UT: BANDWIDT
SIZE VCPU GIB (SSD) GIB DISKS GIB) IOPS/MBPS H (MBPS)

Standard_ 2 28 56 8 10000/10 5000/ 125 2/2000


GS1 0 (264)

Standard_ 4 56 112 16 20000/20 10000/ 2/4000


GS2 0 (528) 250

Standard_ 8 112 224 32 40000/40 20000/ 4/8000


GS3 0 (1056) 500

Standard_ 16 224 448 64 80000/80 40000/10 8/16000


GS4 3 0 (2112) 00

Standard_ 32 448 896 64 160000/1 80000/20 8/20000


GS5 2, 3 600 00
(4224)

1 The maximum disk throughput (IOPS or MBps) possible with a GS series VM may be limited by the
number, size and striping of the attached disk(s). For details, see designing for high performance for
Windows or Linux.
2 Instance is isolated to hardware dedicated to a single customer.

3
3 Constrained core sizes available.

G -series
ACU: 180 - 240
Premium Storage: Not Supported
Premium Storage caching: Not Supported

MAX TEMP
STORAGE MAX
THROUGHPU MAX DATA NICS/EXPECTE
TEMP T: IOPS/READ DISKS/THRO D NETWORK
STORAGE MBPS/WRITE UGHPUT: BANDWIDTH
SIZE VCPU MEMORY: GIB (SSD) GIB MBPS IOPS (MBPS)

Standard_G1 2 28 384 6000/93/46 8/8x500 2/2000

Standard_G2 4 56 768 12000/187/ 16/16x500 2/4000


93

Standard_G3 8 112 1536 24000/375/ 32/32x500 4/8000


187

Standard_G4 16 224 3072 48000/750/ 64/64x500 8/16000


375

Standard_G5 32 448 6144 96000/1500 64/64x500 8/20000


1 /750

1 Instance is isolated to hardware dedicated to a single customer.

Other sizes
General purpose
Compute optimized
Memory optimized
Storage optimized
GPU
High performance compute

Next steps
Learn more about how Azure compute units (ACU ) can help you compare compute performance across
Azure SKUs.
Virtual machine isolation in Azure
11/13/2019 • 4 minutes to read • Edit Online

Azure Compute offers virtual machine sizes that are Isolated to a specific hardware type and dedicated to a single
customer. These virtual machine sizes are best suited for workloads that require a high degree of isolation from
other customers for workloads involving elements like compliance and regulatory requirements. Customers can
also choose to further subdivide the resources of these Isolated virtual machines by using Azure support for
nested virtual machines.
Utilizing an isolated size guarantees that your virtual machine will be the only one running on that specific server
instance. The current Isolated virtual machine offerings include:
Standard_E64is_v3
Standard_E64i_v3
Standard_M128ms
Standard_GS5
Standard_G5
Standard_DS15_v2
Standard_D15_v2
Standard_F72s_v2
You can learn more about each available isolated size here.

Retiring D15_v2/DS15_v2 isolation on May 15, 2020


Update on February 10, 2020: The "isolation" retirement timeline has been extended to May 15, 2020"
Azure Dedicated Host is now GA, which allows you to run your organization’s Linux and Windows virtual
machines on single-tenant physical servers. We plan to fully replace isolated Azure VMs with Azure Dedicated
Host. After May 15, 2020 the D15_v2/DS15_v2 Azure VMs will no longer be hardware isolated.

How does this affect me?


After May 15, 2020, we will no longer provide an isolation guarantee for your D15_v2/DS15_v2 Azure virtual
machines.

What actions should I take?


If hardware isolation is not required for you, there is no action you need to take.
If isolation is required to you, before May 15, 2020, you would need to either:
• Migrate your workload to Azure Dedicated Host.
• Request access to a D15i_v2 and DS15i_v2 Azure VM, to get the same price performance. This option is only
available for pay-as-you-go and one-year reserved instance scenarios.
• Migrate your workload to another Azure isolated virtual machine.
For details see below:

Timeline
DATE ACTION

November 18, 2019 Availability of D/DS15i_v2 (PAYG, 1-year RI)

May 14, 2020 Last day to buy D/DS15i_v2 1-year RI

May 15, 2020 D/DS15_v2 isolation guarantee removed

May 15, 2021 Retire D/DS15i_v2 (all customers except who bought 3-year RI
of D/DS15_v2 before November 18, 2019)

November 17, 2022 Retire D/DS15i_v2 when 3-year RIs done (for customers who
bought 3-year RI of D/DS15_v2 before November 18, 2019)

FAQ
Q: Is the size D/DS15_v2 going to get retired?
A: No, only "isolation" feature is going to get retired. If you do not need isolation, you do not need to take any
action.
Q: Is the size D/DS15i_v2 going to get retired?
A: Yes, the size is only available until May 15,2021. For customers who have bought 3-year RIs on D/DS15_v2
before November 18, 2019 will have access to D/DS15i_v2 until November 17, 2022.
Q: Why am I not seeing the new D/DS15i_v2 sizes in the portal?
A: If you are a current D/DS15_v2 customer and want to use the new D/DS15i_v2 sizes, fill this form
Q: Why I am not seeing any quota for the new D/DS15i_v2 sizes?
A: If you are a current D/DS15_v2 customer and want to use the new D/DS15i_v2 sizes, fill this form
Q: When are the other isolated sizes going to retire?
A: We will provide reminders 12 months in advance of the official decommissioning of the sizes.
Q: Is there a downtime when my vm lands on a non-isolated hardware?
A: If you do not need isolation, you do not need to take any action and you would not see any downtime.
Q: Are there any cost changes for moving to a non-isolated virtual machine?
A: No
Q: I already purchased 1- or 3-year Reserved Instance for D15_v2 or Ds15_v2. How will the discount be applied to
my VM usage?
A: RIs purchased before November 18, 2019 will automatically extend coverage to the new isolated VM series.

RI INSTANCE SIZE FLEXIBILITY BENEFIT ELIGIBILITY

D15_v2 Off D15_v2 and D15i_v2

D15_v2 On D15_v2 series and D15i_v2 will all


receive the RI benefit.

D14_v2 On D15_v2 series and D15i_v2 will all


receive the RI benefit.

Likewise for Dsv2 series.


Q: I want to purchase additional Reserved Instances for Dv2. Which one should I choose?
A: All RIs purchased after Nov 18, 2019, have the following behavior.

RI INSTANCE SIZE FLEXIBILITY BENEFIT ELIGIBILITY

D15_v2 Off D15_v2 only

D15_v2 On D15_v2 series will receive the RI benefit.


The new D15i_v2 will not be eligible for
RI benefit from this RI type.

D15i_v2 Off D15i_v2 only

D15i_v2 On D15i_v2 only

Instance Size Flexibility cannot be used to apply to any other sizes such as D2_v2, D4_v2, or D15_v2. Likewise, for
Dsv2 series.
Q: Can I buy a new 3-year RI for D15i_v2 and DS15i_v2?
A: Unfortunately no, only 1-year RI is available for new purchase.
Q: Can I move my existing D15_v2/DS15_v2 Reserve Instance to an isolated size Reserved Instance?
A: This action is not necessary since the benefit will apply to both isolated and non-isolated sizes. But Azure will
support changing existing D15_v2/DS15_v2 Reserved Instances to D15i_v2/DS15i_v2. For all other Dv2/Dsv2
Reserved Instances, use the existing Reserved Instance or buy new Reserved Instances for the isolated sizes.
Q: I'm an Azure Service Fabric Customer relying on the Silver or Gold Durability Tiers. Does this change impact
me?
A: No. The guarantees provided by Service Fabric's Durability Tiers will continue to function even after this change.
If you require physical hardware isolation for other reasons, you may still need to take one of the actions described
above.

Next steps
You can deploy a dedicated host using Azure PowerShell, the portal, and Azure CLI. For more information, see
the Dedicated hosts overview.
Azure compute unit (ACU)
2/20/2020 • 2 minutes to read • Edit Online

The concept of the Azure Compute Unit (ACU ) provides a way of comparing compute (CPU ) performance
across Azure SKUs. This will help you easily identify which SKU is most likely to satisfy your performance
needs. ACU is currently standardized on a Small (Standard_A1) VM being 100 and all other SKUs then
represent approximately how much faster that SKU can run a standard benchmark.

IMPORTANT
The ACU is only a guideline. The results for your workload may vary.

SKU FAMILY ACU \ VCPU VCPU: CORE

A0 50 1:1

A1 - A4 100 1:1

A5 - A7 100 1:1

A1_v2 - A8_v2 100 1:1

A2m_v2 - A8m_v2 100 1:1

A8 - A11 225* 1:1

D1 - D14 160 - 250 1:1

D1_v2 - D15_v2 210 - 250* 1:1

DS1 - DS14 160 - 250 1:1

DS1_v2 - DS15_v2 210 - 250* 1:1

D_v3 160 - 190* 2:1***

Ds_v3 160 - 190* 2:1***

E_v3 160 - 190* 2:1***

Es_v3 160 - 190* 2:1***

F2s_v2 - F72s_v2 195 - 210* 2:1***

F1 - F16 210 - 250* 1:1

F1s - F16s 210 - 250* 1:1


SKU FAMILY ACU \ VCPU VCPU: CORE

G1 - G5 180 - 240* 1:1

GS1 - GS5 180 - 240* 1:1

H 290 - 300* 1:1

HB 199 - 216** 1:1

HC 297 - 315* 1:1

L4s - L32s 180 - 240* 1:1

L8s_v2 - L80s_v2 150 - 175** 2:1

M 160 - 180 2:1***

*ACUs use Intel® Turbo technology to increase CPU frequency and provide a performance increase. The
amount of the performance increase can vary based on the VM size, workload, and other workloads
running on the same host. **ACUs use AMD® Boost technology to increase CPU frequency and provide a
performance increase. The amount of the performance increase can vary based on the VM size, workload,
and other workloads running on the same host. ***Hyper-threaded and capable of running nested
virtualization
Here are links to more information about the different sizes:
General-purpose
Memory optimized
Compute optimized
GPU optimized
High performance compute
Storage optimized
Compute benchmark scores for Windows VMs
2/26/2020 • 17 minutes to read • Edit Online

The following SPECInt benchmark scores show compute performance for select Azure VMs running Windows
Server. Compute benchmark scores are also available for Linux VMs.

Av2 - General Compute


SIZE VCPUS NUMA NODES CPU RUNS AVG BASE RATE STDDEV

Standard_A1_ 1 1 Intel(R) 12 14.2 0.3


v2 Xeon(R) CPU
E5-2660 0 @
2.20GHz

Standard_A1_ 1 1 Intel(R) 9 13.2 0.6


v2 Xeon(R) CPU
E5-2673 v3 @
2.40GHz

Standard_A1_ 1 1 Intel(R) 10 14.1 0.7


v2 Xeon(R) CPU
E5-2673 v4 @
2.30GHz

Standard_A2_ 2 1 Intel(R) 14 28.9 0.6


v2 Xeon(R) CPU
E5-2660 0 @
2.20GHz

Standard_A2_ 2 1 Intel(R) 10 27.4 1.6


v2 Xeon(R) CPU
E5-2673 v3 @
2.40GHz

Standard_A2_ 2 1 Intel(R) 17 28.9 1.8


v2 Xeon(R) CPU
E5-2673 v4 @
2.30GHz

Standard_A2 2 1 Intel(R) 14 29.0 0.5


m_v2 Xeon(R) CPU
E5-2660 0 @
2.20GHz

Standard_A2 2 1 Intel(R) 11 26.3 0.8


m_v2 Xeon(R) CPU
E5-2673 v3 @
2.40GHz

Standard_A2 2 1 Intel(R) 21 28.4 1.0


m_v2 Xeon(R) CPU
E5-2673 v4 @
2.30GHz
SIZE VCPUS NUMA NODES CPU RUNS AVG BASE RATE STDDEV

Standard_A4_ 4 1 Intel(R) 27 56.6 1.0


v2 Xeon(R) CPU
E5-2660 0 @
2.20GHz

Standard_A4_ 4 1 Intel(R) 13 52.8 2.0


v2 Xeon(R) CPU
E5-2673 v3 @
2.40GHz

Standard_A4_ 4 1 Intel(R) 15 52.1 4.5


v2 Xeon(R) CPU
E5-2673 v4 @
2.30GHz

Standard_A4 4 1 Intel(R) 17 56.4 1.8


m_v2 Xeon(R) CPU
E5-2660 0 @
2.20GHz

Standard_A4 4 1 Intel(R) 6 53.4 1.9


m_v2 Xeon(R) CPU
E5-2673 v3 @
2.40GHz

Standard_A4 4 1 Intel(R) 23 57.1 3.6


m_v2 Xeon(R) CPU
E5-2673 v4 @
2.30GHz

Standard_A8_ 8 1 Intel(R) 14 109.1 1.6


v2 Xeon(R) CPU
E5-2660 0 @
2.20GHz

Standard_A8_ 8 1 Intel(R) 6 101.5 2.8


v2 Xeon(R) CPU
E5-2673 v3 @
2.40GHz

Standard_A8_ 8 1 Intel(R) 11 101.9 2.7


v2 Xeon(R) CPU
E5-2673 v4 @
2.30GHz

Standard_A8 8 1 Intel(R) 11 101.4 1.2


m_v2 Xeon(R) CPU
E5-2673 v3 @
2.40GHz
SIZE VCPUS NUMA NODES CPU RUNS AVG BASE RATE STDDEV

Standard_A8 8 1 Intel(R) 10 104.5 5.1


m_v2 Xeon(R) CPU
E5-2673 v4 @
2.30GHz

Standard_A8 8 2 Intel(R) 13 111.6 2.3


m_v2 Xeon(R) CPU
E5-2660 0 @
2.20GHz

Note: Av2-series VMs can be deployed on a variety of hardware types and processors (as seen above). Av2-series
VMs have CPU performance and memory configurations best suited for entry level workloads like development
and test. The size is throttled to offer relatively consistent processor performance for the running instance,
regardless of the hardware it is deployed on; however, software that takes advantage of specific newer processor
optimizations may see more significant variation across processor types.

B - Burstable
SIZE VCPUS NUMA NODES CPU RUNS AVG BASE RATE STDDEV

Standard_B1m 1 1 Intel(R) 9 6.3 0.2


s Xeon(R) CPU
E5-2673 v3 @
2.40GHz

Standard_B1m 1 1 Intel(R) 47 6.4 0.2


s Xeon(R) CPU
E5-2673 v4 @
2.30GHz

Standard_B2m 2 1 Intel(R) 36 19.8 0.8


s Xeon(R) CPU
E5-2673 v4 @
2.30GHz

Standard_B2s 2 1 Intel(R) 2 13.0 0.0


Xeon(R) CPU
E5-2673 v3 @
2.40GHz

Standard_B2s 2 1 Intel(R) 29 13.0 0.5


Xeon(R) CPU
E5-2673 v4 @
2.30GHz

Standard_B4m 4 1 Intel(R) 6 27.1 1.0


s Xeon(R) CPU
E5-2673 v3 @
2.40GHz

Standard_B4m 4 1 Intel(R) 43 28.3 0.7


s Xeon(R) CPU
E5-2673 v4 @
2.30GHz
SIZE VCPUS NUMA NODES CPU RUNS AVG BASE RATE STDDEV

Standard_B8m 8 1 Intel(R) 3 42.0 0.0


s Xeon(R) CPU
E5-2673 v3 @
2.40GHz

Standard_B8m 8 1 Intel(R) 25 41.4 0.9


s Xeon(R) CPU
E5-2673 v4 @
2.30GHz

Note: B -Series VMs are for workloads with burstable performance requirements. VM instances accumulate credits
when using less than its baseline. When the VM has accumulated credit, the VM can burst above the baseline
using up to 100% to meet short CPU burst requirements. Burst time depends on available credits which is a
function of VM size and time.
SPEC Int is a fairly long running test that typically exhausts available burst credits. Therefore the numbers above
are closer to the baseline performance of the VM (although they may reflect some burst time accumulated
between runs). For short, bursty, workloads (typical on B -Series) performance will typically be closer to that of the
Ds v3 Series..

DSv3 - General Compute + Premium Storage


SIZE VCPUS NUMA NODES CPU RUNS AVG BASE RATE STDDEV

Standard_D2s 2 1 Intel(R) 10 40.8 2.3


_v3 Xeon(R) CPU
E5-2673 v3 @
2.40GHz

Standard_D2s 2 1 Intel(R) 52 43.3 2.1


_v3 Xeon(R) CPU
E5-2673 v4 @
2.30GHz

Standard_D4s 4 1 Intel(R) 21 77.9 2.6


_v3 Xeon(R) CPU
E5-2673 v3 @
2.40GHz

Standard_D4s 4 1 Intel(R) 29 82.3 2.5


_v3 Xeon(R) CPU
E5-2673 v4 @
2.30GHz

Standard_D8s 8 1 Intel(R) 7 148.3 1.9


_v3 Xeon(R) CPU
E5-2673 v3 @
2.40GHz

Standard_D8s 8 1 Intel(R) 28 155.4 5.6


_v3 Xeon(R) CPU
E5-2673 v4 @
2.30GHz
SIZE VCPUS NUMA NODES CPU RUNS AVG BASE RATE STDDEV

Standard_D16 16 1 Intel(R) 3 275.7 5.1


s_v3 Xeon(R) CPU
E5-2673 v3 @
2.40GHz

Standard_D16 16 1 Intel(R) 38 298.2 4.4


s_v3 Xeon(R) CPU
E5-2673 v4 @
2.30GHz

Standard_D32 32 1 Intel(R) 24 545.8 10.5


s_v3 Xeon(R) CPU
E5-2673 v4 @
2.30GHz

Standard_D32 32 2 Intel(R) 9 535.6 12.6


s_v3 Xeon(R) CPU
E5-2673 v3 @
2.40GHz

Standard_D64 64 2 Intel(R) 35 1070.6 2.4


s_v3 Xeon(R) CPU
E5-2673 v4 @
2.30GHz

Dv3 - General Compute


SIZE VCPUS NUMA NODES CPU RUNS AVG BASE RATE STDDEV

Standard_D2_ 2 1 Intel(R) 10 38.6 1.8


v3 Xeon(R) CPU
E5-2673 v3 @
2.40GHz

Standard_D2_ 2 1 Intel(R) 24 41.8 3.3


v3 Xeon(R) CPU
E5-2673 v4 @
2.30GHz

Standard_D4_ 4 1 Intel(R) 17 77.8 1.3


v3 Xeon(R) CPU
E5-2673 v3 @
2.40GHz

Standard_D4_ 4 1 Intel(R) 45 82.7 4.5


v3 Xeon(R) CPU
E5-2673 v4 @
2.30GHz

Standard_D8_ 8 1 Intel(R) 9 146.7 10.4


v3 Xeon(R) CPU
E5-2673 v3 @
2.40GHz
SIZE VCPUS NUMA NODES CPU RUNS AVG BASE RATE STDDEV

Standard_D8_ 8 1 Intel(R) 27 159.9 8.3


v3 Xeon(R) CPU
E5-2673 v4 @
2.30GHz

Standard_D16 16 1 Intel(R) 10 274.1 3.8


_v3 Xeon(R) CPU
E5-2673 v3 @
2.40GHz

Standard_D16 16 1 Intel(R) 32 300.7 8.8


_v3 Xeon(R) CPU
E5-2673 v4 @
2.30GHz

Standard_D32 32 1 Intel(R) 24 549.3 11.1


_v3 Xeon(R) CPU
E5-2673 v4 @
2.30GHz

Standard_D32 32 2 Intel(R) 7 538.6 9.4


_v3 Xeon(R) CPU
E5-2673 v3 @
2.40GHz

Standard_D64 64 2 Intel(R) 32 1070.6 12.4


_v3 Xeon(R) CPU
E5-2673 v4 @
2.30GHz

DSv2 - Storage Optimized


SIZE VCPUS NUMA NODES CPU RUNS AVG BASE RATE STDDEV

Standard_DS1 1 1 Intel(R) 12 33.0 1.1


_v2 Xeon(R) CPU
E5-2673 v3 @
2.40GHz

Standard_DS1 1 1 Intel(R) 37 33.8 2.5


_v2 Xeon(R) CPU
E5-2673 v4 @
2.30GHz

Standard_DS2 2 1 Intel(R) 33 63.9 1.7


_v2 Xeon(R) CPU
E5-2673 v3 @
2.40GHz

Standard_DS2 2 1 Intel(R) 32 66.6 4.8


_v2 Xeon(R) CPU
E5-2673 v4 @
2.30GHz
SIZE VCPUS NUMA NODES CPU RUNS AVG BASE RATE STDDEV

Standard_DS3 4 1 Intel(R) 15 125.5 3.2


_v2 Xeon(R) CPU
E5-2673 v3 @
2.40GHz

Standard_DS3 4 1 Intel(R) 47 130.1 4.3


_v2 Xeon(R) CPU
E5-2673 v4 @
2.30GHz

Standard_DS4 8 1 Intel(R) 23 235.7 6.6


_v2 Xeon(R) CPU
E5-2673 v3 @
2.40GHz

Standard_DS4 8 1 Intel(R) 34 249.4 2.8


_v2 Xeon(R) CPU
E5-2673 v4 @
2.30GHz

Standard_DS5 16 1 Intel(R) 11 414.9 5.1


_v2 Xeon(R) CPU
E5-2673 v3 @
2.40GHz

Standard_DS5 16 1 Intel(R) 31 470.6 5.7


_v2 Xeon(R) CPU
E5-2673 v4 @
2.30GHz

Standard_DS1 2 1 Intel(R) 22 66.3 2.8


1_v2 Xeon(R) CPU
E5-2673 v3 @
2.40GHz

Standard_DS1 2 1 Intel(R) 34 64.8 2.8


1_v2 Xeon(R) CPU
E5-2673 v4 @
2.30GHz

Standard_DS1 1 1 Intel(R) 17 33.6 1.8


1-1_v2 Xeon(R) CPU
E5-2673 v3 @
2.40GHz

Standard_DS1 1 1 Intel(R) 41 36.0 1.7


1-1_v2 Xeon(R) CPU
E5-2673 v4 @
2.30GHz

Standard_DS1 4 1 Intel(R) 10 126.8 2.7


2_v2 Xeon(R) CPU
E5-2673 v3 @
2.40GHz
SIZE VCPUS NUMA NODES CPU RUNS AVG BASE RATE STDDEV

Standard_DS1 4 1 Intel(R) 30 127.5 3.3


2_v2 Xeon(R) CPU
E5-2673 v4 @
2.30GHz

Standard_DS1 1 1 Intel(R) 20 33.5 1.4


2-1_v2 Xeon(R) CPU
E5-2673 v3 @
2.40GHz

Standard_DS1 1 1 Intel(R) 30 34.8 2.4


2-1_v2 Xeon(R) CPU
E5-2673 v4 @
2.30GHz

Standard_DS1 2 1 Intel(R) 17 65.5 2.3


2-2_v2 Xeon(R) CPU
E5-2673 v3 @
2.40GHz

Standard_DS1 2 1 Intel(R) 33 67.7 5.1


2-2_v2 Xeon(R) CPU
E5-2673 v4 @
2.30GHz

Standard_DS1 8 1 Intel(R) 20 234.1 7.1


3_v2 Xeon(R) CPU
E5-2673 v3 @
2.40GHz

Standard_DS1 8 1 Intel(R) 23 248.0 2.2


3_v2 Xeon(R) CPU
E5-2673 v4 @
2.30GHz

Standard_DS1 2 1 Intel(R) 17 65.2 3.1


3-2_v2 Xeon(R) CPU
E5-2673 v3 @
2.40GHz

Standard_DS1 2 1 Intel(R) 15 72.8 3.8


3-2_v2 Xeon(R) CPU
E5-2673 v4 @
2.30GHz

Standard_DS1 4 1 Intel(R) 24 126.1 4.3


3-4_v2 Xeon(R) CPU
E5-2673 v3 @
2.40GHz

Standard_DS1 4 1 Intel(R) 27 133.3 2.8


3-4_v2 Xeon(R) CPU
E5-2673 v4 @
2.30GHz
SIZE VCPUS NUMA NODES CPU RUNS AVG BASE RATE STDDEV

Standard_DS1 16 1 Intel(R) 22 469.5 6.9


4_v2 Xeon(R) CPU
E5-2673 v4 @
2.30GHz

Standard_DS1 16 2 Intel(R) 16 456.6 7.3


4_v2 Xeon(R) CPU
E5-2673 v3 @
2.40GHz

Standard_DS1 4 1 Intel(R) 28 132.8 6.6


4-4_v2 Xeon(R) CPU
E5-2673 v4 @
2.30GHz

Standard_DS1 4 2 Intel(R) 16 125.1 4.8


4-4_v2 Xeon(R) CPU
E5-2673 v3 @
2.40GHz

Standard_DS1 8 1 Intel(R) 27 251.3 2.4


4-8_v2 Xeon(R) CPU
E5-2673 v4 @
2.30GHz

Standard_DS1 8 2 Intel(R) 14 247.4 10.2


4-8_v2 Xeon(R) CPU
E5-2673 v3 @
2.40GHz

Standard_DS1 20 2 Intel(R) 45 546.1 10.5


5_v2 Xeon(R) CPU
E5-2673 v3 @
2.40GHz

Dv2 - General Compute


SIZE VCPUS NUMA NODES CPU RUNS AVG BASE RATE STDDEV

Standard_D1_ 1 1 Intel(R) 30 33.5 1.7


v2 Xeon(R) CPU
E5-2673 v3 @
2.40GHz

Standard_D1_ 1 1 Intel(R) 31 34.7 2.5


v2 Xeon(R) CPU
E5-2673 v4 @
2.30GHz

Standard_D2_ 2 1 Intel(R) 18 66.0 1.8


v2 Xeon(R) CPU
E5-2673 v3 @
2.40GHz
SIZE VCPUS NUMA NODES CPU RUNS AVG BASE RATE STDDEV

Standard_D2_ 2 1 Intel(R) 31 69.9 5.0


v2 Xeon(R) CPU
E5-2673 v4 @
2.30GHz

Standard_D3_ 4 1 Intel(R) 27 127.7 3.0


v2 Xeon(R) CPU
E5-2673 v3 @
2.40GHz

Standard_D3_ 4 1 Intel(R) 27 133.4 9.1


v2 Xeon(R) CPU
E5-2673 v4 @
2.30GHz

Standard_D4_ 8 1 Intel(R) 15 238.7 4.4


v2 Xeon(R) CPU
E5-2673 v3 @
2.40GHz

Standard_D4_ 8 1 Intel(R) 36 248.9 4.8


v2 Xeon(R) CPU
E5-2673 v4 @
2.30GHz

Standard_D5_ 16 1 Intel(R) 9 413.9 14.1


v2 Xeon(R) CPU
E5-2673 v3 @
2.40GHz

Standard_D5_ 16 1 Intel(R) 27 470.2 8.1


v2 Xeon(R) CPU
E5-2673 v4 @
2.30GHz

Standard_D5_ 16 2 Intel(R) 5 466.0 0.0


v2 Xeon(R) CPU
E5-2673 v3 @
2.40GHz

Standard_D11 2 1 Intel(R) 22 66.4 2.9


_v2 Xeon(R) CPU
E5-2673 v3 @
2.40GHz

Standard_D11 2 1 Intel(R) 27 69.0 6.7


_v2 Xeon(R) CPU
E5-2673 v4 @
2.30GHz

Standard_D12 4 1 Intel(R) 24 127.7 4.6


_v2 Xeon(R) CPU
E5-2673 v3 @
2.40GHz
SIZE VCPUS NUMA NODES CPU RUNS AVG BASE RATE STDDEV

Standard_D12 4 1 Intel(R) 20 135.9 9.3


_v2 Xeon(R) CPU
E5-2673 v4 @
2.30GHz

Standard_D13 8 1 Intel(R) 16 237.4 6.6


_v2 Xeon(R) CPU
E5-2673 v3 @
2.40GHz

Standard_D13 8 1 Intel(R) 28 250.2 3.8


_v2 Xeon(R) CPU
E5-2673 v4 @
2.30GHz

Standard_D14 16 1 Intel(R) 23 473.0 9.4


_v2 Xeon(R) CPU
E5-2673 v4 @
2.30GHz

Standard_D14 16 2 Intel(R) 17 443.9 18.8


_v2 Xeon(R) CPU
E5-2673 v3 @
2.40GHz

Standard_D15 20 2 Intel(R) 37 558.8 8.4


_v2 Xeon(R) CPU
E5-2673 v3 @
2.40GHz

Esv3 - Memory Optimized + Premium Storage


SIZE VCPUS NUMA NODES CPU RUNS AVG BASE RATE STDDEV

Standard_E2s_ 2 1 Intel(R) 39 42.5 2.2


v3 Xeon(R) CPU
E5-2673 v4 @
2.30GHz

Standard_E4s_ 4 1 Intel(R) 28 81.4 3.3


v3 Xeon(R) CPU
E5-2673 v4 @
2.30GHz

Standard_E8s_ 8 1 Intel(R) 29 156.3 5.1


v3 Xeon(R) CPU
E5-2673 v4 @
2.30GHz

Standard_E8- 2 1 Intel(R) 57 41.8 2.6


2s_v3 Xeon(R) CPU
E5-2673 v4 @
2.30GHz
SIZE VCPUS NUMA NODES CPU RUNS AVG BASE RATE STDDEV

Standard_E8- 4 1 Intel(R) 45 82.9 3.0


4s_v3 Xeon(R) CPU
E5-2673 v4 @
2.30GHz

Standard_E16 16 1 Intel(R) 31 295.7 4.5


s_v3 Xeon(R) CPU
E5-2673 v4 @
2.30GHz

Standard_E16 4 1 Intel(R) 45 82.7 3.8


-4s_v3 Xeon(R) CPU
E5-2673 v4 @
2.30GHz

Standard_E16 8 1 Intel(R) 39 158.3 4.5


-8s_v3 Xeon(R) CPU
E5-2673 v4 @
2.30GHz

Standard_E20 20 1 Intel(R) 27 369.7 3.2


s_v3 Xeon(R) CPU
E5-2673 v4 @
2.30GHz

Standard_E32 32 2 Intel(R) 31 577.9 9.4


s_v3 Xeon(R) CPU
E5-2673 v4 @
2.30GHz

Standard_E32 8 2 Intel(R) 31 163.4 6.8


-8s_v3 Xeon(R) CPU
E5-2673 v4 @
2.30GHz

Standard_E32 16 2 Intel(R) 41 307.1 8.7


-16s_v3 Xeon(R) CPU
E5-2673 v4 @
2.30GHz

Standard_E4- 2 1 Intel(R) 65 41.9 2.4


2s_v3 Xeon(R) CPU
E5-2673 v4 @
2.30GHz

Standard_E64 64 2 Intel(R) 1 1080.0 0.0


s_v3 Xeon(R) CPU
E5-2673 v4 @
2.30GHz

Standard_E64 16 2 Intel(R) 3 334.3 1.5


-16s_v3 Xeon(R) CPU
E5-2673 v4 @
2.30GHz
SIZE VCPUS NUMA NODES CPU RUNS AVG BASE RATE STDDEV

Standard_E64 32 2 Intel(R) 4 592.5 4.4


-32s_v3 Xeon(R) CPU
E5-2673 v4 @
2.30GHz

Eisv3 - Memory Opt + Premium Storage (isolated)


SIZE VCPUS NUMA NODES CPU RUNS AVG BASE RATE STDDEV

Standard_E64i 64 2 Intel(R) 28 1073.9 5.7


s_v3 Xeon(R) CPU
E5-2673 v4 @
2.30GHz

Ev3 - Memory Optimized


SIZE VCPUS NUMA NODES CPU RUNS AVG BASE RATE STDDEV

Standard_E2_v 2 1 Intel(R) 41 41.2 2.4


3 Xeon(R) CPU
E5-2673 v4 @
2.30GHz

Standard_E4_v 4 1 Intel(R) 43 81.4 5.3


3 Xeon(R) CPU
E5-2673 v4 @
2.30GHz

Standard_E8_v 8 1 Intel(R) 39 157.4 8.1


3 Xeon(R) CPU
E5-2673 v4 @
2.30GHz

Standard_E16 16 1 Intel(R) 49 301.6 8.9


_v3 Xeon(R) CPU
E5-2673 v4 @
2.30GHz

Standard_E20 20 1 Intel(R) 35 371.0 6.9


_v3 Xeon(R) CPU
E5-2673 v4 @
2.30GHz

Standard_E32 32 2 Intel(R) 35 579.9 16.1


_v3 Xeon(R) CPU
E5-2673 v4 @
2.30GHz

Standard_E64 64 2 Intel(R) 31 1080.0 11.3


_v3 Xeon(R) CPU
E5-2673 v4 @
2.30GHz
Eiv3 - Memory Optimized (isolated)
SIZE VCPUS NUMA NODES CPU RUNS AVG BASE RATE STDDEV

Standard_E64i 64 2 Intel(R) 28 1081.4 11.1


_v3 Xeon(R) CPU
E5-2673 v4 @
2.30GHz

Fsv2 - Compute + Storage Optimized


SIZE VCPUS NUMA NODES CPU RUNS AVG BASE RATE STDDEV

Standard_F2s_ 2 1 Intel(R) 46 56.5 2.4


v2 Xeon(R)
Platinum
8168 CPU @
2.70GHz

Standard_F4s_ 4 1 Intel(R) 60 110.2 4.7


v2 Xeon(R)
Platinum
8168 CPU @
2.70GHz

Standard_F8s_ 8 1 Intel(R) 36 215.2 5.3


v2 Xeon(R)
Platinum
8168 CPU @
2.70GHz

Standard_F16 16 1 Intel(R) 36 409.3 15.5


s_v2 Xeon(R)
Platinum
8168 CPU @
2.70GHz

Standard_F32 32 1 Intel(R) 31 760.9 16.9


s_v2 Xeon(R)
Platinum
8168 CPU @
2.70GHz

Standard_F64 64 2 Intel(R) 33 1440.9 26.0


s_v2 Xeon(R)
Platinum
8168 CPU @
2.70GHz

Standard_F72 72 2 Intel(R) 29 1372.1 8.2


s_v2 Xeon(R)
Platinum
8168 CPU @
2.70GHz

Fs - Compute and Storage Optimized


SIZE VCPUS NUMA NODES CPU RUNS AVG BASE RATE STDDEV

Standard_F1s 1 1 Intel(R) 31 33.2 1.0


Xeon(R) CPU
E5-2673 v3 @
2.40GHz

Standard_F1s 1 1 Intel(R) 41 35.1 2.0


Xeon(R) CPU
E5-2673 v4 @
2.30GHz

Standard_F2s 2 1 Intel(R) 18 63.7 1.8


Xeon(R) CPU
E5-2673 v3 @
2.40GHz

Standard_F2s 2 1 Intel(R) 21 66.6 3.8


Xeon(R) CPU
E5-2673 v4 @
2.30GHz

Standard_F4s 4 1 Intel(R) 14 128.4 2.9


Xeon(R) CPU
E5-2673 v3 @
2.40GHz

Standard_F4s 4 1 Intel(R) 25 127.7 4.5


Xeon(R) CPU
E5-2673 v4 @
2.30GHz

Standard_F8s 8 1 Intel(R) 11 234.9 3.7


Xeon(R) CPU
E5-2673 v3 @
2.40GHz

Standard_F8s 8 1 Intel(R) 19 251.2 4.5


Xeon(R) CPU
E5-2673 v4 @
2.30GHz

Standard_F16 16 1 Intel(R) 9 413.9 3.6


s Xeon(R) CPU
E5-2673 v3 @
2.40GHz

Standard_F16 16 1 Intel(R) 36 471.8 7.5


s Xeon(R) CPU
E5-2673 v4 @
2.30GHz

F - Compute Optimized
SIZE VCPUS NUMA NODES CPU RUNS AVG BASE RATE STDDEV
SIZE VCPUS NUMA NODES CPU RUNS AVG BASE RATE STDDEV

Standard_F1 1 1 Intel(R) 15 32.8 1.8


Xeon(R) CPU
E5-2673 v3 @
2.40GHz

Standard_F1 1 1 Intel(R) 13 33.3 2.0


Xeon(R) CPU
E5-2673 v4 @
2.30GHz

Standard_F2 2 1 Intel(R) 27 64.9 6.0


Xeon(R) CPU
E5-2673 v3 @
2.40GHz

Standard_F2 2 1 Intel(R) 21 67.8 4.9


Xeon(R) CPU
E5-2673 v4 @
2.30GHz

Standard_F4 4 1 Intel(R) 18 128.4 3.3


Xeon(R) CPU
E5-2673 v3 @
2.40GHz

Standard_F4 4 1 Intel(R) 32 132.1 7.8


Xeon(R) CPU
E5-2673 v4 @
2.30GHz

Standard_F8 8 1 Intel(R) 17 239.4 2.3


Xeon(R) CPU
E5-2673 v3 @
2.40GHz

Standard_F8 8 1 Intel(R) 25 251.2 7.0


Xeon(R) CPU
E5-2673 v4 @
2.30GHz

Standard_F16 16 1 Intel(R) 19 424.1 8.2


Xeon(R) CPU
E5-2673 v3 @
2.40GHz

Standard_F16 16 1 Intel(R) 32 467.8 11.1


Xeon(R) CPU
E5-2673 v4 @
2.30GHz

Standard_F16 16 2 Intel(R) 6 472.3 13.2


Xeon(R) CPU
E5-2673 v3 @
2.40GHz

GS - Storage Optimized
SIZE VCPUS NUMA NODES CPU RUNS AVG BASE RATE STDDEV

Standard_GS1 2 1 Intel(R) 29 63.6 4.7


Xeon(R) CPU
E5-2698B v3
@ 2.00GHz

Standard_GS2 4 1 Intel(R) 29 122.3 6.9


Xeon(R) CPU
E5-2698B v3
@ 2.00GHz

Standard_GS3 8 1 Intel(R) 31 222.4 8.1


Xeon(R) CPU
E5-2698B v3
@ 2.00GHz

Standard_GS4 16 1 Intel(R) 31 391.4 28.6


Xeon(R) CPU
E5-2698B v3
@ 2.00GHz

Standard_GS4 4 1 Intel(R) 28 127.5 5.3


-4 Xeon(R) CPU
E5-2698B v3
@ 2.00GHz

Standard_GS4 8 1 Intel(R) 31 226.7 5.8


-8 Xeon(R) CPU
E5-2698B v3
@ 2.00GHz

Standard_GS5 32 2 Intel(R) 31 760.9 6.2


Xeon(R) CPU
E5-2698B v3
@ 2.00GHz

Standard_GS5 8 2 Intel(R) 31 259.5 2.7


-8 Xeon(R) CPU
E5-2698B v3
@ 2.00GHz

Standard_GS5 16 2 Intel(R) 31 447.9 4.0


-16 Xeon(R) CPU
E5-2698B v3
@ 2.00GHz

G - Compute Optimized
SIZE VCPUS NUMA NODES CPU RUNS AVG BASE RATE STDDEV

Standard_G1 2 1 Intel(R) 29 64.7 9.2


Xeon(R) CPU
E5-2698B v3
@ 2.00GHz
SIZE VCPUS NUMA NODES CPU RUNS AVG BASE RATE STDDEV

Standard_G2 4 1 Intel(R) 30 127.9 12.2


Xeon(R) CPU
E5-2698B v3
@ 2.00GHz

Standard_G3 8 1 Intel(R) 30 231.7 12.6


Xeon(R) CPU
E5-2698B v3
@ 2.00GHz

Standard_G4 16 1 Intel(R) 31 400.2 3.9


Xeon(R) CPU
E5-2698B v3
@ 2.00GHz

Standard_G5 32 2 Intel(R) 31 774.1 4.1


Xeon(R) CPU
E5-2698B v3
@ 2.00GHz

H - High Performance Compute (HPC)


SIZE VCPUS NUMA NODES CPU RUNS AVG BASE RATE STDDEV

Standard_H8 8 1 Intel(R) 31 296.1 1.4


Xeon(R) CPU
E5-2667 v3 @
3.20GHz

Standard_H8 8 1 Intel(R) 34 295.1 1.5


m Xeon(R) CPU
E5-2667 v3 @
3.20GHz

Standard_H16 16 2 Intel(R) 19 563.5 4.3


Xeon(R) CPU
E5-2667 v3 @
3.20GHz

Standard_H16 16 2 Intel(R) 19 562.9 3.3


m Xeon(R) CPU
E5-2667 v3 @
3.20GHz

Standard_H16 16 2 Intel(R) 18 563.6 3.7


mr Xeon(R) CPU
E5-2667 v3 @
3.20GHz

Standard_H16 16 2 Intel(R) 17 562.2 4.2


r Xeon(R) CPU
E5-2667 v3 @
3.20GHz

Ls - Storage Optimized
SIZE VCPUS NUMA NODES CPU RUNS AVG BASE RATE STDDEV

Standard_L4s 4 1 Intel(R) 29 122.7 6.6


Xeon(R) CPU
E5-2698B v3
@ 2.00GHz

Standard_L8s 8 1 Intel(R) 30 223.3 7.5


Xeon(R) CPU
E5-2698B v3
@ 2.00GHz

Standard_L16 16 1 Intel(R) 31 397.3 2.5


s Xeon(R) CPU
E5-2698B v3
@ 2.00GHz

Standard_L32 32 2 Intel(R) 31 766.1 3.5


s Xeon(R) CPU
E5-2698B v3
@ 2.00GHz

M - Memory Optimized
SIZE VCPUS NUMA NODES CPU RUNS AVG BASE RATE STDDEV

Standard_M8- 2 1 Intel(R) 15 42.1 2.1


2ms Xeon(R) CPU
E7-8890 v3 @
2.50GHz

Standard_M8- 4 1 Intel(R) 13 81.6 2.9


4ms Xeon(R) CPU
E7-8890 v3 @
2.50GHz

Standard_M1 4 1 Intel(R) 14 82.5 2.5


6-4ms Xeon(R) CPU
E7-8890 v3 @
2.50GHz

Standard_M1 8 1 Intel(R) 20 157.2 6.0


6-8ms Xeon(R) CPU
E7-8890 v3 @
2.50GHz

Standard_M3 8 1 Intel(R) 18 162.5 2.1


2-8ms Xeon(R) CPU
E7-8890 v3 @
2.50GHz

Standard_M3 16 1 Intel(R) 12 306.5 0.5


2-16ms Xeon(R) CPU
E7-8890 v3 @
2.50GHz
SIZE VCPUS NUMA NODES CPU RUNS AVG BASE RATE STDDEV

Standard_M6 64 2 Intel(R) 11 1010.9 5.4


4 Xeon(R) CPU
E7-8890 v3 @
2.50GHz

Standard_M6 16 2 Intel(R) 13 316.0 2.4


4-16ms Xeon(R) CPU
E7-8890 v3 @
2.50GHz

Standard_M6 32 2 Intel(R) 12 586.8 5.4


4-32ms Xeon(R) CPU
E7-8890 v3 @
2.50GHz

Standard_M6 64 2 Intel(R) 12 1005.5 12.3


4m Xeon(R) CPU
E7-8890 v3 @
2.50GHz

Standard_M6 64 2 Intel(R) 12 1012.9 12.5


4ms Xeon(R) CPU
E7-8890 v3 @
2.50GHz

Standard_M6 64 2 Intel(R) 12 1012.5 4.5


4s Xeon(R) CPU
E7-8890 v3 @
2.50GHz

Standard_M1 128 4 Intel(R) 11 1777.3 15.6


28 Xeon(R) CPU
E7-8890 v3 @
2.50GHz

Standard_M1 32 4 Intel(R) 13 620.5 2.5


28-32ms Xeon(R) CPU
E7-8890 v3 @
2.50GHz

Standard_M1 64 4 Intel(R) 12 1140.8 2.9


28-64ms Xeon(R) CPU
E7-8890 v3 @
2.50GHz

Standard_M1 128 4 Intel(R) 12 1778.3 10.3


28m Xeon(R) CPU
E7-8890 v3 @
2.50GHz

Standard_M1 128 4 Intel(R) 15 1780.7 18.3


28ms Xeon(R) CPU
E7-8890 v3 @
2.50GHz
SIZE VCPUS NUMA NODES CPU RUNS AVG BASE RATE STDDEV

Standard_M1 128 4 Intel(R) 12 1775.8 11.6


28s Xeon(R) CPU
E7-8890 v3 @
2.50GHz

Standard_M1 16 1 Intel(R) 20 293.1 11.8


6ms Xeon(R) CPU
E7-8890 v3 @
2.50GHz

Standard_M3 32 1 Intel(R) 13 535.2 4.8


2ls Xeon(R) CPU
E7-8890 v3 @
2.50GHz

Standard_M3 32 1 Intel(R) 11 534.1 4.6


2ms Xeon(R) CPU
E7-8890 v3 @
2.50GHz

Standard_M3 32 2 Intel(R) 1 589.0 0.0


2ms Xeon(R) CPU
E7-8890 v3 @
2.50GHz

Standard_M3 32 1 Intel(R) 12 538.6 3.2


2ts Xeon(R) CPU
E7-8890 v3 @
2.50GHz

Standard_M6 64 2 Intel(R) 13 1015.2 10.0


4ls Xeon(R) CPU
E7-8890 v3 @
2.50GHz

Standard_M8 8 1 Intel(R) 13 158.2 5.5


ms Xeon(R) CPU
E7-8890 v3 @
2.50GHz

NCSv3 - GPU Enabled


SIZE VCPUS NUMA NODES CPU RUNS AVG BASE RATE STDDEV

Standard_NC6 6 1 Intel(R) 6 230.2 1.6


s_v3 Xeon(R) CPU
E5-2690 v4 @
2.60GHz

Standard_NC1 12 1 Intel(R) 7 425.0 3.6


2s_v3 Xeon(R) CPU
E5-2690 v4 @
2.60GHz
SIZE VCPUS NUMA NODES CPU RUNS AVG BASE RATE STDDEV

Standard_NC2 24 2 Intel(R) 2 811.0 4.2


4rs_v3 Xeon(R) CPU
E5-2690 v4 @
2.60GHz

Standard_NC2 24 2 Intel(R) 3 809.3 2.3


4s_v3 Xeon(R) CPU
E5-2690 v4 @
2.60GHz

NCSv2 - GPU Enabled


SIZE VCPUS NUMA NODES CPU RUNS AVG BASE RATE STDDEV

Standard_NC6 6 1 Intel(R) 11 227.0 6.2


s_v2 Xeon(R) CPU
E5-2690 v4 @
2.60GHz

Standard_NC1 12 1 Intel(R) 9 427.3 1.3


2s_v2 Xeon(R) CPU
E5-2690 v4 @
2.60GHz

Standard_NC2 24 2 Intel(R) 12 811.0 5.4


4rs_v2 Xeon(R) CPU
E5-2690 v4 @
2.60GHz

Standard_NC2 24 2 Intel(R) 11 811.5 4.4


4s_v2 Xeon(R) CPU
E5-2690 v4 @
2.60GHz

NC - GPU Enabled
SIZE VCPUS NUMA NODES CPU RUNS AVG BASE RATE STDDEV

Standard_NC6 6 1 Intel(R) 27 209.6 4.4


Xeon(R) CPU
E5-2690 v3 @
2.60GHz

Standard_NC1 12 1 Intel(R) 28 394.4 3.8


2 Xeon(R) CPU
E5-2690 v3 @
2.60GHz

Standard_NC2 24 2 Intel(R) 28 751.7 3.5


4 Xeon(R) CPU
E5-2690 v3 @
2.60GHz
SIZE VCPUS NUMA NODES CPU RUNS AVG BASE RATE STDDEV

Standard_NC2 24 2 Intel(R) 27 752.9 3.4


4r Xeon(R) CPU
E5-2690 v3 @
2.60GHz

NDs- GPU Enabled


SIZE VCPUS NUMA NODES CPU RUNS AVG BASE RATE STDDEV

Standard_ND6 6 1 Intel(R) 8 230.1 1.2


s Xeon(R) CPU
E5-2690 v4 @
2.60GHz

Standard_ND1 12 1 Intel(R) 11 426.5 1.4


2s Xeon(R) CPU
E5-2690 v4 @
2.60GHz

Standard_ND2 24 2 Intel(R) 10 811.4 3.5


4rs Xeon(R) CPU
E5-2690 v4 @
2.60GHz

Standard_ND2 24 2 Intel(R) 11 812.6 4.4


4s Xeon(R) CPU
E5-2690 v4 @
2.60GHz

NV - GPU Enabled
SIZE VCPUS NUMA NODES CPU RUNS AVG BASE RATE STDDEV

Standard_NV6 6 1 Intel(R) 28 210.5 6.1


Xeon(R) CPU
E5-2690 v3 @
2.60GHz

Standard_NV1 12 1 Intel(R) 28 394.5 2.3


2 Xeon(R) CPU
E5-2690 v3 @
2.60GHz

Standard_NV2 24 2 Intel(R) 26 752.2 4.4


4 Xeon(R) CPU
E5-2690 v3 @
2.60GHz

About SPECint
Windows numbers were computed by running SPECint 2006 on Windows Server. SPECint was run using the
base rate option (SPECint_rate2006), with one copy per vCPU. SPECint consists of 12 separate tests, each run
three times, taking the median value from each test and weighting them to form a composite score. Those tests
were then run across multiple VMs to provide the average scores shown.

Next steps
For storage capacities, disk details, and additional considerations for choosing among VM sizes, see Sizes for
virtual machines.
Virtual machine vCPU quotas
1/10/2020 • 2 minutes to read • Edit Online

The vCPU quotas for virtual machines and virtual machine scale sets are arranged in two tiers for each
subscription, in each region. The first tier is the Total Regional vCPUs, and the second tier is the various VM size
family cores such as the D -series vCPUs. Any time a new VM is deployed the vCPUs for the VM must not exceed
the vCPU quota for the VM size family or the total regional vCPU quota. If either of those quotas are exceeded, the
VM deployment will not be allowed. There is also a quota for the overall number of virtual machines in the region.
The details on each of these quotas can be seen in the Usage + quotas section of the Subscription page in the
Azure portal, or you can query for the values using PowerShell.

Check usage
You can use the Get-AzVMUsage cmdlet to check on your quota usage.

Get-AzVMUsage -Location "East US"

The output will look similar to this:

Name Current Value Limit Unit


---- ------------- ----- ----
Availability Sets 0 2000 Count
Total Regional vCPUs 4 260 Count
Virtual Machines 4 10000 Count
Virtual Machine Scale Sets 1 2000 Count
Standard B Family vCPUs 1 10 Count
Standard DSv2 Family vCPUs 1 100 Count
Standard Dv2 Family vCPUs 2 100 Count
Basic A Family vCPUs 0 100 Count
Standard A0-A7 Family vCPUs 0 250 Count
Standard A8-A11 Family vCPUs 0 100 Count
Standard D Family vCPUs 0 100 Count
Standard G Family vCPUs 0 100 Count
Standard DS Family vCPUs 0 100 Count
Standard GS Family vCPUs 0 100 Count
Standard F Family vCPUs 0 100 Count
Standard FS Family vCPUs 0 100 Count
Standard NV Family vCPUs 0 24 Count
Standard NC Family vCPUs 0 48 Count
Standard H Family vCPUs 0 8 Count
Standard Av2 Family vCPUs 0 100 Count
Standard LS Family vCPUs 0 100 Count
Standard Dv2 Promo Family vCPUs 0 100 Count
Standard DSv2 Promo Family vCPUs 0 100 Count
Standard MS Family vCPUs 0 0 Count
Standard Dv3 Family vCPUs 0 100 Count
Standard DSv3 Family vCPUs 0 100 Count
Standard Ev3 Family vCPUs 0 100 Count
Standard ESv3 Family vCPUs 0 100 Count
Standard FSv2 Family vCPUs 0 100 Count
Standard ND Family vCPUs 0 0 Count
Standard NCv2 Family vCPUs 0 0 Count
Standard NCv3 Family vCPUs 0 0 Count
Standard LSv2 Family vCPUs 0 0 Count
Standard Storage Managed Disks 2 10000 Count
Premium Storage Managed Disks 1 10000 Count
Reserved VM Instances
Reserved VM Instances, which are scoped to a single subscription without VM size flexibility, will add a new aspect
to the vCPU quotas. These values describe the number of instances of the stated size that must be deployable in
the subscription. They work as a placeholder in the quota system to ensure that quota is reserved to ensure
reserved VM instances are deployable in the subscription. For example, if a specific subscription has 10
Standard_D1 reserved VM instances the usages limit for Standard_D1 reserved VM instances will be 10. This will
cause Azure to ensure that there are always at least 10 vCPUs available in the Total Regional vCPUs quota to be
used for Standard_D1 instances and there are at least 10 vCPUs available in the Standard D Family vCPU quota to
be used for Standard_D1 instances.
If a quota increase is required to purchase a Single Subscription RI, you can request a quota increase on your
subscription.

Next steps
For more information about billing and quotas, see Azure subscription and service limits, quotas, and constraints.
Save costs with Azure Reserved VM Instances
11/12/2019 • 7 minutes to read • Edit Online

When you commit to an Azure reserved VM instance you can save money. The reservation discount is applied
automatically to the number of running virtual machines that match the reservation scope and attributes. You don't
need to assign a reservation to a virtual machine to get the discounts. A reserved instance purchase covers only
the compute part of your VM usage. For Windows VMs, the usage meter is split into two separate meters. There's
a compute meter, which is same as the Linux meter, and a Windows IP meter. The charges that you see when you
make the purchase are only for the compute costs. Charges don't include Windows software costs. For more
information about software costs, see Software costs not included with Azure Reserved VM Instances.

Determine the right VM size before you buy


Before you buy a reservation, you should determine the size of the VM that you need. The following sections will
help you determine the right VM size.
Use reservation recommendations
You can use reservation recommendations to help determine the reservations you should purchase.
Purchase recommendations and recommended quantity are show when you purchase a VM reserved instance
in the Azure portal.
Azure Advisor provides purchase recommendations for individual subscriptions.
You can use the APIs to get purchase recommendations for both shared scope and single subscription scope.
For more information, see Reserved instance purchase recommendation APIs for enterprise customers.
For Enterprise Agreement (EA) and Microsoft Customer Agreement (MCA) customers, purchase
recommendations for shared and single subscription scopes are available with the Azure Consumption Insights
Power BI content pack.
Services that get VM reservation discounts
Your VM reservations can apply to VM usage emitted from multiple services - not just for your VM deployments.
Resources that get reservation discounts change depending on the instance size flexibility setting.
Instance size flexibility setting
The instance size flexibility setting determines which services get the reserved instance discounts.
Whether the setting is on or off, reservation discounts automatically apply to any matching VM usage when the
ConsumedService is Microsoft.Compute . So, check your usage data for the ConsumedService value. Some
examples include:
Virtual machines
Virtual machine scale sets
Container service
Azure Batch deployments (in user subscriptions mode)
Azure Kubernetes Service (AKS )
Service Fabric
When the setting is on, reservation discounts automatically apply to matching VM usage when the
ConsumedService is any of the following items:
Microsoft.Compute
Microsoft.ClassicCompute
Microsoft.Batch
Microsoft.MachineLearningServices
Microsoft.Kusto
Check the ConsumedService value in your usage data to determine if the usage is eligible for reservation
discounts.
For more information about instance size flexibility, see Virtual machine size flexibility with Reserved VM Instances.
Analyze your usage information
Analyze your usage information to help determine which reservations you should purchase.
Usage data is available in the usage file and APIs. Use them together to determine which reservation to purchase.
Check for VM instances that have high usage on daily basis to determine the quantity of reservations to purchase.
Avoid the Meter subcategory and Product fields in usage data. They don't distinguish between VM sizes that use
premium storage. If you use these fields to determine the VM size for reservation purchase, you may buy the
wrong size. Then you won't get the reservation discount you expect. Instead, refer to the AdditionalInfo field in
your usage file or usage API to determine the correct VM size.
Purchase restriction considerations
Reserved VM Instances are available for most VM sizes with some exceptions. Reservation discounts don't apply
for the following VMs:
VM series - A-series, Av2-series, or G -series.
Preview or Promo VMs - Any VM -series or size that is in preview or uses promotional meter.
Clouds - Reservations aren't available for purchase in Germany or China regions.
Insufficient quota - A reservation that is scoped to a single subscription must have vCPU quota available
in the subscription for the new RI. For example, if the target subscription has a quota limit of 10 vCPUs for
D -Series, then you can't buy a reservation for 11 Standard_D1 instances. The quota check for reservations
includes the VMs already deployed in the subscription. For example, if the subscription has a quota of 10
vCPUs for D -Series and has two standard_D1 instances deployed, then you can buy a reservation for 10
standard_D1 instances in this subscription. You can create quote increase request to resolve this issue.
Capacity restrictions - In rare circumstances, Azure limits the purchase of new reservations for subset of
VM sizes, because of low capacity in a region.

Buy a Reserved VM Instance


You can buy a reserved VM instance in the Azure portal. Pay for the reservation up front or with monthly
payments. These requirements apply to buying a reserved VM instance:
You must be in an Owner role for at least one EA subscription or a subscription with a pay-as-you-go rate.
For EA subscriptions, the Add Reserved Instances option must be enabled in the EA portal. Or, if that setting
is disabled, you must be an EA Admin for the subscription.
For the Cloud Solution Provider (CSP ) program, only the admin agents or sales agents can buy reservations.
To buy an instance:
1. Sign in to the Azure portal.
2. Select All services > Reservations.
3. Select Add to purchase a new reservation and then click Virtual machine.
4. Enter required fields. Running VM instances that match the attributes you select qualify to get the reservation
discount. The actual number of your VM instances that get the discount depend on the scope and quantity
selected.
If you have an EA agreement, you can use the Add more option to quickly add additional instances. The option
isn't available for other subscription types.

FIELD DESCRIPTION

Subscription The subscription used to pay for the reservation. The payment
method on the subscription is charged the costs for the
reservation. The subscription type must be an enterprise
agreement (offer numbers: MS-AZR-0017P or MS-AZR-
0148P) or Microsoft Customer Agreement or an individual
subscription with pay-as-you-go rates (offer numbers: MS-
AZR-0003P or MS-AZR-0023P). The charges are deducted
from the monetary commitment balance, if available, or
charged as overage. For a subscription with pay-as-you-go
rates, the charges are billed to the credit card or invoice
payment method on the subscription.

Scope The reservation’s scope can cover one subscription or multiple


subscriptions (shared scope). If you select:
Single resource group scope — Applies the
reservation discount to the matching resources in the
selected resource group only.
Single subscription scope — Applies the reservation
discount to the matching resources in the selected
subscription.
Shared scope — Applies the reservation discount to
matching resources in eligible subscriptions that are in
the billing context. For EA customers, the billing
context is the enrollment. For individual subscriptions
with pay-as-you-go rates, the billing scope is all
eligible subscriptions created by the account
administrator.

Region The Azure region that’s covered by the reservation.

VM Size The size of the VM instances.

Optimize for VM instance size flexibility is selected by default. Click


Advanced settings to change the instance size flexibility
value to apply the reservation discount to other VMs in the
same VM size group. Capacity priority prioritizes data center
capacity for your deployments. It offers additional confidence
in your ability to launch the VM instances when you need
them. Capacity priority is only available when the reservation
scope is single subscription.

Term One year or three years.

Quantity The number of instances being purchased within the


reservation. The quantity is the number of running VM
instances that can get the billing discount. For example, if you
are running 10 Standard_D2 VMs in the East US, then you
would specify quantity as 10 to maximize the benefit for all
running VMs.
Usage data and reservation utilization
Your usage data has an effective price of zero for the usage that gets a reservation discount. You can see which VM
instance received the reservation discount for each reservation.
For more information about how reservation discounts appear in usage data, see Understand Azure reservation
usage for your Enterprise enrollment if you are an EA customer. If you have an individual subscription, see
Understand Azure reservation usage for your Pay-As-You-Go subscription.

Change a reservation after purchase


You can make the following types of changes to a reservation after purchase:
Update reservation scope
Instance size flexibility (if applicable)
Ownership
You can also split a reservation into smaller chunks and merge already split reservations. None of the changes
cause a new commercial transaction or change the end date of the reservation.
You can't make the following types of changes after purchase, directly:
An existing reservation’s region
SKU
Quantity
Duration
However, you can exchange a reservation if you want to make changes.

Cancel, exchange, or refund reservations


You can cancel, exchange, or refund reservations with certain limitations. For more information, see Self-service
exchanges and refunds for Azure Reservations.

Need help? Contact us.


If you have questions or need help, create a support request.

Next steps
To learn how to manage a reservation, see Manage Azure Reservations.
To learn more about Azure Reservations, see the following articles:
What are Azure Reservations?
Manage Reservations in Azure
Understand how the reservation discount is applied
Understand reservation usage for a subscription with pay-as-you-go rates
Understand reservation usage for your Enterprise enrollment
Windows software costs not included with reservations
Azure Reservations in Partner Center Cloud Solution Provider (CSP ) program
2 minutes to read
Virtual machine size flexibility with Reserved VM
Instances
2/19/2020 • 2 minutes to read • Edit Online

When you buy a Reserved VM Instance, you can choose to optimize for instance size flexibility or capacity priority.
For more information about setting or changing the optimize setting for reserved VM instances, see Change the
optimize setting for reserved VM instances.
With a reserved virtual machine instance that's optimized for instance size flexibility, the reservation you buy can
apply to the virtual machines (VMs) sizes in the same instance size flexibility group. For example, if you buy a
reservation for a VM size that's listed in the DSv2 Series, like Standard_DS5_v2, the reservation discount can apply
to the other four sizes that are listed in that same instance size flexibility group:
Standard_DS1_v2
Standard_DS2_v2
Standard_DS3_v2
Standard_DS4_v2
But that reservation discount doesn't apply to VMs sizes that are listed in different instance size flexibility groups,
like SKUs in DSv2 Series High Memory: Standard_DS11_v2, Standard_DS12_v2, and so on.
Within the instance size flexibility group, the number of VMs the reservation discount applies to depends on the
VM size you pick when you buy a reservation. It also depends on the sizes of the VMs that you have running. The
ratio column compares the relative footprint for each VM size in that instance size flexibility group. Use the ratio
value to calculate how the reservation discount applies to the VMs you have running.

Examples
The following examples use the sizes and ratios in the DSv2-series table.
You buy a reserved VM instance with the size Standard_DS4_v2 where the ratio or relative footprint compared to
the other sizes in that series is 8.
Scenario 1: Run eight Standard_DS1_v2 sized VMs with a ratio of 1. Your reservation discount applies to all
eight of those VMs.
Scenario 2: Run two Standard_DS2_v2 sized VMs with a ratio of 2 each. Also run a Standard_DS3_v2 sized VM
with a ratio of 4. The total footprint is 2+2+4=8. So your reservation discount applies to all three of those VMs.
Scenario 3: Run one Standard_DS5_v2 with a ratio of 16. Your reservation discount applies to half that VM's
compute cost.
The following sections show what sizes are in the same size series group when you buy a reserved VM instance
optimized for instance size flexibility.

Instance size flexibility ratio for VMs


CSV below has the instance size flexibility groups, ArmSkuName and the ratios.
Instance size flexibility ratios
We will keep the file URL and the schema fixed so you can consume this file programmatically. The data will also
be available through API soon.
Azure Dedicated Hosts
1/9/2020 • 7 minutes to read • Edit Online

Azure Dedicated Host is a service that provides physical servers - able to host one or more virtual machines -
dedicated to one Azure subscription. Dedicated hosts are the same physical servers used in our data centers,
provided as a resource. You can provision dedicated hosts within a region, availability zone, and fault domain.
Then, you can place VMs directly into your provisioned hosts, in whatever configuration best meets your needs.

Limitations
Virtual machine scale sets are not currently supported on dedicated hosts.
The following VM series are supported: DSv3, ESv3 and Fsv2.

Benefits
Reserving the entire host provides the following benefits:
Hardware isolation at the physical server level. No other VMs will be placed on your hosts. Dedicated hosts are
deployed in the same data centers and share the same network and underlying storage infrastructure as other,
non-isolated hosts.
Control over maintenance events initiated by the Azure platform. While the majority of maintenance events
have little to no impact on your virtual machines, there are some sensitive workloads where each second of
pause can have an impact. With dedicated hosts, you can opt-in to a maintenance window to reduce the impact
to your service.
With the Azure hybrid benefit, you can bring your own licenses for Windows and SQL to Azure. Using the
hybrid benefits provides you with additional benefits. For more information, see Azure Hybrid Benefit.

Groups, hosts, and VMs

A host group is a resource that represents a collection of dedicated hosts. You create a host group in a region and
an availability zone, and add hosts to it.
A host is a resource, mapped to a physical server in an Azure data center. The physical server is allocated when
the host is created. A host is created within a host group. A host has a SKU describing which VM sizes can be
created. Each host can host multiple VMs, of different sizes, as long as they are from the same size series.
When creating a VM in Azure, you can select which dedicated host to use for your VM. You have full control as to
which VMs are placed on your hosts.

High Availability considerations


For high availability, you should deploy multiple VMs, spread across multiple hosts (minimum of 2). With Azure
Dedicated Hosts, you have several options to provision your infrastructure to shape your fault isolation
boundaries.
Use Availability Zones for fault isolation
Availability zones are unique physical locations within an Azure region. Each zone is made up of one or more
datacenters equipped with independent power, cooling, and networking. A host group is created in a single
availability zone. Once created, all hosts will be placed within that zone. To achieve high availability across zones,
you need to create multiple host groups (one per zone) and spread your hosts accordingly.
If you assign a host group to an availability zone, all VMs created on that host must be created in the same zone.
Use Fault Domains for fault isolation
A host can be created in a specific fault domain. Just like VM in a scale set or availability set, hosts in different fault
domains will be placed on different physical racks in the data center. When you create a host group, you are
required to specify the fault domain count. When creating hosts within the host group, you assign fault domain for
each host. The VMs do not require any fault domain assignment.
Fault domains are not the same as collocation. Having the same fault domain for two hosts does not mean they
are in proximity with each other.
Fault domains are scoped to the host group. You should not make any assumption on anti-affinity between two
host groups (unless they are in different availability zones).
VMs deployed to hosts with different fault domains, will have their underlying managed disks services on multiple
storage stamps, to increase the fault isolation protection.
Using Availability Zones and Fault Domains
You can use both capabilities together to achieve even more fault isolation. In this case, you will specify the
availability zone and fault domain count in for each host group, assign a fault domain to each of your hosts in the
group, and assign an availability zone to each of your VMs
The Resource Manager sample template found here uses zones and fault domains to spread hosts for maximum
resiliency in a region.

Maintenance control
The infrastructure supporting your virtual machines may occasionally be updated to improve reliability,
performance, security, and to launch new features. The Azure platform tries to minimize the impact of platform
maintenance whenever possible, but customers with maintenance sensitive workloads can't tolerate even few
seconds that the VM needs to be frozen or disconnected for maintenance.
Maintenance Control provides customers with an option to skip regular platform updates scheduled on their
dedicated hosts, then apply it at the time of their choice within a 35-day rolling window.

NOTE
Maintenance control is currently in public preview. For more information, see Control updates with Maintenance Control
using CLI or PowerShell.

Capacity considerations
Once a dedicated host is provisioned, Azure assigns it to physical server. This guarantees the availability of the
capacity when you need to provision your VM. Azure uses the entire capacity in the region (or zone) to pick a
physical server for your host. It also means that customers can expect to be able to grow their dedicated host
footprint without the concern of running out of space in the cluster.
Quotas
There is a default quota limit of 3000 vCPUs for dedicated hosts, per region. But, the number of hosts you can
deploy is also limited by the quota for the VM size family used for the host. For example, a Pay-as-you-go
subscription may only have a quota of 10 vCPUs available for the Dsv3 size series, in the East US region. In this
case, you need to request a quota increase to at least 64 vCPUs before you can deploy a dedicated host. Select the
Request increase button in the upper right corner to file a request if needed.

For more information, see Virtual machine vCPU quotas.


Free trial and MSDN subscriptions do not have quota for Azure Dedicated Hosts.

Pricing
Users are charged per dedicated host, regardless how many VMs are deployed. In your monthly statement you
will see a new billable resource type of hosts. The VMs on a dedicated host will still be shown in your statement,
but will carry a price of 0.
The host price is set based on VM family, type (hardware size), and region. A host price is relative to the largest
VM size supported on the host.
Software licensing, storage and network usage are billed separately from the host and VMs. There is no change to
those billable items.
For more information, see Azure Dedicated Host pricing.

VM families and Hardware generations


A SKU is defined for a host and it represents the VM size series and type. You can mix multiple VMs of different
sizes within a single host as long as they are of the same size series. The type is the hardware generation currently
available in the region.
Different types for the same VM series will be from different CPU vendors and have different CPU generations
and number of cores.
Refer to the host pricing page to learn more.
Dedicated hosts support the following host SKU\types: DSv3_Type1 and ESv3_Type1

Host life cycle


Azure monitors and manages the health status of your hosts. The following states will be returned when you
query your host:
HEALTH STATE DESCRIPTION

Host Available There are no known issues with your host.

Host Under Investigation We’re having some issues with the host which we’re looking
into. This is a transitional state required for Azure to try and
identify the scope and root cause for the issue identified.
Virtual machines running on the host may be impacted.

Host Pending Deallocate Azure can’t restore the host back to a healthy state and ask
you to redeploy your virtual machines out of this host. If
autoReplaceOnFailure is enabled, your virtual machines are
service healed to healthy hardware. Otherwise, your virtual
machine may be running on a host that is about to fail.

Host deallocated All virtual machines have been removed from the host. You
are no longer being charged for this host since the hardware
was taken out of rotation.

Next steps
You can deploy a dedicated host using Azure PowerShell, the portal, and Azure CLI.
There is sample template, found here, that uses both zones and fault domains for maximum resiliency in a
region.
Maintenance for virtual machines in Azure
2/10/2020 • 6 minutes to read • Edit Online

Azure periodically updates its platform to improve the reliability, performance, and security of the host
infrastructure for virtual machines. The purpose of these updates ranges from patching software components in
the hosting environment to upgrading networking components or decommissioning hardware.
Updates rarely affect the hosted VMs. When updates do have an effect, Azure chooses the least impactful method
for updates:
If the update doesn't require a reboot, the VM is paused while the host is updated, or the VM is live-migrated to
an already updated host.
If maintenance requires a reboot, you're notified of the planned maintenance. Azure also provides a time
window in which you can start the maintenance yourself, at a time that works for you. The self-maintenance
window is typically 30 days unless the maintenance is urgent. Azure is investing in technologies to reduce the
number of cases in which planned platform maintenance requires the VMs to be rebooted. For instructions on
managing planned maintenance, see Handling planned maintenance notifications using the Azure CLI,
PowerShell or portal.
This page describes how Azure performs both types of maintenance. For more information about unplanned
events (outages), see Manage the availability of VMs for Windows or the corresponding article for Linux.
Within a VM, you can get notifications about upcoming maintenance by using Scheduled Events for Windows or
for Linux.

Maintenance that doesn't require a reboot


Most platform updates don't affect customer VMs. When a no-impact update isn't possible, Azure chooses the
update mechanism that's least impactful to customer VMs.
Most nonzero-impact maintenance pauses the VM for less than 10 seconds. In certain cases, Azure uses memory-
preserving maintenance mechanisms. These mechanisms pause the VM for up to 30 seconds and preserve the
memory in RAM. The VM is then resumed, and its clock is automatically synchronized.
Memory-preserving maintenance works for more than 90 percent of Azure VMs. It doesn't work for G, M, N, and
H series. Azure increasingly uses live-migration technologies and improves memory-preserving maintenance
mechanisms to reduce the pause durations.
These maintenance operations that don't require a reboot are applied one fault domain at a time. They stop if they
receive any warning health signals.
These types of updates can affect some applications. When the VM is live-migrated to a different host, some
sensitive workloads might show a slight performance degradation in the few minutes leading up to the VM pause.
To prepare for VM maintenance and reduce impact during Azure maintenance, try using Scheduled Events for
Windows or Linux for such applications.
There is also a feature, maintenance control, in public preview that can help manage maintenance that doesn't
require a reboot. You must be using either Azure Dedicated Hosts or an isolated VM. Maintenance control gives
you the option to skip platform updates and apply the updates at your choice of time within a 35-day rolling
window. For more information, see Control updates with Maintenance Control and the Azure CLI.
Live migration
Live migration is an operation that doesn't require a reboot and that preserves memory for the VM. It causes a
pause or freeze, typically lasting no more than 5 seconds. Except for G, M, N, and H series, all infrastructure as a
service (IaaS ) VMs, are eligible for live migration. Eligible VMs represent more than 90 percent of the IaaS VMs
that are deployed to the Azure fleet.
The Azure platform starts live migration in the following scenarios:
Planned maintenance
Hardware failure
Allocation optimizations
Some planned-maintenance scenarios use live migration, and you can use Scheduled Events to know in advance
when live migration operations will start.
Live migration can also be used to move VMs when Azure Machine Learning algorithms predict an impending
hardware failure or when you want to optimize VM allocations. For more information about predictive modeling
that detects instances of degraded hardware, see Improving Azure VM resiliency with predictive machine learning
and live migration. Live-migration notifications appear in the Azure portal in the Monitor and Service Health logs
as well as in Scheduled Events if you use these services.

Maintenance that requires a reboot


In the rare case where VMs need to be rebooted for planned maintenance, you'll be notified in advance. Planned
maintenance has two phases: the self-service phase and a scheduled maintenance phase.
During the self-service phase, which typically lasts four weeks, you start the maintenance on your VMs. As part of
the self-service, you can query each VM to see its status and the result of your last maintenance request.
When you start self-service maintenance, your VM is redeployed to an already updated node. Because the VM
reboots, the temporary disk is lost and dynamic IP addresses associated with the virtual network interface are
updated.
If an error arises during self-service maintenance, the operation stops, the VM isn't updated, and you get the
option to retry the self-service maintenance.
When the self-service phase ends, the scheduled maintenance phase begins. During this phase, you can still query
for the maintenance phase, but you can't start the maintenance yourself.
For more information on managing maintenance that requires a reboot, see Handling planned maintenance
notifications using the Azure CLI, PowerShell or portal.
Availability considerations during scheduled maintenance
If you decide to wait until the scheduled maintenance phase, there are a few things you should consider to
maintain the highest availability of your VMs.
Paired regions
Each Azure region is paired with another region within the same geographical vicinity. Together, they make a
region pair. During the scheduled maintenance phase, Azure updates only the VMs in a single region of a region
pair. For example, while updating the VM in North Central US, Azure doesn't update any VM in South Central US
at the same time. However, other regions such as North Europe can be under maintenance at the same time as
East US. Understanding how region pairs work can help you better distribute your VMs across regions. For more
information, see Azure region pairs.
Availability sets and scale sets
When deploying a workload on Azure VMs, you can create the VMs within an availability set to provide high
availability to your application. Using availability sets, you can ensure that during either an outage or maintenance
events that require a reboot, at least one VM is available.
Within an availability set, individual VMs are spread across up to 20 update domains. During scheduled
maintenance, only one update domain is updated at any given time. Update domains aren't necessarily updated
sequentially.
Virtual machine scale sets are an Azure compute resource that you can use to deploy and manage a set of identical
VMs as a single resource. The scale set is automatically deployed across UDs, like VMs in an availability set. As
with availability sets, when you use scale sets, only one UD is updated at any given time during scheduled
maintenance.
For more information about setting up your VMs for high availability, see Manage the availability of your VMs for
Windows or the corresponding article for Linux.
Availability zones
Availability zones are unique physical locations within an Azure region. Each zone is made up of one or more
datacenters equipped with independent power, cooling, and networking. To ensure resiliency, there’s a minimum of
three separate zones in all enabled regions.
An availability zone is a combination of a fault domain and an update domain. If you create three or more VMs
across three zones in an Azure region, your VMs are effectively distributed across three fault domains and three
update domains. The Azure platform recognizes this distribution across update domains to make sure that VMs in
different zones are not updated at the same time.
Each infrastructure update rolls out zone by zone, within a single region. But, you can have deployment going on in
Zone 1, and different deployment going in Zone 2, at the same time. Deployments are not all serialized. But, a
single deployment only rolls out one zone at a time to reduce risk.

Next steps
You can use the Azure CLI, Azure PowerShell or the portal to manage planned maintenance.
Introduction to Azure managed disks
12/16/2019 • 9 minutes to read • Edit Online

Azure managed disks are block-level storage volumes that are managed by Azure and used with Azure Virtual
Machines. Managed disks are like a physical disk in an on-premises server but virtualized. With managed disks,
all you have to do is specify the disk size, the disk type, and provision the disk. Once you provision the disk,
Azure handles the rest.
The available types of disks are ultra disks, premium solid-state drives (SSD ), standard SSDs, and standard hard
disk drives (HDD ). For information about each individual disk type, see Select a disk type for IaaS VMs.

Benefits of managed disks


Let's go over some of the benefits you gain by using managed disks.
Highly durable and available
Managed disks are designed for 99.999% availability. Managed disks achieve this by providing you with three
replicas of your data, allowing for high durability. If one or even two replicas experience issues, the remaining
replicas help ensure persistence of your data and high tolerance against failures. This architecture has helped
Azure consistently deliver enterprise-grade durability for infrastructure as a service (IaaS ) disks, with an
industry-leading ZERO% annualized failure rate.
Simple and scalable VM deployment
Using managed disks, you can create up to 50,000 VM disks of a type in a subscription per region, allowing you
to create thousands of VMs in a single subscription. This feature also further increases the scalability of virtual
machine scale sets by allowing you to create up to 1,000 VMs in a virtual machine scale set using a Marketplace
image.
Integration with availability sets
Managed disks are integrated with availability sets to ensure that the disks of VMs in an availability set are
sufficiently isolated from each other to avoid a single point of failure. Disks are automatically placed in different
storage scale units (stamps). If a stamp fails due to hardware or software failure, only the VM instances with
disks on those stamps fail. For example, let's say you have an application running on five VMs, and the VMs are
in an Availability Set. The disks for those VMs won't all be stored in the same stamp, so if one stamp goes down,
the other instances of the application continue to run.
Integration with Availability Zones
Managed disks support Availability Zones, which is a high-availability offering that protects your applications
from datacenter failures. Availability Zones are unique physical locations within an Azure region. Each zone is
made up of one or more datacenters equipped with independent power, cooling, and networking. To ensure
resiliency, there’s a minimum of three separate zones in all enabled regions. With Availability Zones, Azure offers
industry best 99.99% VM uptime SLA.
Azure Backup support
To protect against regional disasters, Azure Backup can be used to create a backup job with time-based backups
and backup retention policies. This allows you to perform easy VM restorations at will. Currently Azure Backup
supports disk sizes up to four tebibyte (TiB ) disks. Azure Backup supports backup and restore of managed disks.
Learn more about Azure VM backup support.
Granular access control
You can use Azure role-based access control (RBAC ) to assign specific permissions for a managed disk to one or
more users. Managed disks expose a variety of operations, including read, write (create/update), delete, and
retrieving a shared access signature (SAS ) URI for the disk. You can grant access to only the operations a person
needs to perform their job. For example, if you don't want a person to copy a managed disk to a storage account,
you can choose not to grant access to the export action for that managed disk. Similarly, if you don't want a
person to use an SAS URI to copy a managed disk, you can choose not to grant that permission to the managed
disk.
Upload your vhd
Direct upload makes it easy to transfer your vhd to an Azure managed disk. Previously, you had to follow a more
involved process that included staging your data in a storage account. Now, there are fewer steps. It is easier to
upload on premises VMs to Azure, upload to large managed disks, and the backup and restore process is
simplified. It also reduces cost by allowing you to upload data to managed disks directly without attaching them
to VMs. You can use direct upload to upload vhds up to 32 TiB in size.
To learn how to transfer your vhd to Azure, see the CLI or PowerShell articles.

Encryption
Managed disks offer two different kinds of encryption. The first is Server Side Encryption (SSE ), which is
performed by the storage service. The second one is Azure Disk Encryption (ADE ), which you can enable on the
OS and data disks for your VMs.
Server-side encryption
Azure Server-side Encryption provides encryption-at-rest and safeguards your data to meet your organizational
security and compliance commitments. Server-side encryption is enabled by default for all managed disks,
snapshots, and images in all the regions where managed disks are available. You can either allow Azure to
manage your keys for you, these are platform-managed keys, or you can manage the keys yourself, these are
customer-managed keys. Visit the Managed Disks FAQ page for more details.
Azure Disk Encryption
Azure Disk Encryption allows you to encrypt the OS and Data disks used by an IaaS Virtual Machine. This
encryption includes managed disks. For Windows, the drives are encrypted using industry-standard BitLocker
encryption technology. For Linux, the disks are encrypted using the DM -Crypt technology. The encryption
process is integrated with Azure Key Vault to allow you to control and manage the disk encryption keys. For
more information, see Azure Disk Encryption for IaaS VMs.

Disk roles
There are three main disk roles in Azure: the data disk, the OS disk, and the temporary disk. These roles map to
disks that are attached to your virtual machine.

Data disk
A data disk is a managed disk that's attached to a virtual machine to store application data, or other data you
need to keep. Data disks are registered as SCSI drives and are labeled with a letter that you choose. Each data
disk has a maximum capacity of 32,767 gibibytes (GiB ). The size of the virtual machine determines how many
data disks you can attach to it and the type of storage you can use to host the disks.
OS disk
Every virtual machine has one attached operating system disk. That OS disk has a pre-installed OS, which was
selected when the VM was created. This disk contains the boot volume.
This disk has a maximum capacity of 2,048 GiB.
Temporary disk
Every VM contains a temporary disk, which is not a managed disk. The temporary disk provides short-term
storage for applications and processes and is intended to only store data such as page or swap files. Data on the
temporary disk may be lost during a maintenance event event or when you redeploy a VM. On Azure Linux
VMs, the temporary disk is /dev/sdb by default and on Windows VMs the temporary disk is D: by default.
During a successful standard reboot of the VM, the data on the temporary disk will persist.

Managed disk snapshots


A managed disk snapshot is a read-only crash-consistent full copy of a managed disk that is stored as a standard
managed disk by default. With snapshots, you can back up your managed disks at any point in time. These
snapshots exist independent of the source disk and can be used to create new managed disks.
Snapshots are billed based on the used size. For example, if you create a snapshot of a managed disk with
provisioned capacity of 64 GiB and actual used data size of 10 GiB, that snapshot is billed only for the used data
size of 10 GiB. You can see the used size of your snapshots by looking at the Azure usage report. For example, if
the used data size of a snapshot is 10 GiB, the daily usage report will show 10 GiB/(31 days) = 0.3226 as the
consumed quantity.
To learn more about how to create snapshots for managed disks, see the following resources:
Create a snapshot of a managed disk in Windows
Create a snapshot of a managed disk in Linux
Images
Managed disks also support creating a managed custom image. You can create an image from your custom VHD
in a storage account or directly from a generalized (sysprepped) VM. This process captures a single image. This
image contains all managed disks associated with a VM, including both the OS and data disks. This managed
custom image enables creating hundreds of VMs using your custom image without the need to copy or manage
any storage accounts.
For information on creating images, see the following articles:
How to capture a managed image of a generalized VM in Azure
How to generalize and capture a Linux virtual machine using the Azure CLI
Images versus snapshots
It's important to understand the difference between images and snapshots. With managed disks, you can take an
image of a generalized VM that has been deallocated. This image includes all of the disks attached to the VM.
You can use this image to create a VM, and it includes all of the disks.
A snapshot is a copy of a disk at the point in time the snapshot is taken. It applies only to one disk. If you have a
VM that has one disk (the OS disk), you can take a snapshot or an image of it and create a VM from either the
snapshot or the image.
A snapshot doesn't have awareness of any disk except the one it contains. This makes it problematic to use in
scenarios that require the coordination of multiple disks, such as striping. Snapshots would need to be able to
coordinate with each other and this is currently not supported.

Disk allocation and performance


The following diagram depicts real-time allocation of bandwidth and IOPS for disks, using a three-level
provisioning system:

The first level provisioning sets the per-disk IOPS and bandwidth assignment. At the second level, compute
server host implements SSD provisioning, applying it only to data that is stored on the server’s SSD, which
includes disks with caching (ReadWrite and ReadOnly) as well as local and temp disks. Finally, VM network
provisioning takes place at the third level for any I/O that the compute host sends to Azure Storage's backend.
With this scheme, the performance of a VM depends on a variety of factors, from how the VM uses the local
SSD, to the number of disks attached, as well as the performance and caching type of the disks it has attached.
As an example of these limitations, a Standard_DS1v1 VM is prevented from achieving the 5,000 IOPS potential
of a P30 disk, whether it is cached or not, because of limits at the SSD and network levels:
Azure uses prioritized network channel for disk traffic, which gets the precedence over other low priority of
network traffic. This helps disks maintain their expected performance in case of network contentions. Similarly,
Azure Storage handles resource contentions and other issues in the background with automatic load balancing.
Azure Storage allocates required resources when you create a disk, and applies proactive and reactive balancing
of resources to handle the traffic level. This further ensures disks can sustain their expected IOPS and
throughput targets. You can use the VM -level and Disk-level metrics to track the performance and setup alerts as
needed.
Refer to our design for high performance article, to learn the best practices for optimizing VM + Disk
configurations so that you can achieve your desired performance

Next steps
If you'd like a video going into more detail on managed disks, check out: Better Azure VM Resiliency with
Managed Disks.
Learn more about the individual disk types Azure offers, which type is a good fit for your needs, and learn about
their performance targets in our article on disk types.
Select a disk type for IaaS VMs
What disk types are available in Azure?
11/12/2019 • 13 minutes to read • Edit Online

Azure managed disks currently offers four disk types, each type is aimed towards specific customer scenarios.

Disk comparison
The following table provides a comparison of ultra disks, premium solid-state drives (SSD ), standard SSD, and
standard hard disk drives (HDD ) for managed disks to help you decide what to use.

ULTRA DISK PREMIUM SSD STANDARD SSD STANDARD HDD

Disk type SSD SSD SSD HDD

Scenario IO-intensive Production and Web servers, lightly Backup, non-critical,


workloads such as performance sensitive used enterprise infrequent access
SAP HANA, top tier workloads applications and
databases (for dev/test
example, SQL, Oracle),
and other
transaction-heavy
workloads.

Max disk size 65,536 gibibyte (GiB) 32,767 GiB 32,767 GiB 32,767 GiB

Max throughput 2,000 MiB/s 900 MiB/s 750 MiB/s 500 MiB/s

Max IOPS 160,000 20,000 6,000 2,000

Ultra disk
Azure ultra disks deliver high throughput, high IOPS, and consistent low latency disk storage for Azure IaaS VMs.
Some additional benefits of ultra disks include the ability to dynamically change the performance of the disk,
along with your workloads, without the need to restart your virtual machines (VM ). Ultra disks are suited for data-
intensive workloads such as SAP HANA, top tier databases, and transaction-heavy workloads. Ultra disks can only
be used as data disks. We recommend using premium SSDs as OS disks.
Performance
When you provision an ultra disk, you can independently configure the capacity and the performance of the disk.
Ultra disks come in several fixed sizes, ranging from 4 GiB up to 64 TiB, and feature a flexible performance
configuration model that allows you to independently configure IOPS and throughput.
Some key capabilities of ultra disks are:
Disk capacity: Ultra disks capacity ranges from 4 GiB up to 64 TiB.
Disk IOPS: Ultra disks support IOPS limits of 300 IOPS/GiB, up to a maximum of 160 K IOPS per disk. To
achieve the IOPS that you provisioned, ensure that the selected Disk IOPS are less than the VM IOPS limit.
The minimum IOPS per disk is 2 IOPS/GiB, with an overall baseline minimum of 100 IOPS. For example, if
you had a 4 GiB ultra disk, you will have a minimum of 100 IOPS, instead of eight IOPS.
Disk throughput: With ultra disks, the throughput limit of a single disk is 256 KiB/s for each provisioned IOPS,
up to a maximum of 2000 MBps per disk (where MBps = 10^6 Bytes per second). The minimum throughput
per disk is 4KiB/s for each provisioned IOPS, with an overall baseline minimum of 1 MBps.
Ultra disks support adjusting the disk performance attributes (IOPS and throughput) at runtime without
detaching the disk from the virtual machine. Once a disk performance resize operation has been issued on a
disk, it can take up to an hour for the change to actually take effect. There is a limit of four performance resize
operations during a 24 hour window. It is possible for a performance resize operation to fail due to a lack of
performance bandwidth capacity.
Disk size
DISK SIZE (GIB) IOPS CAP THROUGHPUT CAP (MBPS)

4 1,200 300

8 2,400 600

16 4,800 1,200

32 9,600 2,000

64 19,200 2,000

128 38,400 2,000

256 76,800 2,000

512 80,000 2,000

1,024-65,536 (sizes in this range 160,000 2,000


increasing in increments of 1 TiB)

GA scope and limitations


For now, ultra disks have additional limitations, they are as follows:
Are supported in the following regions, with a varying number of availability zones per region:
East US 2
East US
West US 2
SouthEast Asia
North Europe
West Europe
UK South
Can only be used with availability zones (availability sets and single VM deployments outside of zones will not
have the ability to attach an ultra disk)
Are only supported on the following VM series:
ESv3
DSv3
FSv2
M
Mv2
Not every VM size is available in every supported region with ultra disks
Are only available as data disks and only support 4k physical sector size. Due to the 4K native sector size of
Ultra Disk, there are some applications that won't be compatible with ultra disks. One example would be Oracle
Database, which requires release 12.2 or later in order to support ultra disks.
Can only be created as empty disks
Do not yet support disk snapshots, VM images, availability sets, and Azure disk encryption
Do not yet support integration with Azure Backup or Azure Site Recovery
The current maximum limit for IOPS on GA VMs is 80,000.
If you would like to participate in a limited preview of a VM that can accomplish 160,000 IOPS with ultra disks,
please email UltraDiskFeedback@microsoft .com
If you would like to start using ultra disks, see our article on the subject: Using Azure ultra disks.

Premium SSD
Azure premium SSDs deliver high-performance and low -latency disk support for virtual machines (VMs) with
input/output (IO )-intensive workloads. To take advantage of the speed and performance of premium storage disks,
you can migrate existing VM disks to Premium SSDs. Premium SSDs are suitable for mission-critical production
applications. Premium SSDs can only be used with VM series that are premium storage-compatible.
To learn more about individual VM types and sizes in Azure for Windows, including which sizes are premium
storage-compatible, see Windows VM sizes. To learn more about individual VM types and sizes in Azure for Linux,
including which sizes are premium storage-compatible, see Linux VM sizes.
Disk size
PRE
MIU
M
SSD
SIZE
S P1* P2* P3* P4 P6 P10 P15 P20 P30 P40 P50 P60 P70 P80

Disk 4 8 16 32 64 128 256 512 1,02 2,04 4,09 8,19 16,3 32,7
size 4 8 6 2 84 67
in
GiB

IOP 120 120 120 120 240 500 1,1 2,30 5,00 7,50 7,50 16,0 18,0 20,0
S 00 0 0 0 0 00 00 00
per
disk

Thr 25 25 25 25 50 100 125 150 200 250 250 500 750 900
oug MiB MiB MiB MiB MiB MiB MiB MiB MiB MiB MiB MiB MiB MiB
hpu /sec /sec /sec /sec /sec /sec /sec /sec /sec /sec /sec /sec /sec /sec
t
per
disk

Max 3,5 3,5 3,5 3,5 3,5 3,5 3,5 3,50


bur 00 00 00 00 00 00 00 0
st
IOP
S
per
disk
**
PRE
MIU
M
SSD
SIZE
S P1* P2* P3* P4 P6 P10 P15 P20 P30 P40 P50 P60 P70 P80

Max 170 170 170 170 170 170 170 170


bur MiB MiB MiB MiB MiB MiB MiB MiB
st /sec /sec /sec /sec /sec /sec /sec /sec
thro
ugh
put
per
disk
**

Max 30 30 30 30 30 30 30 30
bur min min min min min min min min
st
dur
atio
n**

Eligi No No No No No No No No Yes, Yes, Yes, Yes, Yes, Yes,


ble up up up up up up
for to to to to to to
rese one one one one one one
rvat year year year year year year
ion

*Denotes a disk size that is currently in preview, for regional availability information see New disk sizes: Managed
and unmanaged.
**Denotes a feature that is currently in preview, see Disk bursting for more information.
When you provision a premium storage disk, unlike standard storage, you are guaranteed the capacity, IOPS, and
throughput of that disk. For example, if you create a P50 disk, Azure provisions 4,095-GB storage capacity, 7,500
IOPS, and 250-MB/s throughput for that disk. Your application can use all or part of the capacity and
performance. Premium SSD disks are designed to provide low single-digit millisecond latencies and target IOPS
and throughput described in the preceding table 99.9% of the time.

Bursting (preview)
Premium SSD sizes smaller than P30 now offer disk bursting (preview ) and can burst their IOPS per disk up to
3,500 and their bandwidth up to 170 Mbps. Bursting is automated and operates based on a credit system. Credits
are automatically accumulated in a burst bucket when disk traffic is below the provisioned performance target and
credits are automatically consumed when traffic bursts beyond the target, up to the max burst limit. The max burst
limit defines the ceiling of disk IOPS & Bandwidth even if you have burst credits to consume from. Disk bursting
provides better tolerance on unpredictable changes of IO patterns. You can best leverage it for OS disk boot and
applications with spiky traffic.
Disks bursting support will be enabled on new deployments of applicable disk sizes in the preview regions by
default, with no user action required. For existing disks of the applicable sizes, you can enable bursting with either
of two the options: detach and reattach the disk or stop and restart the attached VM. All burst applicable disk sizes
will start with a full burst credit bucket when the disk is attached to a Virtual Machine that supports a max
duration at peak burst limit of 30 mins. To learn more about how bursting work on Azure Disks, see Premium SSD
bursting.
Transactions
For premium SSDs, each I/O operation less than or equal to 256 KiB of throughput is considered a single I/O
operation. I/O operations larger than 256 KiB of throughput are considered multiple I/Os of size 256 KiB.

Standard SSD
Azure standard SSDs are a cost-effective storage option optimized for workloads that need consistent
performance at lower IOPS levels. Standard SSD offers a good entry level experience for those who wish to move
to the cloud, especially if you experience issues with the variance of workloads running on your HDD solutions on
premises. Compared to standard HDDs, standard SSDs deliver better availability, consistency, reliability, and
latency. Standard SSDs are suitable for Web servers, low IOPS application servers, lightly used enterprise
applications, and Dev/Test workloads. Like standard HDDs, standard SSDs are available on all Azure VMs.
Disk size
STA
NDA
RD
SSD
SIZE
S E1* E2* E3* E4 E6 E10 E15 E20 E30 E40 E50 E60 E70 E80

Disk 4 8 16 32 64 128 256 512 1,02 2,04 4,09 8,19 16,3 32,7
size 4 8 6 2 84 67
in
GiB

IOP Up Up Up Up Up Up Up Up Up Up Up Up Up Up
S to to to to to to to to to to to to to to
per 120 120 120 120 240 500 500 500 500 500 500 2,00 4,00 6,00
disk 0 0 0

Thr Up Up Up Up Up Up Up Up Up Up Up Up Up Up
oug to to to to to to to to to to to to to to
hpu 25 25 25 25 50 60 60 60 60 60 60 400 600 750
t MiB MiB MiB MiB MiB MiB MiB MiB MiB MiB MiB MiB MiB MiB
per /sec /sec /sec /sec /sec /sec /sec /sec /sec /sec /sec /sec /sec /sec
disk

*Denotes a disk size that is currently in preview, for regional availability information see New disk sizes: Managed
and unmanaged.
Standard SSDs are designed to provide single-digit millisecond latencies and the IOPS and throughput up to the
limits described in the preceding table 99% of the time. Actual IOPS and throughput may vary sometimes
depending on the traffic patterns. Standard SSDs will provide more consistent performance than the HDD disks
with the lower latency.
Transactions
For standard SSDs, each I/O operation less than or equal to 256 KiB of throughput is considered a single I/O
operation. I/O operations larger than 256 KiB of throughput are considered multiple I/Os of size 256 KiB. These
transactions have a billing impact.

Standard HDD
Azure standard HDDs deliver reliable, low -cost disk support for VMs running latency-insensitive workloads. With
standard storage, the data is stored on hard disk drives (HDDs). Latency, IOPS, and Throughput of Standard HDD
disks may vary more widely as compared to SSD -based disks. Standard HDD Disks are designed to deliver write
latencies under 10ms and read latencies under 20ms for most IO operations, however the actual performance
may vary depending on the IO size and workload pattern. When working with VMs, you can use standard HDD
disks for dev/test scenarios and less critical workloads. Standard HDDs are available in all Azure regions and can
be used with all Azure VMs.
Disk size
STAND
ARD
DISK
TYPE S4 S6 S10 S15 S20 S30 S40 S50 S60 S70 S80

Disk 32 64 128 256 512 1,024 2,048 4,096 8,192 16,38 32,76
size in 4 7
GiB

IOPS Up to Up to Up to Up to Up to Up to Up to Up to Up to Up to Up to
per 500 500 500 500 500 500 500 500 1,300 2,000 2,000
disk

Throu Up to Up to Up to Up to Up to Up to Up to Up to Up to Up to Up to
ghput 60 60 60 60 60 60 60 60 300 500 500
per MiB/s MiB/s MiB/s MiB/s MiB/s MiB/s MiB/s MiB/s MiB/s MiB/s MiB/s
disk ec ec ec ec ec ec ec ec ec ec ec

Transactions
For Standard HDDs, each IO operation is considered as a single transaction, regardless of the I/O size. These
transactions have a billing impact.

Billing
When using managed disks, the following billing considerations apply:
Disk type
managed disk Size
Snapshots
Outbound data transfers
Number of transactions
Managed disk size: managed disks are billed on the provisioned size. Azure maps the provisioned size (rounded
up) to the nearest offered disk size. For details of the disk sizes offered, see the previous tables. Each disk maps to
a supported provisioned disk size offering and is billed accordingly. For example, if you provisioned a 200 GiB
Standard SSD, it maps to the disk size offer of E15 (256 GiB ). Billing for any provisioned disk is prorated hourly by
using the monthly price for the Premium Storage offer. For example, if you provisioned an E10 disk and deleted it
after 20 hours, you're billed for the E10 offering prorated to 20 hours. This is regardless of the amount of actual
data written to the disk.
Snapshots: Snapshots are billed based on the size used. For example, if you create a snapshot of a managed disk
with provisioned capacity of 64 GiB and actual used data size of 10 GiB, the snapshot is billed only for the used
data size of 10 GiB.
For more information on snapshots, see the section on snapshots in the managed disk overview.
Outbound data transfers: Outbound data transfers (data going out of Azure data centers) incur billing for
bandwidth usage.
Transactions: You're billed for the number of transactions that you perform on a standard managed disk. For
standard SSDs, each I/O operation less than or equal to 256 KiB of throughput is considered a single I/O
operation. I/O operations larger than 256 KiB of throughput are considered multiple I/Os of size 256 KiB. For
Standard HDDs, each IO operation is considered as a single transaction, regardless of the I/O size.
For detailed information on pricing for Managed Disks, including transaction costs, see Managed Disks Pricing.
Ultra disk VM reservation fee
Azure VMs have the capability to indicate if they are compatible with ultra disks. An ultra disk compatible VM
allocates dedicated bandwidth capacity between the compute VM instance and the block storage scale unit to
optimize the performance and reduce latency. Adding this capability on the VM results in a reservation charge that
is only imposed if you enabled ultra disk capability on the VM without attaching an ultra disk to it. When an ultra
disk is attached to the ultra disk compatible VM, this charge would not be applied. This charge is per vCPU
provisioned on the VM.

NOTE
For constrained core VM sizes, the reservation fee is based on the actual number of vCPUs and not the constrained cores.
For Standard_E32-8s_v3, the reservation fee will be based on 32 cores.

Refer to the Azure Disks pricing page for ultra disk pricing details.
Azure disk reservation
Disk reservation is the option to purchase one year of disk storage in advance at a discount, reducing your total
cost. When purchasing a disk reservation, you select a specific Disk SKU in a target region, for example, 10 P30
(1TiB ) premium SSDs in East US 2 region for a one year term. The reservation experience is similar to reserved
virtual machine (VM ) instances. You can bundle VM and Disk reservations to maximize your savings. For now,
Azure Disks Reservation offers one year commitment plan for premium SSD SKUs from P30 (1TiB ) to P80 (32
TiB ) in all production regions. For more details on the Reserved Disks pricing, see Azure Disks pricing page.
Server side encryption of Azure managed disks
2/18/2020 • 12 minutes to read • Edit Online

Azure managed disks automatically encrypt your data by default when persisting it to the cloud. Server-side
encryption protects your data and helps you meet your organizational security and compliance commitments. Data
in Azure managed disks is encrypted transparently using 256-bit AES encryption, one of the strongest block
ciphers available, and is FIPS 140-2 compliant.
Encryption does not impact the performance of managed disks. There is no additional cost for the encryption.
For more information about the cryptographic modules underlying Azure managed disks, see Cryptography API:
Next Generation

About encryption key management


You can rely on platform-managed keys for the encryption of your managed disk, or you can manage encryption
using your own keys. If you choose to manage encryption with your own keys, you can specify a customer-
managed key to use for encrypting and decrypting all data in managed disks.
The following sections describe each of the options for key management in greater detail.

Platform-managed keys
By default, managed disks use platform-managed encryption keys. As of June 10, 2017, all new managed disks,
snapshots, images, and new data written to existing managed disks are automatically encrypted-at-rest with
platform-managed keys.

Customer-managed keys
You can choose to manage encryption at the level of each managed disk, with your own keys. Server-side
encryption for managed disks with customer-managed keys offers an integrated experience with Azure Key Vault.
You can either import your RSA keys to your Key Vault or generate new RSA keys in Azure Key Vault. Azure
managed disks handles the encryption and decryption in a fully transparent fashion using envelope encryption. It
encrypts data using an AES 256 based data encryption key (DEK), which is, in turn, protected using your keys. You
have to grant access to managed disks in your Key Vault to use your keys for encrypting and decrypting the DEK.
This allows you full control of your data and keys. You can disable your keys or revoke access to managed disks at
any time. You can also audit the encryption key usage with Azure Key Vault monitoring to ensure that only
managed disks or other trusted Azure services are accessing your keys.
The following diagram shows how managed disks use Azure Active Directory and Azure Key Vault to make
requests using the customer-managed key:
The following list explains the diagram in even more detail:
1. An Azure Key Vault administrator creates key vault resources.
2. The key vault admin either imports their RSA keys to Key Vault or generate new RSA keys in Key Vault.
3. That administrator creates an instance of Disk Encryption Set resource, specifying an Azure Key Vault ID and a
key URL. Disk Encryption Set is a new resource introduced for simplifying the key management for managed
disks.
4. When a disk encryption set is created, a system-assigned managed identity is created in Azure Active Directory
(AD ) and associated with the disk encryption set.
5. The Azure key vault administrator then grants the managed identity permission to perform operations in the
key vault.
6. A VM user creates disks by associating them with the disk encryption set. The VM user can also enable server-
side encryption with customer-managed keys for existing resources by associating them with the disk
encryption set.
7. Managed disks use the managed identity to send requests to the Azure Key Vault.
8. For reading or writing data, managed disks sends requests to Azure Key Vault to encrypt (wrap) and decrypt
(unwrap) the data encryption key in order to perform encryption and decryption of the data.

To revoke access to customer-managed keys, see Azure Key Vault PowerShell and Azure Key Vault CLI. Revoking
access effectively blocks access to all data in the storage account, as the encryption key is inaccessible by Azure
Storage.
Supported regions
Only the following regions are currently supported:
Available as a GA offering in the East US, West US 2, South Central US, UK South regions.
Available as a public preview in the West Central US, East US 2, Canada Central, and North Europe regions.
Restrictions
For now, customer-managed keys have the following restrictions:
Only "soft" and "hard" RSA keys of size 2080 are supported, no other keys or sizes.
Disks created from custom images that are encrypted using server-side encryption and customer-managed
keys must be encrypted using the same customer-managed keys and must be in the same subscription.
Snapshots created from disks that are encrypted with server-side encryption and customer-managed keys must
be encrypted with the same customer-managed keys.
Custom images encrypted using server-side encryption and customer-managed keys cannot be used in the
shared image gallery.
All resources related to your customer-managed keys (Azure Key Vaults, disk encryption sets, VMs, disks, and
snapshots) must be in the same subscription and region.
Disks, snapshots, and images encrypted with customer-managed keys cannot move to another subscription.
If you use the Azure portal to create your disk encryption set, you cannot use snapshots for now.
PowerShell
Setting up your Azure Key Vault and DiskEncryptionSet
1. Make sure that you have installed latest Azure PowerShell version, and you are signed in to an Azure
account in with Connect-AzAccount
2. Create an instance of Azure Key Vault and encryption key.
When creating the Key Vault instance, you must enable soft delete and purge protection. Soft delete ensures
that the Key Vault holds a deleted key for a given retention period (90 day default). Purge protection ensures
that a deleted key cannot be permanently deleted until the retention period lapses. These settings protect
you from losing data due to accidental deletion. These settings are mandatory when using a Key Vault for
encrypting managed disks.

$ResourceGroupName="yourResourceGroupName"
$LocationName="westcentralus"
$keyVaultName="yourKeyVaultName"
$keyName="yourKeyName"
$keyDestination="Software"
$diskEncryptionSetName="yourDiskEncryptionSetName"

$keyVault = New-AzKeyVault -Name $keyVaultName -ResourceGroupName $ResourceGroupName -Location


$LocationName -EnableSoftDelete -EnablePurgeProtection

$key = Add-AzKeyVaultKey -VaultName $keyVaultName -Name $keyName -Destination $keyDestination

3. Create an instance of a DiskEncryptionSet.

$desConfig=New-AzDiskEncryptionSetConfig -Location $LocationName -SourceVaultId $keyVault.ResourceId -


KeyUrl $key.Key.Kid -IdentityType SystemAssigned

$des=New-AzDiskEncryptionSet -Name $diskEncryptionSetName -ResourceGroupName $ResourceGroupName -


InputObject $desConfig

4. Grant the DiskEncryptionSet resource access to the key vault.

NOTE
It may take few minutes for Azure to create the identity of your DiskEncryptionSet in your Azure Active Directory. If
you get an error like "Cannot find the Active Directory object" when running the following command, wait a few
minutes and try again.
$identity = Get-AzADServicePrincipal -DisplayName myDiskEncryptionSet1

Set-AzKeyVaultAccessPolicy -VaultName $keyVaultName -ObjectId $des.Identity.PrincipalId -


PermissionsToKeys wrapkey,unwrapkey,get

New-AzRoleAssignment -ResourceName $keyVaultName -ResourceGroupName $ResourceGroupName -ResourceType


"Microsoft.KeyVault/vaults" -ObjectId $des.Identity.PrincipalId -RoleDefinitionName "Reader"

Create a VM using a Marketplace image, encrypting the OS and data disks with customer-managed keys

$VMLocalAdminUser = "yourVMLocalAdminUserName"
$VMLocalAdminSecurePassword = ConvertTo-SecureString <password> -AsPlainText -Force
$LocationName = "westcentralus"
$ResourceGroupName = "yourResourceGroupName"
$ComputerName = "yourComputerName"
$VMName = "yourVMName"
$VMSize = "Standard_DS3_v2"
$diskEncryptionSetName="yourdiskEncryptionSetName"

$NetworkName = "yourNetworkName"
$NICName = "yourNICName"
$SubnetName = "yourSubnetName"
$SubnetAddressPrefix = "10.0.0.0/24"
$VnetAddressPrefix = "10.0.0.0/16"

$SingleSubnet = New-AzVirtualNetworkSubnetConfig -Name $SubnetName -AddressPrefix $SubnetAddressPrefix


$Vnet = New-AzVirtualNetwork -Name $NetworkName -ResourceGroupName $ResourceGroupName -Location $LocationName -
AddressPrefix $VnetAddressPrefix -Subnet $SingleSubnet
$NIC = New-AzNetworkInterface -Name $NICName -ResourceGroupName $ResourceGroupName -Location $LocationName -
SubnetId $Vnet.Subnets[0].Id

$Credential = New-Object System.Management.Automation.PSCredential ($VMLocalAdminUser,


$VMLocalAdminSecurePassword);

$VirtualMachine = New-AzVMConfig -VMName $VMName -VMSize $VMSize


$VirtualMachine = Set-AzVMOperatingSystem -VM $VirtualMachine -Windows -ComputerName $ComputerName -Credential
$Credential -ProvisionVMAgent -EnableAutoUpdate
$VirtualMachine = Add-AzVMNetworkInterface -VM $VirtualMachine -Id $NIC.Id
$VirtualMachine = Set-AzVMSourceImage -VM $VirtualMachine -PublisherName 'MicrosoftWindowsServer' -Offer
'WindowsServer' -Skus '2012-R2-Datacenter' -Version latest

$diskEncryptionSet=Get-AzDiskEncryptionSet -ResourceGroupName $ResourceGroupName -Name $diskEncryptionSetName

$VirtualMachine = Set-AzVMOSDisk -VM $VirtualMachine -Name $($VMName +"_OSDisk") -DiskEncryptionSetId


$diskEncryptionSet.Id -CreateOption FromImage

$VirtualMachine = Add-AzVMDataDisk -VM $VirtualMachine -Name $($VMName +"DataDisk1") -DiskSizeInGB 128 -


StorageAccountType Premium_LRS -CreateOption Empty -Lun 0 -DiskEncryptionSetId $diskEncryptionSet.Id

New-AzVM -ResourceGroupName $ResourceGroupName -Location $LocationName -VM $VirtualMachine -Verbose

Create an empty disk encrypted using server-side encryption with customer-managed keys and attach it to a VM
$vmName = "yourVMName"
$LocationName = "westcentralus"
$ResourceGroupName = "yourResourceGroupName"
$diskName = "yourDiskName"
$diskSKU = "Premium_LRS"
$diskSizeinGiB = 30
$diskLUN = 1
$diskEncryptionSetName="yourDiskEncryptionSetName"

$vm = Get-AzVM -Name $vmName -ResourceGroupName $ResourceGroupName

$diskEncryptionSet=Get-AzDiskEncryptionSet -ResourceGroupName $ResourceGroupName -Name $diskEncryptionSetName

$vm = Add-AzVMDataDisk -VM $vm -Name $diskName -CreateOption Empty -DiskSizeInGB $diskSizeinGiB -
StorageAccountType $diskSKU -Lun $diskLUN -DiskEncryptionSetId $diskEncryptionSet.Id

Update-AzVM -ResourceGroupName $ResourceGroupName -VM $vm

Encrypt existing unattached managed disks


Your existing disks must not be attached to a running VM in order for you to encrypt them using the following
script:

$rgName = "yourResourceGroupName"
$diskName = "yourDiskName"
$diskEncryptionSetName = "yourDiskEncryptionSetName"

$diskEncryptionSet = Get-AzDiskEncryptionSet -ResourceGroupName $rgName -Name $diskEncryptionSetName

New-AzDiskUpdateConfig -EncryptionType "EncryptionAtRestWithCustomerKey" -DiskEncryptionSetId


$diskEncryptionSet.Id | Update-AzDisk -ResourceGroupName $rgName -DiskName $diskName

Create a virtual machine scale set using a Marketplace image, encrypting the OS and data disks with customer-managed keys
$VMLocalAdminUser = "yourLocalAdminUser"
$VMLocalAdminSecurePassword = ConvertTo-SecureString Password@123 -AsPlainText -Force
$LocationName = "westcentralus"
$ResourceGroupName = "yourResourceGroupName"
$ComputerNamePrefix = "yourComputerNamePrefix"
$VMScaleSetName = "yourVMSSName"
$VMSize = "Standard_DS3_v2"
$diskEncryptionSetName="yourDiskEncryptionSetName"

$NetworkName = "yourVNETName"
$SubnetName = "yourSubnetName"
$SubnetAddressPrefix = "10.0.0.0/24"
$VnetAddressPrefix = "10.0.0.0/16"

$SingleSubnet = New-AzVirtualNetworkSubnetConfig -Name $SubnetName -AddressPrefix $SubnetAddressPrefix

$Vnet = New-AzVirtualNetwork -Name $NetworkName -ResourceGroupName $ResourceGroupName -Location $LocationName -


AddressPrefix $VnetAddressPrefix -Subnet $SingleSubnet

$ipConfig = New-AzVmssIpConfig -Name "myIPConfig" -SubnetId $Vnet.Subnets[0].Id

$VMSS = New-AzVmssConfig -Location $LocationName -SkuCapacity 2 -SkuName $VMSize -UpgradePolicyMode 'Automatic'

$VMSS = Add-AzVmssNetworkInterfaceConfiguration -Name "myVMSSNetworkConfig" -VirtualMachineScaleSet $VMSS -


Primary $true -IpConfiguration $ipConfig

$diskEncryptionSet=Get-AzDiskEncryptionSet -ResourceGroupName $ResourceGroupName -Name $diskEncryptionSetName

# Enable encryption at rest with customer managed keys for OS disk by setting DiskEncryptionSetId property

$VMSS = Set-AzVmssStorageProfile $VMSS -OsDiskCreateOption "FromImage" -DiskEncryptionSetId


$diskEncryptionSet.Id -ImageReferenceOffer 'WindowsServer' -ImageReferenceSku '2012-R2-Datacenter' -
ImageReferenceVersion latest -ImageReferencePublisher 'MicrosoftWindowsServer'

$VMSS = Set-AzVmssOsProfile $VMSS -ComputerNamePrefix $ComputerNamePrefix -AdminUsername $VMLocalAdminUser -


AdminPassword $VMLocalAdminSecurePassword

# Add a data disk encrypted at rest with customer managed keys by setting DiskEncryptionSetId property

$VMSS = Add-AzVmssDataDisk -VirtualMachineScaleSet $VMSS -CreateOption Empty -Lun 1 -DiskSizeGB 128 -


StorageAccountType Premium_LRS -DiskEncryptionSetId $diskEncryptionSet.Id

$Credential = New-Object System.Management.Automation.PSCredential ($VMLocalAdminUser,


$VMLocalAdminSecurePassword);

New-AzVmss -VirtualMachineScaleSet $VMSS -ResourceGroupName $ResourceGroupName -VMScaleSetName $VMScaleSetName

IMPORTANT
Customer-managed keys rely on managed identities for Azure resources, a feature of Azure Active Directory (Azure AD).
When you configure customer-managed keys, a managed identity is automatically assigned to your resources under the
covers. If you subsequently move the subscription, resource group, or managed disk from one Azure AD directory to another,
the managed identity associated with managed disks is not transferred to the new tenant, so customer-managed keys may
no longer work. For more information, see Transferring a subscription between Azure AD directories.

Portal
Setting up customer-managed keys for your disks will require you to create resources in a particular order, if you're
doing it for the first time. First, you will need to create and set up an Azure Key Vault.
Setting up your Azure Key Vault
1. Sign into the Azure portal and search for Key Vault
2. Search for and select Key Vaults.

IMPORTANT
Your Azure key vault, disk encryption set, VM, disks, and snapshots must all be in the same region and subscription
for deployment to succeed.

3. Select +Add to create a new Key Vault.


4. Create a new resource group
5. Enter a key vault name, select a region, and select a pricing tier.
6. Select Review + Create, verify your choices, then select Create.
7. Once your key vault finishes deploying, select it.
8. Select Keys under Settings.
9. Select Generate/Import
10. Leave both Key Type set to RSA and RSA Key Size set to 2080.
11. Fill in the remaining selections as you like and then select Create.

Setting up your disk encryption set


To create and configure disk encryption sets, you must use the following link: https://aka.ms/diskencryptionsets.
Disk encryption set creation is not yet available in the global Azure portal.
1. Open the disk encryption sets link.
2. Select +Add.

3. Select your resource group, name your encryption set, and select the same region as your key vault.
4. Select Key vault and key.
5. Select the key vault and key you created previously, as well as the version.
6. Press Select.
7. Select Review + Create and then Create.
8. Open the disk encryption set once it finishes creating and select the alert that pops up.

Two notifications should pop up and succeed. Doing this will allow you to use the disk encryption set with your key
vault.

Deploy a VM
Now that you've created and set up your key vault and the disk encryption set, you can deploy a VM using the
encryption. The VM deployment process is similar to the standard deployment process, the only differences are
that you need to deploy the VM in the same region as your other resources and you opt to use a customer
managed key.
1. Open the disk encryption sets link.
2. Search for Virtual Machines and select + Add to create a VM.
3. On the Basic tab, select the same region as your disk encryption set and Azure Key Vault.
4. Fill in the other values on the Basic tab as you like.
5. On the Disks tab, select Encryption at rest with a customer-managed key.
6. Select your disk encryption set in the Disk encryption set drop-down.
7. Make the remaining selections as you like.
Enable on an existing disk
To manage and configure disk encryption on your existing disks, you must use the following link:
https://aka.ms/diskencryptionsets. Enabling customer-managed keys on existing disks is not yet available in the
global Azure portal.
Cau t i on

Enabling disk encryption on any disks attached to a VM will require that you stop the VM.
1. Open the disk encryption sets link.
2. Navigate to a VM which is in the same region as one of your disk encryption sets.
3. Open the VM and select Stop.
4. After the VM has finished stopping, select Disks and then select the disk you want to encrypt.

5. Select Encryption and select Encryption at rest with a customer-managed key and then select your
disk encryption set in the drop-down list.
6. Select Save.

7. Repeat this process for any other disks attached to the VM you'd like to encrypt.
8. When your disks finish switching over to customer-managed keys, if there are no there no other attached
disks you'd like to encrypt, you may start your VM.
IMPORTANT
Customer-managed keys rely on managed identities for Azure resources, a feature of Azure Active Directory (Azure AD).
When you configure customer-managed keys, a managed identity is automatically assigned to your resources under the
covers. If you subsequently move the subscription, resource group, or managed disk from one Azure AD directory to another,
the managed identity associated with managed disks is not transferred to the new tenant, so customer-managed keys may
no longer work. For more information, see Transferring a subscription between Azure AD directories.

Server-side encryption versus Azure disk encryption


Azure Disk Encryption leverages the BitLocker feature of Windows and the DM -Crypt feature of Linux to encrypt
managed disks with customer-managed keys within the guest VM. Server-side encryption with customer-
managed keys improves on ADE by enabling you to use any OS types and images for your VMs by encrypting
data in the Storage service.

Next steps
Explore the Azure Resource Manager templates for creating encrypted disks with customer-managed keys
What is Azure Key Vault?
Replicate machines with customer-managed keys enabled disks
Set up disaster recovery of VMware VMs to Azure with PowerShell
Set up disaster recovery to Azure for Hyper-V VMs using PowerShell and Azure Resource Manager
Understand how your reservation discount is applied
to Azure disk storage
2/24/2020 • 2 minutes to read • Edit Online

After you purchase Azure disk reserved capacity, a reservation discount is automatically applied to disk resources
that match the terms of your reservation. The reservation discount applies to disk SKUs only. Disk snapshots are
charged at pay-as-you-go rates.
For more information about Azure disk reservation, see Save costs with Azure disk reservation. For information
about pricing for Azure disk reservation, see Azure Managed Disks pricing.

How the reservation discount is applied


The Azure disk reservation discount is a use-it-or-lose-it discount. It's applied to managed disk resources hourly.
For a given hour, if you have no managed disk resources that meet the reservation terms, you lose a reservation
quantity for that hour. Unused hours don't carry forward.
When you delete a resource, the reservation discount automatically applies to another matching resource in the
specified scope. If no matching resource is found, the reserved hours are lost.

Discount examples
The following examples show how the Azure disk reservation discount applies depending on your deployment.
Suppose you purchase and reserve 100 P30 disks in the US West 2 region for a one-year term. Each disk has
approximately 1 TiB of storage. Assume the cost of this sample reservation is $140,100. You can choose to pay
either the full amount up front or fixed monthly installments of $11,675 for the next 12 months.
The following scenarios describe what happens if you underuse, overuse, or tier your reserved capacity. For these
examples, assume you've signed up for a monthly reservation-payment plan.
Underusing your capacity
Suppose you deploy only 99 of your 100 reserved Azure premium solid-state drive (SSD ) P30 disks for an hour
within the reservation period. The remaining P30 disk isn't applied during that hour. It also doesn't carry over.
Overusing your capacity
Suppose that for an hour within the reservation period, you use 101 premium SSD P30 disks. The reservation
discount applies only to 100 P30 disks. The remaining P30 disk is charged at pay-as-you-go rates for that hour. For
the next hour, if your usage goes down to 100 P30 disks, all usage is covered by the reservation.
Tiering your capacity
Suppose that in a given hour within your reservation period, you want to use a total of 200 P30 premium SSDs.
Also suppose you use only 100 for the first 30 minutes. During this period, your use is fully covered because you
made a reservation for 100 P30 disks. If you then discontinue the use of the first 100 (so that you're using zero)
and then begin to use the other 100 for the remaining 30 minutes, that usage is also covered under your
reservation.
Need help? Contact us
If you have questions or need help, create a support request.

Next steps
Reduce costs with Azure Disks Reservation (Linux)
Reduce costs with Azure Disks Reservation (Windows)
What are Azure Reservations?
Azure premium storage: design for high performance
12/23/2019 • 37 minutes to read • Edit Online

This article provides guidelines for building high performance applications using Azure Premium Storage. You can
use the instructions provided in this document combined with performance best practices applicable to
technologies used by your application. To illustrate the guidelines, we have used SQL Server running on Premium
Storage as an example throughout this document.
While we address performance scenarios for the Storage layer in this article, you will need to optimize the
application layer. For example, if you are hosting a SharePoint Farm on Azure Premium Storage, you can use the
SQL Server examples from this article to optimize the database server. Additionally, optimize the SharePoint
Farm's Web server and Application server to get the most performance.
This article will help answer following common questions about optimizing application performance on Azure
Premium Storage,
How to measure your application performance?
Why are you not seeing expected high performance?
Which factors influence your application performance on Premium Storage?
How do these factors influence performance of your application on Premium Storage?
How can you optimize for IOPS, Bandwidth and Latency?
We have provided these guidelines specifically for Premium Storage because workloads running on Premium
Storage are highly performance sensitive. We have provided examples where appropriate. You can also apply
some of these guidelines to applications running on IaaS VMs with Standard Storage disks.

NOTE
Sometimes, what appears to be a disk performance issue is actually a network bottleneck. In these situations, you should
optimize your network performance.
If you are looking to benchmark your disk, see our article on Benchmarking a disk.
If your VM supports accelerated networking, you should make sure it is enabled. If it is not enabled, you can enable it on
already deployed VMs on both Windows and Linux.

Before you begin, if you are new to Premium Storage, first read the Select an Azure disk type for IaaS VMs and
Scalability targets for premium page blob storage accounts.

Application performance indicators


We assess whether an application is performing well or not using performance indicators like, how fast an
application is processing a user request, how much data an application is processing per request, how many
requests is an application processing in a specific period of time, how long a user has to wait to get a response
after submitting their request. The technical terms for these performance indicators are, IOPS, Throughput or
Bandwidth, and Latency.
In this section, we will discuss the common performance indicators in the context of Premium Storage. In the
following section, Gathering Application Requirements, you will learn how to measure these performance
indicators for your application. Later in Optimizing Application Performance, you will learn about the factors
affecting these performance indicators and recommendations to optimize them.
IOPS
IOPS, or Input/output Operations Per Second, is the number of requests that your application is sending to the
storage disks in one second. An input/output operation could be read or write, sequential, or random. Online
Transaction Processing (OLTP ) applications like an online retail website need to process many concurrent user
requests immediately. The user requests are insert and update intensive database transactions, which the
application must process quickly. Therefore, OLTP applications require very high IOPS. Such applications handle
millions of small and random IO requests. If you have such an application, you must design the application
infrastructure to optimize for IOPS. In the later section, Optimizing Application Performance, we discuss in detail
all the factors that you must consider to get high IOPS.
When you attach a premium storage disk to your high scale VM, Azure provisions for you a guaranteed number of
IOPS as per the disk specification. For example, a P50 disk provisions 7500 IOPS. Each high scale VM size also
has a specific IOPS limit that it can sustain. For example, a Standard GS5 VM has 80,000 IOPS limit.

Throughput
Throughput, or bandwidth is the amount of data that your application is sending to the storage disks in a specified
interval. If your application is performing input/output operations with large IO unit sizes, it requires high
throughput. Data warehouse applications tend to issue scan intensive operations that access large portions of data
at a time and commonly perform bulk operations. In other words, such applications require higher throughput. If
you have such an application, you must design its infrastructure to optimize for throughput. In the next section, we
discuss in detail the factors you must tune to achieve this.
When you attach a premium storage disk to a high scale VM, Azure provisions throughput as per that disk
specification. For example, a P50 disk provisions 250 MB per second disk throughput. Each high scale VM size also
has as specific throughput limit that it can sustain. For example, Standard GS5 VM has a maximum throughput of
2,000 MB per second.
There is a relation between throughput and IOPS as shown in the formula below.

Therefore, it is important to determine the optimal throughput and IOPS values that your application requires. As
you try to optimize one, the other also gets affected. In a later section, Optimizing Application Performance, we
will discuss in more details about optimizing IOPS and Throughput.

Latency
Latency is the time it takes an application to receive a single request, send it to the storage disks and send the
response to the client. This is a critical measure of an application's performance in addition to IOPS and
Throughput. The Latency of a premium storage disk is the time it takes to retrieve the information for a request
and communicate it back to your application. Premium Storage provides consistent low latencies. Premium Disks
are designed to provide single-digit millisecond latencies for most IO operations. If you enable ReadOnly host
caching on premium storage disks, you can get much lower read latency. We will discuss Disk Caching in more
detail in later section on Optimizing Application Performance.
When you are optimizing your application to get higher IOPS and Throughput, it will affect the latency of your
application. After tuning the application performance, always evaluate the latency of the application to avoid
unexpected high latency behavior.
The following control plane operations on Managed Disks may involve movement of the Disk from one Storage
location to another. This is orchestrated via background copy of data that can take several hours to complete,
typically less than 24 hours depending on the amount of data in the disks. During that time your application can
experience higher than usual read latency as some reads can get redirected to the original location and can take
longer to complete. There is no impact on write latency during this period.
Update the storage type.
Detach and attach a disk from one VM to another.
Create a managed disk from a VHD.
Create a managed disk from a snapshot.
Convert unmanaged disks to managed disks.

Performance Application Checklist for disks


The first step in designing high-performance applications running on Azure Premium Storage is understanding
the performance requirements of your application. After you have gathered performance requirements, you can
optimize your application to achieve the most optimal performance.
In the previous section, we explained the common performance indicators, IOPS, Throughput, and Latency. You
must identify which of these performance indicators are critical to your application to deliver the desired user
experience. For example, high IOPS matters most to OLTP applications processing millions of transactions in a
second. Whereas, high Throughput is critical for Data Warehouse applications processing large amounts of data in
a second. Extremely low Latency is crucial for real-time applications like live video streaming websites.
Next, measure the maximum performance requirements of your application throughout its lifetime. Use the
sample checklist below as a start. Record the maximum performance requirements during normal, peak, and off-
hours workload periods. By identifying requirements for all workloads levels, you will be able to determine the
overall performance requirement of your application. For example, the normal workload of an e-commerce
website will be the transactions it serves during most days in a year. The peak workload of the website will be the
transactions it serves during holiday season or special sale events. The peak workload is typically experienced for a
limited period, but can require your application to scale two or more times its normal operation. Find out the 50
percentile, 90 percentile, and 99 percentile requirements. This helps filter out any outliers in the performance
requirements and you can focus your efforts on optimizing for the right values.

Application performance requirements checklist


PERFORMANCE
REQUIREMENTS 50 PERCENTILE 90 PERCENTILE 99 PERCENTILE

Max. Transactions per


second

% Read operations

% Write operations

% Random operations

% Sequential operations

IO request size

Average Throughput

Max. Throughput
PERFORMANCE
REQUIREMENTS 50 PERCENTILE 90 PERCENTILE 99 PERCENTILE

Min. Latency

Average Latency

Max. CPU

Average CPU

Max. Memory

Average Memory

Queue Depth

NOTE
You should consider scaling these numbers based on expected future growth of your application. It is a good idea to plan for
growth ahead of time, because it could be harder to change the infrastructure for improving performance later.

If you have an existing application and want to move to Premium Storage, first build the checklist above for the
existing application. Then, build a prototype of your application on Premium Storage and design the application
based on guidelines described in Optimizing Application Performance in a later section of this document. The next
article describes the tools you can use to gather the performance measurements.
Counters to measure application performance requirements
The best way to measure performance requirements of your application, is to use performance-monitoring tools
provided by the operating system of the server. You can use PerfMon for Windows and iostat for Linux. These
tools capture counters corresponding to each measure explained in the above section. You must capture the values
of these counters when your application is running its normal, peak, and off-hours workloads.
The PerfMon counters are available for processor, memory and, each logical disk and physical disk of your server.
When you use premium storage disks with a VM, the physical disk counters are for each premium storage disk,
and logical disk counters are for each volume created on the premium storage disks. You must capture the values
for the disks that host your application workload. If there is a one to one mapping between logical and physical
disks, you can refer to physical disk counters; otherwise refer to the logical disk counters. On Linux, the iostat
command generates a CPU and disk utilization report. The disk utilization report provides statistics per physical
device or partition. If you have a database server with its data and logs on separate disks, collect this data for both
disks. Below table describes counters for disks, processors, and memory:

COUNTER DESCRIPTION PERFMON IOSTAT

IOPS or Transactions per Number of I/O requests Disk Reads/sec tps


second issued to the storage disk Disk Writes/sec r/s
per second. w/s

Disk Reads and Writes % of Reads and Write % Disk Read Time r/s
operations performed on the % Disk Write Time w/s
disk.
COUNTER DESCRIPTION PERFMON IOSTAT

Throughput Amount of data read from Disk Read Bytes/sec kB_read/s


or written to the disk per Disk Write Bytes/sec kB_wrtn/s
second.

Latency Total time to complete a disk Average Disk sec/Read await


IO request. Average disk sec/Write svctm

IO size The size of I/O requests Average Disk Bytes/Read avgrq-sz


issues to the storage disks. Average Disk Bytes/Write

Queue Depth Number of outstanding I/O Current Disk Queue Length avgqu-sz
requests waiting to be read
from or written to the
storage disk.

Max. Memory Amount of memory required % Committed Bytes in Use Use vmstat
to run application smoothly

Max. CPU Amount CPU required to % Processor time %util


run application smoothly

Learn more about iostat and PerfMon.

Optimize application performance


The main factors that influence performance of an application running on Premium Storage are Nature of IO
requests, VM size, Disk size, Number of disks, disk caching, multithreading, and queue depth. You can control
some of these factors with knobs provided by the system. Most applications may not give you an option to alter
the IO size and Queue Depth directly. For example, if you are using SQL Server, you cannot choose the IO size and
queue depth. SQL Server chooses the optimal IO size and queue depth values to get the most performance. It is
important to understand the effects of both types of factors on your application performance, so that you can
provision appropriate resources to meet performance needs.
Throughout this section, refer to the application requirements checklist that you created, to identify how much you
need to optimize your application performance. Based on that, you will be able to determine which factors from
this section you will need to tune. To witness the effects of each factor on your application performance, run
benchmarking tools on your application setup. Refer to the Benchmarking article, linked at the end, for steps to run
common benchmarking tools on Windows and Linux VMs.
Optimize IOPS, throughput, and latency at a glance
The table below summarizes performance factors and the steps necessary to optimize IOPS, throughput, and
latency. The sections following this summary will describe each factor is much more depth.
For more information on VM sizes and on the IOPS, throughput, and latency available for each type of VM, see
Linux VM sizes or Windows VM sizes.

IOPS THROUGHPUT LATENCY

Example Scenario Enterprise OLTP application Enterprise Data warehousing Near real-time applications
requiring very high application processing large requiring instant responses
transactions per second rate. amounts of data. to user requests, like online
gaming.
IOPS THROUGHPUT LATENCY

Performance factors

IO size Smaller IO size yields higher Larger IO size to yields


IOPS. higher Throughput.

VM size Use a VM size that offers Use a VM size with Use a VM size that offers
IOPS greater than your throughput limit greater scale limits greater than your
application requirement. than your application application requirement.
requirement.

Disk size Use a disk size that offers Use a disk size with Use a disk size that offers
IOPS greater than your Throughput limit greater scale limits greater than your
application requirement. than your application application requirement.
requirement.

VM and Disk Scale Limits IOPS limit of the VM size Throughput limit of the VM Scale limits of the VM size
chosen should be greater size chosen should be chosen must be greater than
than total IOPS driven by greater than total total scale limits of attached
storage disks attached to it. Throughput driven by premium storage disks.
premium storage disks
attached to it.

Disk Caching Enable ReadOnly Cache on Enable ReadOnly Cache on


premium storage disks with premium storage disks with
Read heavy operations to Ready heavy operations to
get higher Read IOPS. get very low Read latencies.

Disk Striping Use multiple disks and stripe


them together to get a
combined higher IOPS and
Throughput limit. The
combined limit per VM
should be higher than the
combined limits of attached
premium disks.

Stripe Size Smaller stripe size for Larger stripe size for
random small IO pattern sequential large IO pattern
seen in OLTP applications. seen in Data Warehouse
For example, use stripe size applications. For example,
of 64 KB for SQL Server use 256 KB stripe size for
OLTP application. SQL Server Data warehouse
application.

Multithreading Use multithreading to push


higher number of requests
to Premium Storage that will
lead to higher IOPS and
Throughput. For example, on
SQL Server set a high
MAXDOP value to allocate
more CPUs to SQL Server.

Queue Depth Larger Queue Depth yields Larger Queue Depth yields Smaller Queue Depth yields
higher IOPS. higher Throughput. lower latencies.
Nature of IO requests
An IO request is a unit of input/output operation that your application will be performing. Identifying the nature of
IO requests, random or sequential, read or write, small or large, will help you determine the performance
requirements of your application. It is important to understand the nature of IO requests, to make the right
decisions when designing your application infrastructure. IOs must be distributed evenly to achieve the best
performance possible.
IO size is one of the more important factors. The IO size is the size of the input/output operation request
generated by your application. The IO size has a significant impact on performance especially on the IOPS and
Bandwidth that the application is able to achieve. The following formula shows the relationship between IOPS, IO
size, and Bandwidth/Throughput.

Some applications allow you to alter their IO size, while some applications do not. For example, SQL Server
determines the optimal IO size itself, and does not provide users with any knobs to change it. On the other hand,
Oracle provides a parameter called DB_BLOCK_SIZE using which you can configure the I/O request size of the
database.
If you are using an application, which does not allow you to change the IO size, use the guidelines in this article to
optimize the performance KPI that is most relevant to your application. For example,
An OLTP application generates millions of small and random IO requests. To handle these types of IO requests,
you must design your application infrastructure to get higher IOPS.
A data warehousing application generates large and sequential IO requests. To handle these types of IO
requests, you must design your application infrastructure to get higher Bandwidth or Throughput.
If you are using an application, which allows you to change the IO size, use this rule of thumb for the IO size in
addition to other performance guidelines,
Smaller IO size to get higher IOPS. For example, 8 KB for an OLTP application.
Larger IO size to get higher Bandwidth/Throughput. For example, 1024 KB for a data warehouse application.
Here is an example on how you can calculate the IOPS and Throughput/Bandwidth for your application. Consider
an application using a P30 disk. The maximum IOPS and Throughput/Bandwidth a P30 disk can achieve is 5000
IOPS and 200 MB per second respectively. Now, if your application requires the maximum IOPS from the P30
disk and you use a smaller IO size like 8 KB, the resulting Bandwidth you will be able to get is 40 MB per second.
However, if your application requires the maximum Throughput/Bandwidth from P30 disk, and you use a larger
IO size like 1024 KB, the resulting IOPS will be less, 200 IOPS. Therefore, tune the IO size such that it meets both
your application's IOPS and Throughput/Bandwidth requirement. The following table summarizes the different IO
sizes and their corresponding IOPS and Throughput for a P30 disk.

APPLICATION REQUIREMENT I/O SIZE IOPS THROUGHPUT/BANDWIDTH

Max IOPS 8 KB 5,000 40 MB per second

Max Throughput 1024 KB 200 200 MB per second

Max Throughput + high 64 KB 3,200 200 MB per second


IOPS

Max IOPS + high 32 KB 5,000 160 MB per second


Throughput
To get IOPS and Bandwidth higher than the maximum value of a single premium storage disk, use multiple
premium disks striped together. For example, stripe two P30 disks to get a combined IOPS of 10,000 IOPS or a
combined Throughput of 400 MB per second. As explained in the next section, you must use a VM size that
supports the combined disk IOPS and Throughput.

NOTE
As you increase either IOPS or Throughput the other also increases, make sure you do not hit throughput or IOPS limits of
the disk or VM when increasing either one.

To witness the effects of IO size on application performance, you can run benchmarking tools on your VM and
disks. Create multiple test runs and use different IO size for each run to see the impact. Refer to the Benchmarking
article, linked at the end, for more details.

High scale VM sizes


When you start designing an application, one of the first things to do is, choose a VM to host your application.
Premium Storage comes with High Scale VM sizes that can run applications requiring higher compute power and
a high local disk I/O performance. These VMs provide faster processors, a higher memory-to-core ratio, and a
Solid-State Drive (SSD ) for the local disk. Examples of High Scale VMs supporting Premium Storage are the DS
and GS series VMs.
High Scale VMs are available in different sizes with a different number of CPU cores, memory, OS, and temporary
disk size. Each VM size also has maximum number of data disks that you can attach to the VM. Therefore, the
chosen VM size will affect how much processing, memory, and storage capacity is available for your application. It
also affects the Compute and Storage cost. For example, below are the specifications of the largest VM size in a DS
series and a GS series:

BANDWIDTH
VM DISK MAX. DATA CACHE IO
VM SIZE CPU CORES MEMORY SIZES DISKS CACHE SIZE IOPS LIMITS

Standard_D 16 112 GB OS = 1023 32 576 GB 50,000 4,000 IOPS


S14 GB IOPS and 33 MB
Local SSD = 512 MB per per second
224 GB second

Standard_G 32 448 GB OS = 1023 64 4224 GB 80,000 5,000 IOPS


S5 GB IOPS and 50 MB
Local SSD = 2,000 MB per second
896 GB per second

To view a complete list of all available Azure VM sizes, refer to Windows VM sizes or Linux VM sizes. Choose a
VM size that can meet and scale to your desired application performance requirements. In addition to this, take
into account following important considerations when choosing VM sizes.
Scale Limits
The maximum IOPS limits per VM and per disk are different and independent of each other. Make sure that the
application is driving IOPS within the limits of the VM as well as the premium disks attached to it. Otherwise,
application performance will experience throttling.
As an example, suppose an application requirement is a maximum of 4,000 IOPS. To achieve this, you provision a
P30 disk on a DS1 VM. The P30 disk can deliver up to 5,000 IOPS. However, the DS1 VM is limited to 3,200
IOPS. Consequently, the application performance will be constrained by the VM limit at 3,200 IOPS and there will
be degraded performance. To prevent this situation, choose a VM and disk size that will both meet application
requirements.
Cost of Operation
In many cases, it is possible that your overall cost of operation using Premium Storage is lower than using
Standard Storage.
For example, consider an application requiring 16,000 IOPS. To achieve this performance, you will need a
Standard_D14 Azure IaaS VM, which can give a maximum IOPS of 16,000 using 32 standard storage 1 TB disks.
Each 1-TB standard storage disk can achieve a maximum of 500 IOPS. The estimated cost of this VM per month
will be $1,570. The monthly cost of 32 standard storage disks will be $1,638. The estimated total monthly cost will
be $3,208.
However, if you hosted the same application on Premium Storage, you will need a smaller VM size and fewer
premium storage disks, thus reducing the overall cost. A Standard_DS13 VM can meet the 16,000 IOPS
requirement using four P30 disks. The DS13 VM has a maximum IOPS of 25,600 and each P30 disk has a
maximum IOPS of 5,000. Overall, this configuration can achieve 5,000 x 4 = 20,000 IOPS. The estimated cost of
this VM per month will be $1,003. The monthly cost of four P30 premium storage disks will be $544.34. The
estimated total monthly cost will be $1,544.
Table below summarizes the cost breakdown of this scenario for Standard and Premium Storage.

STANDARD PREMIUM

Cost of VM per month $1,570.58 (Standard_D14) $1,003.66 (Standard_DS13)

Cost of Disks per month $1,638.40 (32 x 1-TB disks) $544.34 (4 x P30 disks)

Overall Cost per month $3,208.98 $1,544.34

Linux Distros
With Azure Premium Storage, you get the same level of Performance for VMs running Windows and Linux. We
support many flavors of Linux distros, and you can see the complete list here. It is important to note that different
distros are better suited for different types of workloads. You will see different levels of performance depending on
the distro your workload is running on. Test the Linux distros with your application and choose the one that works
best.
When running Linux with Premium Storage, check the latest updates about required drivers to ensure high
performance.

Premium storage disk sizes


Azure Premium Storage offers a variety of sizes so you can choose one that best suits your needs. Each disk size
has a different scale limit for IOPS, bandwidth, and storage. Choose the right Premium Storage Disk size
depending on the application requirements and the high scale VM size. The table below shows the disks sizes and
their capabilities. P4, P6, P15, P60, P70, and P80 sizes are currently only supported for Managed Disks.

PRE
MIU
M
SSD
SIZE
S P1* P2* P3* P4 P6 P10 P15 P20 P30 P40 P50 P60 P70 P80

Disk 4 8 16 32 64 128 256 512 1,02 2,04 4,09 8,19 16,3 32,7
size 4 8 6 2 84 67
in
GiB
PRE
MIU
M
SSD
SIZE
S P1* P2* P3* P4 P6 P10 P15 P20 P30 P40 P50 P60 P70 P80

IOP 120 120 120 120 240 500 1,10 2,30 5,00 7,50 7,50 16,0 18,0 20,0
S 0 0 0 0 0 00 00 00
per
disk

Thr 25 25 25 25 50 100 125 150 200 250 250 500 750 900
oug MiB MiB MiB MiB MiB MiB MiB MiB MiB MiB MiB MiB MiB MiB
hpu /sec /sec /sec /sec /sec /sec /sec /sec /sec /sec /sec /sec /sec /sec
t
per
disk

Max 3,5 3,5 3,5 3,5 3,5 3,50 3,50 3,50


bur 00 00 00 00 00 0 0 0
st
IOP
S
per
disk
**

Max 170 170 170 170 170 170 170 170


bur MiB MiB MiB MiB MiB MiB MiB MiB
st /sec /sec /sec /sec /sec /sec /sec /sec
thro
ugh
put
per
disk
**

Max 30 30 30 30 30 30 30 30
bur min min min min min min min min
st
dur
atio
n**

Eligi No No No No No No No No Yes, Yes, Yes, Yes, Yes, Yes,


ble up up up up up up
for to to to to to to
rese one one one one one one
rvat year year year year year year
ion

*Denotes a disk size that is currently in preview, for regional availability information see New disk sizes: Managed
and unmanaged.
**Denotes a feature that is currently in preview, see Disk bursting for more information.
How many disks you choose depends on the disk size chosen. You could use a single P50 disk or multiple P10
disks to meet your application requirement. Take into account considerations listed below when making the choice.
Scale Limits (IOPS and Throughput)
The IOPS and Throughput limits of each Premium disk size is different and independent from the VM scale limits.
Make sure that the total IOPS and Throughput from the disks are within scale limits of the chosen VM size.
For example, if an application requirement is a maximum of 250 MB/sec Throughput and you are using a DS4 VM
with a single P30 disk. The DS4 VM can give up to 256 MB/sec Throughput. However, a single P30 disk has
Throughput limit of 200 MB/sec. Consequently, the application will be constrained at 200 MB/sec due to the disk
limit. To overcome this limit, provision more than one data disks to the VM or resize your disks to P40 or P50.

NOTE
Reads served by the cache are not included in the disk IOPS and Throughput, hence not subject to disk limits. Cache has its
separate IOPS and Throughput limit per VM.
For example, initially your reads and writes are 60MB/sec and 40MB/sec respectively. Over time, the cache warms up and
serves more and more of the reads from the cache. Then, you can get higher write Throughput from the disk.

Number of Disks
Determine the number of disks you will need by assessing application requirements. Each VM size also has a limit
on the number of disks that you can attach to the VM. Typically, this is twice the number of cores. Ensure that the
VM size you choose can support the number of disks needed.
Remember, the Premium Storage disks have higher performance capabilities compared to Standard Storage disks.
Therefore, if you are migrating your application from Azure IaaS VM using Standard Storage to Premium Storage,
you will likely need fewer premium disks to achieve the same or higher performance for your application.

Disk caching
High Scale VMs that leverage Azure Premium Storage have a multi-tier caching technology called BlobCache.
BlobCache uses a combination of the Virtual Machine RAM and local SSD for caching. This cache is available for
the Premium Storage persistent disks and the VM local disks. By default, this cache setting is set to Read/Write for
OS disks and ReadOnly for data disks hosted on Premium Storage. With disk caching enabled on the Premium
Storage disks, the high scale VMs can achieve extremely high levels of performance that exceed the underlying
disk performance.

WARNING
Disk Caching is not supported for disks 4 TiB and larger. If multiple disks are attached to your VM, each disk that is smaller
than 4 TiB will support caching.
Changing the cache setting of an Azure disk detaches and re-attaches the target disk. If it is the operating system disk, the
VM is restarted. Stop all applications/services that might be affected by this disruption before changing the disk cache
setting.

To learn more about how BlobCache works, refer to the Inside Azure Premium Storage blog post.
It is important to enable cache on the right set of disks. Whether you should enable disk caching on a premium
disk or not will depend on the workload pattern that disk will be handling. Table below shows the default cache
settings for OS and Data disks.

DISK TYPE DEFAULT CACHE SETTING

OS disk ReadWrite

Data disk ReadOnly

Following are the recommended disk cache settings for data disks,
DISK CACHING SETTING RECOMMENDATION ON WHEN TO USE THIS SETTING

None Configure host-cache as None for write-only and write-heavy


disks.

ReadOnly Configure host-cache as ReadOnly for read-only and read-


write disks.

ReadWrite Configure host-cache as ReadWrite only if your application


properly handles writing cached data to persistent disks when
needed.

ReadOnly
By configuring ReadOnly caching on Premium Storage data disks, you can achieve low Read latency and get very
high Read IOPS and Throughput for your application. This is due two reasons,
1. Reads performed from cache, which is on the VM memory and local SSD, are much faster than reads from the
data disk, which is on the Azure blob storage.
2. Premium Storage does not count the Reads served from cache, towards the disk IOPS and Throughput.
Therefore, your application is able to achieve higher total IOPS and Throughput.
ReadWrite
By default, the OS disks have ReadWrite caching enabled. We have recently added support for ReadWrite caching
on data disks as well. If you are using ReadWrite caching, you must have a proper way to write the data from cache
to persistent disks. For example, SQL Server handles writing cached data to the persistent storage disks on its own.
Using ReadWrite cache with an application that does not handle persisting the required data can lead to data loss,
if the VM crashes.
None
Currently, None is only supported on data disks. It is not supported on OS disks. If you set None on an OS disk it
will override this internally and set it to ReadOnly.
As an example, you can apply these guidelines to SQL Server running on Premium Storage by doing the
following,
1. Configure "ReadOnly" cache on premium storage disks hosting data files.
a. The fast reads from cache lower the SQL Server query time since data pages are retrieved much faster from
the cache compared to directly from the data disks.
b. Serving reads from cache, means there is additional Throughput available from premium data disks. SQL
Server can use this additional Throughput towards retrieving more data pages and other operations like
backup/restore, batch loads, and index rebuilds.
2. Configure "None" cache on premium storage disks hosting the log files.
a. Log files have primarily write-heavy operations. Therefore, they do not benefit from the ReadOnly cache.

Optimize performance on Linux VMs


For all premium SSDs or ultra disks with cache set to ReadOnly or None, you must disable "barriers" when you
mount the file system. You don't need barriers in this scenario because the writes to premium storage disks are
durable for these cache settings. When the write request successfully finishes, data has been written to the
persistent store. To disable "barriers," use one of the following methods. Choose the one for your file system:
For reiserFS, to disable barriers, use the barrier=none mount option. (To enable barriers, use barrier=flush .)
For ext3/ext4, to disable barriers, use the barrier=0 mount option. (To enable barriers, use barrier=1 .)
For XFS, to disable barriers, use the nobarrier mount option. (To enable barriers, use barrier .)
For premium storage disks with cache set to ReadWrite, enable barriers for write durability.
For volume labels to persist after you restart the VM, you must update /etc/fstab with the universally unique
identifier (UUID ) references to the disks. For more information, see Add a managed disk to a Linux VM.
The following Linux distributions have been validated for premium SSDs. For better performance and stability
with premium SSDs, we recommend that you upgrade your VMs to one of these versions or newer.
Some of the versions require the latest Linux Integration Services (LIS ), v4.0, for Azure. To download and install a
distribution, follow the link listed in the following table. We add images to the list as we complete validation. Our
validations show that performance varies for each image. Performance depends on workload characteristics and
your image settings. Different images are tuned for different kinds of workloads.

DISTRIBUTION VERSION SUPPORTED KERNEL DETAILS

Ubuntu 12.04 or newer 3.2.0-75.110+

Ubuntu 14.04 or newer 3.13.0-44.73+

Debian 7.x, 8.x or newer 3.16.7-ckt4-1+

SUSE SLES 12 or newer 3.12.36-38.1+

SUSE SLES 11 SP4 or newer 3.0.101-0.63.1+

CoreOS 584.0.0+ or newer 3.18.4+

CentOS 6.5, 6.6, 6.7, 7.0, or newer LIS4 required


See note in the next section

CentOS 7.1+ or newer 3.10.0-229.1.2.el7+ LIS4 recommended


See note in the next section

Red Hat Enterprise Linux 6.8+, 7.2+, or newer


(RHEL)

Oracle 6.0+, 7.2+, or newer UEK4 or RHCK

Oracle 7.0-7.1 or newer UEK4 or RHCK w/LIS4

Oracle 6.4-6.7 or newer UEK4 or RHCK w/LIS4

LIS drivers for OpenLogic CentOS


If you're running OpenLogic CentOS VMs, run the following command to install the latest drivers:

sudo yum remove hypervkvpd ## (Might return an error if not installed. That's OK.)
sudo yum install microsoft-hyper-v
sudo reboot

In some cases the command above will upgrade the kernel as well. If a kernel update is required then you may
need to run the above commands again after rebooting to fully install the microsoft-hyper-v package.

Disk striping
When a high scale VM is attached with several premium storage persistent disks, the disks can be striped together
to aggregate their IOPs, bandwidth, and storage capacity.
On Windows, you can use Storage Spaces to stripe disks together. You must configure one column for each disk in
a pool. Otherwise, the overall performance of striped volume can be lower than expected, due to uneven
distribution of traffic across the disks.
Important: Using Server Manager UI, you can set the total number of columns up to 8 for a striped volume. When
attaching more than eight disks, use PowerShell to create the volume. Using PowerShell, you can set the number
of columns equal to the number of disks. For example, if there are 16 disks in a single stripe set; specify 16
columns in the NumberOfColumns parameter of the New -VirtualDisk PowerShell cmdlet.
On Linux, use the MDADM utility to stripe disks together. For detailed steps on striping disks on Linux refer to
Configure Software RAID on Linux.
Stripe Size
An important configuration in disk striping is the stripe size. The stripe size or block size is the smallest chunk of
data that application can address on a striped volume. The stripe size you configure depends on the type of
application and its request pattern. If you choose the wrong stripe size, it could lead to IO misalignment, which
leads to degraded performance of your application.
For example, if an IO request generated by your application is bigger than the disk stripe size, the storage system
writes it across stripe unit boundaries on more than one disk. When it is time to access that data, it will have to
seek across more than one stripe units to complete the request. The cumulative effect of such behavior can lead to
substantial performance degradation. On the other hand, if the IO request size is smaller than stripe size, and if it is
random in nature, the IO requests may add up on the same disk causing a bottleneck and ultimately degrading the
IO performance.
Depending on the type of workload your application is running, choose an appropriate stripe size. For random
small IO requests, use a smaller stripe size. Whereas for large sequential IO requests use a larger stripe size. Find
out the stripe size recommendations for the application you will be running on Premium Storage. For SQL Server,
configure stripe size of 64 KB for OLTP workloads and 256 KB for data warehousing workloads. See Performance
best practices for SQL Server on Azure VMs to learn more.

NOTE
You can stripe together a maximum of 32 premium storage disks on a DS series VM and 64 premium storage disks on a GS
series VM.

Multi-threading
Azure has designed Premium Storage platform to be massively parallel. Therefore, a multi-threaded application
achieves much higher performance than a single-threaded application. A multi-threaded application splits up its
tasks across multiple threads and increases efficiency of its execution by utilizing the VM and disk resources to the
maximum.
For example, if your application is running on a single core VM using two threads, the CPU can switch between the
two threads to achieve efficiency. While one thread is waiting on a disk IO to complete, the CPU can switch to the
other thread. In this way, two threads can accomplish more than a single thread would. If the VM has more than
one core, it further decreases running time since each core can execute tasks in parallel.
You may not be able to change the way an off-the-shelf application implements single threading or multi-
threading. For example, SQL Server is capable of handling multi-CPU and multi-core. However, SQL Server
decides under what conditions it will leverage one or more threads to process a query. It can run queries and build
indexes using multi-threading. For a query that involves joining large tables and sorting data before returning to
the user, SQL Server will likely use multiple threads. However, a user cannot control whether SQL Server executes
a query using a single thread or multiple threads.
There are configuration settings that you can alter to influence this multi-threading or parallel processing of an
application. For example, in case of SQL Server it is the maximum Degree of Parallelism configuration. This setting
called MAXDOP, allows you to configure the maximum number of processors SQL Server can use when parallel
processing. You can configure MAXDOP for individual queries or index operations. This is beneficial when you
want to balance resources of your system for a performance critical application.
For example, say your application using SQL Server is executing a large query and an index operation at the same
time. Let us assume that you wanted the index operation to be more performant compared to the large query. In
such a case, you can set MAXDOP value of the index operation to be higher than the MAXDOP value for the
query. This way, SQL Server has more number of processors that it can leverage for the index operation compared
to the number of processors it can dedicate to the large query. Remember, you do not control the number of
threads SQL Server will use for each operation. You can control the maximum number of processors being
dedicated for multi-threading.
Learn more about Degrees of Parallelism in SQL Server. Find out such settings that influence multi-threading in
your application and their configurations to optimize performance.

Queue depth
The queue depth or queue length or queue size is the number of pending IO requests in the system. The value of
queue depth determines how many IO operations your application can line up, which the storage disks will be
processing. It affects all the three application performance indicators that we discussed in this article viz., IOPS,
throughput, and latency.
Queue Depth and multi-threading are closely related. The Queue Depth value indicates how much multi-threading
can be achieved by the application. If the Queue Depth is large, application can execute more operations
concurrently, in other words, more multi-threading. If the Queue Depth is small, even though application is multi-
threaded, it will not have enough requests lined up for concurrent execution.
Typically, off the shelf applications do not allow you to change the queue depth, because if set incorrectly it will do
more harm than good. Applications will set the right value of queue depth to get the optimal performance.
However, it is important to understand this concept so that you can troubleshoot performance issues with your
application. You can also observe the effects of queue depth by running benchmarking tools on your system.
Some applications provide settings to influence the Queue Depth. For example, the MAXDOP (maximum degree
of parallelism) setting in SQL Server explained in previous section. MAXDOP is a way to influence Queue Depth
and multi-threading, although it does not directly change the Queue Depth value of SQL Server.
High queue depth
A high queue depth lines up more operations on the disk. The disk knows the next request in its queue ahead of
time. Consequently, the disk can schedule operations ahead of time and process them in an optimal sequence.
Since the application is sending more requests to the disk, the disk can process more parallel IOs. Ultimately, the
application will be able to achieve higher IOPS. Since application is processing more requests, the total
Throughput of the application also increases.
Typically, an application can achieve maximum Throughput with 8-16+ outstanding IOs per attached disk. If a
queue depth is one, application is not pushing enough IOs to the system, and it will process less amount of in a
given period. In other words, less Throughput.
For example, in SQL Server, setting the MAXDOP value for a query to "4" informs SQL Server that it can use up
to four cores to execute the query. SQL Server will determine what is best queue depth value and the number of
cores for the query execution.
Optimal queue depth
Very high queue depth value also has its drawbacks. If queue depth value is too high, the application will try to
drive very high IOPS. Unless application has persistent disks with sufficient provisioned IOPS, this can negatively
affect application latencies. Following formula shows the relationship between IOPS, latency, and queue depth.

You should not configure Queue Depth to any high value, but to an optimal value, which can deliver enough IOPS
for the application without affecting latencies. For example, if the application latency needs to be 1 millisecond, the
Queue Depth required to achieve 5,000 IOPS is, QD = 5000 x 0.001 = 5.
Queue Depth for Striped Volume
For a striped volume, maintain a high enough queue depth such that, every disk has a peak queue depth
individually. For example, consider an application that pushes a queue depth of 2 and there are four disks in the
stripe. The two IO requests will go to two disks and remaining two disks will be idle. Therefore, configure the
queue depth such that all the disks can be busy. Formula below shows how to determine the queue depth of
striped volumes.

Throttling
Azure Premium Storage provisions specified number of IOPS and Throughput depending on the VM sizes and
disk sizes you choose. Anytime your application tries to drive IOPS or Throughput above these limits of what the
VM or disk can handle, Premium Storage will throttle it. This manifests in the form of degraded performance in
your application. This can mean higher latency, lower Throughput, or lower IOPS. If Premium Storage does not
throttle, your application could completely fail by exceeding what its resources are capable of achieving. So, to
avoid performance issues due to throttling, always provision sufficient resources for your application. Take into
consideration what we discussed in the VM sizes and Disk sizes sections above. Benchmarking is the best way to
figure out what resources you will need to host your application.

Next steps
If you are looking to benchmark your disk, see our article on Benchmarking a disk.
Learn more about the available disk types: Select a disk type
For SQL Server users, read articles on Performance Best Practices for SQL Server:
Performance Best Practices for SQL Server in Azure Virtual Machines
Azure Premium Storage provides highest performance for SQL Server in Azure VM
Premium SSD bursting (preview)
12/2/2019 • 4 minutes to read • Edit Online

Disk bursting is currently a preview feature for premium SSDs. Bursting is supported on any premium SSD disk
sizes <= 512 GiB (P20 or below ). These disk sizes support bursting on a best effort basis and utilize a credit system
to manage bursting. Credits accumulate in a burst bucket whenever disk traffic is below the provisioned
performance target for their disk size, and consume credits when traffic bursts beyond the target. Disk traffic is
tracked against both IOPS and bandwidth in the provisioned target.
Disk bursting is enabled by default on new deployments of the disk sizes that support it. Existing disk sizes, if they
support disk bursting, can enable bursting through either of the following methods:
Detach and reattach the disk.
Stop and start the VM.

Burst states
All burst applicable disk sizes will start with a full burst credit bucket when the disk is attached to a Virtual Machine.
The max duration of bursting is determined by the size of the burst credit bucket. You can only accumulate unused
credits up to the size of the credit bucket. At any point of time, your disk burst credit bucket can be in one of the
following three states:
Accruing, when the disk traffic is using less than the provisioned performance target. You can accumulate
credit if disk traffic is beyond IOPS or bandwidth targets or both. You can still accumulate IO credits when
you are consuming full disk bandwidth, vice versa.
Declining, when the disk traffic is using more than the provisioned performance target. The burst traffic will
independently consume credits from IOPS or bandwidth.
Remaining constant, when the disk traffic is exactly at the provisioned performance target.
The disk sizes that provide bursting support along with the burst specifications are summarized in the table below.

Regional availability
Currently, disk bursting is only available in the West Central US region.

Disk sizes
PRE
MIU
M
SSD
SIZE
S P1* P2* P3* P4 P6 P10 P15 P20 P30 P40 P50 P60 P70 P80

Disk 4 8 16 32 64 128 256 512 1,02 2,04 4,09 8,19 16,3 32,7
size 4 8 6 2 84 67
in
GiB
PRE
MIU
M
SSD
SIZE
S P1* P2* P3* P4 P6 P10 P15 P20 P30 P40 P50 P60 P70 P80

IOP 120 120 120 120 240 500 1,10 2,30 5,00 7,50 7,50 16,0 18,0 20,0
S 0 0 0 0 0 00 00 00
per
disk

Thr 25 25 25 25 50 100 125 150 200 250 250 500 750 900
oug MiB MiB MiB MiB MiB MiB MiB MiB MiB MiB MiB MiB MiB MiB
hpu /sec /sec /sec /sec /sec /sec /sec /sec /sec /sec /sec /sec /sec /sec
t
per
disk

Max 3,5 3,5 3,50 3,50 3,50 3,50 3,50 3,50


bur 00 00 0 0 0 0 0 0
st
IOP
S
per
disk
**

Max 170 170 170 170 170 170 170 170


bur MiB MiB MiB MiB MiB MiB MiB MiB
st /sec /sec /sec /sec /sec /sec /sec /sec
thro
ugh
put
per
disk
**

Max 30 30 30 30 30 30 30 30
bur min min min min min min min min
st
dur
atio
n**

Eligi No No No No No No No No Yes, Yes, Yes, Yes, Yes, Yes,


ble up up up up up up
for to to to to to to
rese one one one one one one
rvat year year year year year year
ion

*Denotes a disk size that is currently in preview, for regional availability information see New disk sizes: Managed
and unmanaged.
**Denotes a feature that is currently in preview, see Disk bursting for more information.

Example scenarios
To give you a better idea of how this works, here's a few example scenarios:
One common scenario that can benefit from disk bursting is faster VM boot and application launch on OS
disks. Take a Linux VM with an 8 GiB OS image as an example. If we use a P2 disk as the OS disk, the
provisioned target is 120 IOPS and 25 MBps. When VM starts, there will be a read spike to the OS disk
loading the boot files. With the introduction of bursting, you can read at the max burst speed of 3500 IOPS
and 170 MBps, accelerating the load time by at least 6x. After VM boot, the traffic level on the OS disk is
usually low, since most data operations by the application will be against the attached data disks. If the traffic
is below the provisioned target, you will accumulate credits.
If you are hosting a Remote Virtual Desktop environment, whenever an active user launches an application
like AutoCAD, read traffic to the OS disk significantly increases. In this case, burst traffic will consume
accumulated credits, allowing you to go beyond the provisioned target, and launching the application much
faster.
A P1 disk has a provisioned target of 120 IOPS and 25 MBps. If the actual traffic on the disk was 100 IOPS
and 20 MBps in the past 1 second interval, then the unused 20 IOs and 5 MB are credited to the burst
bucket of the disk. Credits in the burst bucket can later be used when the traffic exceeds the provisioned
target, up to the max burst limit. The max burst limit defines the ceiling of disk traffic even if you have burst
credits to consume from. In this case, even if you have 10,000 IOs in the credit bucket, a P1 disk cannot issue
more than the max burst of 3,500 IO per sec.

Next steps
Attach a managed data disk to a Windows VM by using the Azure portal
Scalability and performance targets for VM disks on
Windows
1/3/2020 • 5 minutes to read • Edit Online

You can attach a number of data disks to an Azure virtual machine. Based on the scalability and performance
targets for a VM's data disks, you can determine the number and type of disk that you need to meet your
performance and capacity requirements.

IMPORTANT
For optimal performance, limit the number of highly utilized disks attached to the virtual machine to avoid possible throttling.
If all attached disks aren't highly utilized at the same time, the virtual machine can support a larger number of disks.

For Azure managed disks:


The following table illustrates the default and maximum limits of the number of resources per region per
subscription. There is no limit for the number of Managed Disks, snapshots and images per resource group.

RESOURCE DEFAULT LIMIT MAXIMUM LIMIT

Standard managed disks 50,000 50,000

Standard SSD managed disks 50,000 50,000

Premium managed disks 50,000 50,000

Standard_LRS snapshots 50,000 50,000

Standard_ZRS snapshots 50,000 50,000

Managed image 50,000 50,000

For Standard storage accounts: A Standard storage account has a maximum total request rate of 20,000
IOPS. The total IOPS across all of your virtual machine disks in a Standard storage account should not
exceed this limit.
You can roughly calculate the number of highly utilized disks supported by a single Standard storage
account based on the request rate limit. For example, for a Basic tier VM, the maximum number of highly
utilized disks is about 66, which is 20,000/300 IOPS per disk. The maximum number of highly utilized disks
for a Standard tier VM is about 40, which is 20,000/500 IOPS per disk.
For Premium storage accounts: A Premium storage account has a maximum total throughput rate of 50
Gbps. The total throughput across all of your VM disks should not exceed this limit.
See Windows VM sizes for additional details.

Managed virtual machine disks


Sizes denoted with an asterisk are currently in preview. See our FAQ to learn what regions they are available in.
Standard HDD managed disks

STAND
ARD
DISK
TYPE S4 S6 S10 S15 S20 S30 S40 S50 S60 S70 S80

Disk 32 64 128 256 512 1,024 2,048 4,096 8,192 16,38 32,76
size in 4 7
GiB

IOPS Up to Up to Up to Up to Up to Up to Up to Up to Up to Up to Up to
per 500 500 500 500 500 500 500 500 1,300 2,000 2,000
disk

Throu Up to Up to Up to Up to Up to Up to Up to Up to Up to Up to Up to
ghput 60 60 60 60 60 60 60 60 300 500 500
per MiB/s MiB/s MiB/s MiB/s MiB/s MiB/s MiB/s MiB/s MiB/s MiB/s MiB/s
disk ec ec ec ec ec ec ec ec ec ec ec

Standard SSD managed disks

STA
NDA
RD
SSD
SIZE
S E1* E2* E3* E4 E6 E10 E15 E20 E30 E40 E50 E60 E70 E80

Disk 4 8 16 32 64 128 256 512 1,02 2,04 4,09 8,19 16,3 32,7
size 4 8 6 2 84 67
in
GiB

IOP Up Up Up Up Up Up Up Up Up Up Up Up Up Up
S to to to to to to to to to to to to to to
per 120 120 120 120 240 500 500 500 500 500 500 2,00 4,00 6,00
disk 0 0 0

Thr Up Up Up Up Up Up Up Up Up Up Up Up Up Up
oug to to to to to to to to to to to to to to
hpu 25 25 25 25 50 60 60 60 60 60 60 400 600 750
t MiB MiB MiB MiB MiB MiB MiB MiB MiB MiB MiB MiB MiB MiB
per /sec /sec /sec /sec /sec /sec /sec /sec /sec /sec /sec /sec /sec /sec
disk

*Denotes a disk size that is currently in preview, for regional availability information see New disk sizes: Managed
and unmanaged.
Premium SSD managed disks: Per-disk limits

PRE
MIU
M
SSD
SIZE
S P1* P2* P3* P4 P6 P10 P15 P20 P30 P40 P50 P60 P70 P80

Disk 4 8 16 32 64 128 256 512 1,02 2,04 4,09 8,19 16,3 32,7
size 4 8 6 2 84 67
in
GiB
PRE
MIU
M
SSD
SIZE
S P1* P2* P3* P4 P6 P10 P15 P20 P30 P40 P50 P60 P70 P80

IOP 120 120 120 120 240 500 1,10 2,30 5,00 7,50 7,50 16,0 18,0 20,0
S 0 0 0 0 0 00 00 00
per
disk

Thr 25 25 25 25 50 100 125 150 200 250 250 500 750 900
oug MiB MiB MiB MiB MiB MiB MiB MiB MiB MiB MiB MiB MiB MiB
hpu /sec /sec /sec /sec /sec /sec /sec /sec /sec /sec /sec /sec /sec /sec
t
per
disk

Max 3,5 3,5 3,50 3,50 3,50 3,50 3,50 3,50


bur 00 00 0 0 0 0 0 0
st
IOP
S
per
disk
**

Max 170 170 170 170 170 170 170 170


bur MiB MiB MiB MiB MiB MiB MiB MiB
st /sec /sec /sec /sec /sec /sec /sec /sec
thro
ugh
put
per
disk
**

Max 30 30 30 30 30 30 30 30
bur min min min min min min min min
st
dur
atio
n**

Eligi No No No No No No No No Yes, Yes, Yes, Yes, Yes, Yes,


ble up up up up up up
for to to to to to to
rese one one one one one one
rvat year year year year year year
ion

*Denotes a disk size that is currently in preview, for regional availability information see New disk sizes: Managed
and unmanaged.
**Denotes a feature that is currently in preview, see Disk bursting for more information.
Premium SSD managed disks: Per-VM limits

RESOURCE DEFAULT LIMIT

Maximum IOPS Per VM 80,000 IOPS with GS5 VM

Maximum throughput per VM 2,000 MB/s with GS5 VM

Unmanaged virtual machine disks


Standard unmanaged virtual machine disks: Per-disk limits

VM TIER BASIC TIER VM STANDARD TIER VM

Disk size 4,095 GB 4,095 GB

Maximum 8-KB IOPS per persistent disk 300 500

Maximum number of disks that perform 66 40


the maximum IOPS

Premium unmanaged virtual machine disks: Per-account limits

RESOURCE DEFAULT LIMIT

Total disk capacity per account 35 TB

Total snapshot capacity per account 10 TB

Maximum bandwidth per account (ingress + egress)1 <=50 Gbps

1Ingress refers to all data from


requests that are sent to a storage account. Egress refers to all data from responses
that are received from a storage account.
Premium unmanaged virtual machine disks: Per-disk limits

PREMIUM
STORAGE DISK
TYPE P10 P20 P30 P40 P50

Disk size 128 GiB 512 GiB 1,024 GiB (1 TB) 2,048 GiB (2 TB) 4,095 GiB (4 TB)

Maximum IOPS 500 2,300 5,000 7,500 7,500


per disk

Maximum 100 MB/sec 150 MB/sec 200 MB/sec 250 MB/sec 250 MB/sec
throughput per
disk

Maximum 280 70 35 17 8
number of disks
per storage
account

Premium unmanaged virtual machine disks: Per-VM limits


RESOURCE DEFAULT LIMIT

Maximum IOPS per VM 80,000 IOPS with GS5 VM

Maximum throughput per VM 2,000 MB/sec with GS5 VM

See also
Azure subscription and service limits, quotas, and constraints
Backup and disaster recovery for Azure IaaS disks
12/10/2019 • 21 minutes to read • Edit Online

This article explains how to plan for backup and disaster recovery (DR ) of IaaS virtual machines (VMs) and disks in
Azure. This document covers both managed and unmanaged disks.
First, we cover the built-in fault tolerance capabilities in the Azure platform that helps guard against local failures.
We then discuss the disaster scenarios not fully covered by the built-in capabilities. We also show several examples
of workload scenarios where different backup and DR considerations can apply. We then review possible solutions
for the DR of IaaS disks.

Introduction
The Azure platform uses various methods for redundancy and fault tolerance to help protect customers from
localized hardware failures. Local failures can include problems with an Azure Storage server machine that stores
part of the data for a virtual disk or failures of an SSD or HDD on that server. Such isolated hardware component
failures can happen during normal operations.
The Azure platform is designed to be resilient to these failures. Major disasters can result in failures or the
inaccessibility of many storage servers or even a whole datacenter. Although your VMs and disks are normally
protected from localized failures, additional steps are necessary to protect your workload from region-wide
catastrophic failures, such as a major disaster, that can affect your VM and disks.
In addition to the possibility of platform failures, problems with a customer application or data can occur. For
example, a new version of your application might inadvertently make a change to the data that causes it to break.
In that case, you might want to revert the application and the data to a prior version that contains the last known
good state. This requires maintaining regular backups.
For regional disaster recovery, you must back up your IaaS VM disks to a different region.
Before we look at backup and DR options, let’s recap a few methods available for handling localized failures.
Azure IaaS resiliency
Resiliency refers to the tolerance for normal failures that occur in hardware components. Resiliency is the ability to
recover from failures and continue to function. It's not about avoiding failures, but responding to failures in a way
that avoids downtime or data loss. The goal of resiliency is to return the application to a fully functioning state
following a failure. Azure virtual machines and disks are designed to be resilient to common hardware faults. Let's
look at how the Azure IaaS platform provides this resiliency.
A virtual machine consists mainly of two parts: a compute server and the persistent disks. Both affect the fault
tolerance of a virtual machine.
If the Azure compute host server that houses your VM experiences a hardware failure, which is rare, Azure is
designed to automatically restore the VM on another server. If this scenario, your computer reboots, and the VM
comes back up after some time. Azure automatically detects such hardware failures and executes recoveries to help
ensure the customer VM is available as soon as possible.
Regarding IaaS disks, the durability of data is critical for a persistent storage platform. Azure customers have
important business applications running on IaaS, and they depend on the persistence of the data. Azure designs
protection for these IaaS disks, with three redundant copies of the data that is stored locally. These copies provide
for high durability against local failures. If one of the hardware components that holds your disk fails, your VM is
not affected, because there are two additional copies to support disk requests. It works fine, even if two different
hardware components that support a disk fail at the same time (which is rare).
To ensure that you always maintain three replicas, Azure Storage automatically spawns a new copy of the data in
the background if one of the three copies becomes unavailable. Therefore, it should not be necessary to use RAID
with Azure disks for fault tolerance. A simple RAID 0 configuration should be sufficient for striping the disks, if
necessary, to create larger volumes.
Because of this architecture, Azure has consistently delivered enterprise-grade durability for IaaS disks, with an
industry-leading zero percent annualized failure rate.
Localized hardware faults on the compute host or in the Storage platform can sometimes result in of the
temporary unavailability of the VM that is covered by the Azure SLA for VM availability. Azure also provides an
industry-leading SLA for single VM instances that use Azure premium SSDs.
To safeguard application workloads from downtime due to the temporary unavailability of a disk or VM, customers
can use availability sets. Two or more virtual machines in an availability set provide redundancy for the application.
Azure then creates these VMs and disks in separate fault domains with different power, network, and server
components.
Because of these separate fault domains, localized hardware failures typically do not affect multiple VMs in the set
at the same time. Having separate fault domains provides high availability for your application. It's considered a
good practice to use availability sets when high availability is required. The next section covers the disaster
recovery aspect.
Backup and disaster recovery
Disaster recovery is the ability to recover from rare, but major, incidents. These incidents include non-transient,
wide-scale failures, such as service disruption that affects an entire region. Disaster recovery includes data backup
and archiving, and might include manual intervention, such as restoring a database from a backup.
The Azure platform’s built-in protection against localized failures might not fully protect the VMs/disks if a major
disaster causes large-scale outages. These large-scale outages include catastrophic events, such as if a datacenter is
hit by a hurricane, earthquake, fire, or if there is a large-scale hardware unit failure. In addition, you might
encounter failures due to application or data issues.
To help protect your IaaS workloads from outages, you should plan for redundancy and have backups to enable
recovery. For disaster recovery, you should back up in a different geographic location away from the primary site.
This approach helps ensure your backup is not affected by the same event that originally affected the VM or disks.
For more information, see Disaster recovery for Azure applications.
Your DR considerations might include the following aspects:
High availability: The ability of the application to continue running in a healthy state, without significant
downtime. By healthy state, this state means that the application is responsive, and users can connect to the
application and interact with it. Certain mission-critical applications and databases might be required to
always be available, even when there are failures in the platform. For these workloads, you might need to
plan redundancy for the application, as well as the data.
Data durability: In some cases, the main consideration is ensuring that the data is preserved if a disaster
happens. Therefore, you might need a backup of your data in a different site. For such workloads, you might
not need full redundancy for the application, but only a regular backup of the disks.

Backup and DR scenarios


Let’s look at a few typical examples of application workload scenarios and the considerations for planning for
disaster recovery.
Scenario 1: Major database solutions
Consider a production database server, like SQL Server or Oracle, that can support high availability. Critical
production applications and users depend on this database. The disaster recovery plan for this system might need
to support the following requirements:
The data must be protected and recoverable.
The server must be available for use.
The disaster recovery plan might require maintaining a replica of the database in a different region as a backup.
Depending on the requirements for server availability and data recovery, the solution might range from an active-
active or active-passive replica site to periodic offline backups of the data. Relational databases, such as SQL
Server and Oracle, provide various options for replication. For SQL Server, use SQL Server AlwaysOn Availability
Groups for high availability.
NoSQL databases, like MongoDB, also support replicas for redundancy. The replicas for high availability are used.
Scenario 2: A cluster of redundant VMs
Consider a workload handled by a cluster of VMs that provide redundancy and load balancing. One example is a
Cassandra cluster deployed in a region. This type of architecture already provides a high level of redundancy
within that region. However, to protect the workload from a regional-level failure, you should consider spreading
the cluster across two regions or making periodic backups to another region.
Scenario 3: IaaS application workload
Let's look at the IaaS application workload. For example, this application might be a typical production workload
running on an Azure VM. It might be a web server or file server holding the content and other resources of a site.
It might also be a custom-built business application running on a VM that stored its data, resources, and
application state on the VM disks. In this case, it's important to make sure you take backups on a regular basis.
Backup frequency should be based on the nature of the VM workload. For example, if the application runs every
day and modifies data, then the backup should be taken every hour.
Another example is a reporting server that pulls data from other sources and generates aggregated reports. The
loss of this VM or disks might lead to the loss of the reports. However, it might be possible to rerun the reporting
process and regenerate the output. In that case, you don’t really have a loss of data, even if the reporting server is
hit with a disaster. As a result, you might have a higher level of tolerance for losing part of the data on the
reporting server. In that case, less frequent backups are an option to reduce costs.
Scenario 4: IaaS application data issues
IaaS application data issues are another possibility. Consider an application that computes, maintains, and serves
critical commercial data, such as pricing information. A new version of your application had a software bug that
incorrectly computed the pricing and corrupted the existing commerce data served by the platform. Here, the best
course of action is to revert to the earlier version of the application and the data. To enable this, take periodic
backups of your system.

Disaster recovery solution: Azure Backup


Azure Backup is used for backups and DR, and it works with managed disks as well as unmanaged disks. You can
create a backup job with time-based backups, easy VM restoration, and backup retention policies.
If you use premium SSDs, managed disks, or other disk types with the locally redundant storage option, it's
especially important to make periodic DR backups. Azure Backup stores the data in your recovery services vault
for long-term retention. Choose the geo-redundant storage option for the backup recovery services vault. That
option ensures that backups are replicated to a different Azure region for safeguarding from regional disasters.
For unmanaged disks, you can use the locally redundant storage type for IaaS disks, but ensure that Azure Backup
is enabled with the geo-redundant storage option for the recovery services vault.
NOTE
If you use the geo-redundant storage or read-access geo-redundant storage option for your unmanaged disks, you still
need consistent snapshots for backup and DR. Use either Azure Backup or consistent snapshots.

The following table is a summary of the solutions available for DR.

SCENARIO AUTOMATIC REPLICATION DR SOLUTION

Premium SSD disks Local (locally redundant storage) Azure Backup

Managed disks Local (locally redundant storage) Azure Backup

Unmanaged locally redundant storage Local (locally redundant storage) Azure Backup
disks

Unmanaged geo-redundant storage Cross region (geo-redundant storage) Azure Backup


disks Consistent snapshots

Unmanaged read-access geo- Cross region (read-access geo- Azure Backup


redundant storage disks redundant storage) Consistent snapshots

High availability is best met by using managed disks in an availability set along with Azure Backup. If you use
unmanaged disks, you can still use Azure Backup for DR. If you are unable to use Azure Backup, then taking
consistent snapshots, as described in a later section, is an alternative solution for backup and DR.
Your choices for high availability, backup, and DR at application or infrastructure levels can be represented as
follows:

LEVEL HIGH AVAILABILITY BACKUP OR DR

Application SQL Server AlwaysOn Azure Backup

Infrastructure Availability set Geo-redundant storage with consistent


snapshots

Using Azure Backup


Azure Backup can back up your VMs running Windows or Linux to the Azure recovery services vault. Backing up
and restoring business-critical data is complicated by the fact that business-critical data must be backed up while
the applications that produce the data are running.
To address this issue, Azure Backup provides application-consistent backups for Microsoft workloads. It uses the
volume shadow service to ensure that data is written correctly to storage. For Linux VMs, the default backup
consistency mode is file-consistent backups, because Linux does not have functionality equivalent to the volume
shadow service as in the case of Windows. For Linux machines, see Application-consistent backup of Azure Linux
VMs.
When Azure Backup initiates a backup job at the scheduled time, it triggers the backup extension installed in the
VM to take a point-in-time snapshot. A snapshot is taken in coordination with the volume shadow service to get a
consistent snapshot of the disks in the virtual machine without having to shut it down. The backup extension in the
VM flushes all writes before taking a consistent snapshot of all of the disks. After taking the snapshot, the data is
transferred by Azure Backup to the backup vault. To make the backup process more efficient, the service identifies
and transfers only the blocks of data that have changed after the last backup.
To restore, you can view the available backups through Azure Backup and then initiate a restore. You can create
and restore Azure backups through the Azure portal, by using PowerShell, or by using the Azure CLI.
Steps to enable a backup
Use the following steps to enable backups of your VMs by using the Azure portal. There is some variation
depending on your exact scenario. Refer to the Azure Backup documentation for full details. Azure Backup also
supports VMs with managed disks.
1. Create a recovery services vault for a VM:
a. In the Azure portal, browse All resources and find Recovery Services vaults.
b. On the Recovery Services vaults menu, click Add and follow the steps to create a new vault in the same
region as the VM. For example, if your VM is in the West US region, pick West US for the vault.
2. Verify the storage replication for the newly created vault. Access the vault under Recovery Services vaults
and go to Properties > Backup Configuration > Update. Ensure the geo-redundant storage option is
selected by default. This option ensures that your vault is automatically replicated to a secondary datacenter.
For example, your vault in West US is automatically replicated to East US.
3. Configure the backup policy and select the VM from the same UI.
4. Make sure the Backup Agent is installed on the VM. If your VM is created by using an Azure gallery image,
then the Backup Agent is already installed. Otherwise (that is, if you use a custom image), use the
instructions to install the VM agent on a virtual machine.
5. After the previous steps are completed, the backup runs at regular intervals as specified in the backup
policy. If necessary, you can trigger the first backup manually from the vault dashboard on the Azure portal.
For automating Azure Backup by using scripts, refer to PowerShell cmdlets for VM backup.
Steps for recovery
If you need to repair or rebuild a VM, you can restore the VM from any of the backup recovery points in the vault.
There are a couple of different options for performing the recovery:
You can create a new VM as a point-in-time representation of your backed-up VM.
You can restore the disks, and then use the template for the VM to customize and rebuild the restored VM.
For more information, see the instructions to use the Azure portal to restore virtual machines . This document also
explains the specific steps for restoring backed-up VMs to a paired datacenter by using your geo-redundant
backup vault if there is a disaster at the primary datacenter. In that case, Azure Backup uses the Compute service
from the secondary region to create the restored virtual machine.
You can also use PowerShell for creating a new VM from restored disks.

Alternative solution: Consistent snapshots


If you are unable to use Azure Backup, you can implement your own backup mechanism by using snapshots.
Creating consistent snapshots for all the disks used by a VM and then replicating those snapshots to another
region is complicated. For this reason, Azure considers using the Backup service as a better option than building a
custom solution.
If you use read-access geo-redundant storage/geo-redundant storage for disks, snapshots are automatically
replicated to a secondary datacenter. If you use locally redundant storage for disks, you need to replicate the data
yourself. For more information, see Back up Azure-unmanaged VM disks with incremental snapshots.
A snapshot is a representation of an object at a specific point in time. A snapshot incurs billing for the incremental
size of the data it holds. For more information, see Create a blob snapshot.
Create snapshots while the VM is running
Although you can take a snapshot at any time, if the VM is running, there is still data being streamed to the disks.
The snapshots might contain partial operations that were in flight. Also, if there are several disks involved, the
snapshots of different disks might have occurred at different times. These scenarios may cause to the snapshots to
be uncoordinated. This lack of co-ordination is especially problematic for striped volumes whose files might be
corrupted if changes were being made during backup.
To avoid this situation, the backup process must implement the following steps:
1. Freeze all the disks.
2. Flush all the pending writes.
3. Create a blob snapshot for all the disks.
Some Windows applications, like SQL Server, provide a coordinated backup mechanism via a volume shadow
service to create application-consistent backups. On Linux, you can use a tool like fsfreeze for coordinating the
disks. This tool provides file-consistent backups, but not application-consistent snapshots. This process is complex,
so you should consider using Azure Backup or a third-party backup solution that already implements this
procedure.
The previous process results in a collection of coordinated snapshots for all of the VM disks, representing a specific
point-in-time view of the VM. This is a backup restore point for the VM. You can repeat the process at scheduled
intervals to create periodic backups. See Copy the backups to another region for steps to copy the snapshots to
another region for DR.
Create snapshots while the VM is offline
Another option to create consistent backups is to shut down the VM and take blob snapshots of each disk. Taking
blob snapshots is easier than coordinating snapshots of a running VM, but it requires a few minutes of downtime.
1. Shut down the VM.
2. Create a snapshot of each virtual hard drive blob, which only takes a few seconds.
To create a snapshot, you can use PowerShell, the Azure Storage REST API, Azure CLI, or one of the Azure
Storage client libraries, such as the Storage client library for .NET.
3. Start the VM, which ends the downtime. Typically, the entire process finishes within a few minutes.
This process yields a collection of consistent snapshots for all the disks, providing a backup restore point for the
VM.
Copy the snapshots to another region
Creation of the snapshots alone might not be sufficient for DR. You must also replicate the snapshot backups to
another region.
If you use geo-redundant storage or read-access geo-redundant storage for your disks, then the snapshots are
replicated to the secondary region automatically. There can be a few minutes of lag before the replication. If the
primary datacenter goes down before the snapshots finish replicating, you cannot access the snapshots from the
secondary datacenter. The likelihood of this is small.

NOTE
Only having the disks in a geo-redundant storage or read-access geo-redundant storage account does not protect the VM
from disasters. You must also create coordinated snapshots or use Azure Backup. This is required to recover a VM to a
consistent state.

If you use locally redundant storage, you must copy the snapshots to a different storage account immediately after
creating the snapshot. The copy target might be a locally redundant storage account in a different region, resulting
in the copy being in a remote region. You can also copy the snapshot to a read-access geo-redundant storage
account in the same region. In this case, the snapshot is lazily replicated to the remote secondary region. Your
backup is protected from disasters at the primary site after the copying and replication is complete.
To copy your incremental snapshots for DR efficiently, review the instructions in Back up Azure unmanaged VM
disks with incremental snapshots.

Recovery from snapshots


To retrieve a snapshot, copy it to make a new blob. If you are copying the snapshot from the primary account, you
can copy the snapshot over to the base blob of the snapshot. This process reverts the disk to the snapshot. This
process is known as promoting the snapshot. If you are copying the snapshot backup from a secondary account, in
the case of a read-access geo-redundant storage account, you must copy it to a primary account. You can copy a
snapshot by using PowerShell or by using the AzCopy utility. For more information, see Transfer data with the
AzCopy command-line utility.
For VMs with multiple disks, you must copy all the snapshots that are part of the same coordinated restore point.
After you copy the snapshots to writable VHD blobs, you can use the blobs to recreate your VM by using the
template for the VM.

Other options
SQL Server
SQL Server running in a VM has its own built-in capabilities to back up your SQL Server database to Azure Blob
storage or a file share. If the storage account is geo-redundant storage or read-access geo-redundant storage, you
can access those backups in the storage account’s secondary datacenter in the event of a disaster, with the same
restrictions as previously discussed. For more information, see Back up and restore for SQL Server in Azure virtual
machines. In addition to back up and restore, SQL Server AlwaysOn availability groups can maintain secondary
replicas of databases. This ability greatly reduces the disaster recovery time.

Other considerations
This article has discussed how to back up or take snapshots of your VMs and their disks to support disaster
recovery and how to use those backups or snapshots to recover your data. With the Azure Resource Manager
model, many people use templates to create their VMs and other infrastructures in Azure. You can use a template
to create a VM that has the same configuration every time. If you use custom images for creating your VMs, you
must also make sure that your images are protected by using a read-access geo-redundant storage account to
store them.
Consequently, your backup process can be a combination of two things:
Back up the data (disks).
Back up the configuration (templates and custom images).
Depending on the backup option you choose, you might have to handle the backup of both the data and the
configuration, or the backup service might handle all of that for you.

Appendix: Understanding the impact of data redundancy


For storage accounts in Azure, there are three types of data redundancy that you should consider regarding
disaster recovery: locally redundant, geo-redundant, or geo-redundant with read access.
Locally redundant storage retains three copies of the data in the same datacenter. When the VM writes the data, all
three copies are updated before success is returned to the caller, so you know they are identical. Your disk is
protected from local failures, because it's unlikely that all three copies are affected at the same time. In the case of
locally redundant storage, there is no geo-redundancy, so the disk is not protected from catastrophic failures that
can affect an entire datacenter or storage unit.
With geo-redundant storage and read-access geo-redundant storage, three copies of your data are retained in the
primary region that is selected by you. Three more copies of your data are retained in a corresponding secondary
region that is set by Azure. For example, if you store data in West US, the data is replicated to East US. Copy
retention is done asynchronously, and there is a small delay between updates to the primary and secondary sites.
Replicas of the disks on the secondary site are consistent on a per-disk basis (with the delay), but replicas of
multiple active disks might not be in sync with each other. To have consistent replicas across multiple disks,
consistent snapshots are needed.
The main difference between geo-redundant storage and read-access geo-redundant storage is that with read-
access geo-redundant storage, you can read the secondary copy at any time. If there is a problem that renders the
data in the primary region inaccessible, the Azure team makes every effort to restore access. While the primary is
down, if you have read-access geo-redundant storage enabled, you can access the data in the secondary
datacenter. Therefore, if you plan to read from the replica while the primary is inaccessible, then read-access geo-
redundant storage should be considered.
If it turns out to be a significant outage, the Azure team might trigger a geo-failover and change the primary DNS
entries to point to secondary storage. At this point, if you have either geo-redundant storage or read-access geo-
redundant storage enabled, you can access the data in the region that used to be the secondary. In other words, if
your storage account is geo-redundant storage and there is a problem, you can access the secondary storage only
if there is a geo-failover.
For more information, see What to do if an Azure Storage outage occurs.

NOTE
Microsoft controls whether a failover occurs. Failover is not controlled per storage account, so it's not decided by individual
customers. To implement disaster recovery for specific storage accounts or virtual machine disks, you must use the
techniques described previously in this article.
Azure shared disks
2/19/2020 • 4 minutes to read • Edit Online

Azure shared disks (preview ) is a new feature for Azure managed disks that enables attaching an Azure managed
disk to multiple virtual machines (VMs) simultaneously. Attaching a managed disk to multiple VMs allows you to
either deploy new or migrate existing clustered applications to Azure.

How it works
VMs in the cluster can read or write to your attached disk based on the reservation chosen by the clustered
application using SCSI Persistent Reservations (SCSI PR ). SCSI PR is a well-known industry standard leveraged
by applications running on Storage Area Network (SAN ) on-premises. Enabling SCSI PR on a managed disk
allows you to migrate these applications to Azure as-is.
Managed disks with shared disks enabled offer shared block storage that can be accessed by multiple VMs, this is
exposed as logical unit numbers (LUNs). LUNs are then presented to an initiator (VM ) from a target (disk). These
LUNs look like direct-attached-storage (DAS ) or a local drive to the VM.
Managed disks with shared disks enabled do not natively offer a fully-managed file system that can be accessed
using SMB/NFS. You will need to use a cluster manager, like Windows Server Failover Cluster (WSFC ) or
Pacemaker, that handles cluster node communication as well as write locking.

Limitations
While in preview, managed disks that have shared disks enabled are subject to the following limitations:
Currently only available with premium SSDs.
Currently only supported in the West Central US region.
All virtual machines sharing a disk must be deployed in the same proximity placement groups.
Can only be enabled on data disks, not OS disks.
Only basic disks can be used with some versions of Windows Server Failover Cluster, for details see Failover
clustering hardware requirements and storage options.
ReadOnly host caching is not available for premium SSDs with maxShares>1 .
Availability sets and virtual machine scale sets can only be used with FaultDomainCount set to 1.
Azure Backup and Azure Site Recovery support is not yet available.
If you're interested in trying shared disks then sign up for our preview.

Disk sizes
For now, only premium SSDs can enable shared disks. The disk sizes that support this feature are P15 and greater.
Different disk sizes may have a different maxShares limit, which you cannot exceed when setting the maxShares
value.
For each disk, you can define a maxShares value that represents the maximum number of nodes that can
simultaneously share the disk. For example, if you plan to set up a 2-node failover cluster, you would set
maxShares=2 . The maximum value is an upper bound. Nodes can join or leave the cluster (mount or unmount the
disk) as long as the number of nodes is lower than the specified maxShares value.
NOTE
The maxShares value can only be set or edited when the disk is detached from all nodes.

The following table illustrates the allowed maximum values for maxShares by disk size:

DISK SIZES MAXSHARES LIMIT

P15, P20 2

P30, P40, P50 5

P60, P70, P80 10

The IOPS and bandwidth limits for a disk are not affected by the maxShares value. For example, the max IOPS of a
P15 disk are 1100 whether maxShares = 1 or maxShares > 1.

Sample workloads
Windows
Most Windows-based clustering build on WSFC, which handles all core infrastructure for cluster node
communication, allowing your applications to take advantage of parallel access patterns. WSFC enables both CSV
and non-CSV -based options depending on your version of Windows Server. For details, refer to Create a failover
cluster.
Some popular applications running on WSFC include:
SQL Server Failover Cluster Instances (FCI)
Scale-out File Server (SoFS )
File Server for General Use (IW workload)
Remote Desktop Server User Profile Disk (RDS UPD )
SAP ASCS/SCS
Linux
Linux clusters can leverage cluster managers such as Pacemaker. Pacemaker builds on Corosync, enabling cluster
communications for applications deployed in highly available environments. Some common clustered filesystems
include ocfs2 and gfs2. You can manipulate reservations and registrations using utilities such as fence_scsi and
sg_persist.

Persistent Reservation flow


The following diagram illustrates a sample 2-node clustered database application that leverages SCSI PR to enable
failover from one node to the other.
The flow is as follows:
1. The clustered application running on both Azure VM1 and VM2 registers its intent to read or write to the disk.
2. The application instance on VM1 then takes exclusive reservation to write to the disk.
3. This reservation is enforced on your Azure disk and the database can now exclusively write to the disk. Any
writes from the application instance on VM2 will not succeed.
4. If the application instance on VM1 goes down, the instance on VM2 can now initiate a database failover and
take-over of the disk.
5. This reservation is now enforced on the Azure disk and the disk will no longer accept writes from VM1. It will
only accept writes from VM2.
6. The clustered application can complete the database failover and serve requests from VM2.
The following diagram illustrates another common clustered workload consisting of multiple nodes reading data
from the disk for running parallel processes, such as training of machine learning models.
The flow is as follows:
1. The clustered application running on all VMs registers the intent to read or write to the disk.
2. The application instance on VM1 takes an exclusive reservation to write to the disk while opening up reads to
the disk from other VMs.
3. This reservation is enforced on your Azure disk.
4. All nodes in the cluster can now read from the disk. Only one node writes back results to the disk, on behalf of
all nodes in the cluster.

Next steps
If you're interested in enabling and using shared disks for your managed disks, proceed to our article Enable
shared disk.
Ephemeral OS disks for Azure VMs
11/13/2019 • 6 minutes to read • Edit Online

Ephemeral OS disks are created on the local virtual machine (VM ) storage and not saved to the remote Azure
Storage. Ephemeral OS disks work well for stateless workloads, where applications are tolerant of individual VM
failures, but are more affected by VM deployment time or reimaging the individual VM instances. With Ephemeral
OS disk, you get lower read/write latency to the OS disk and faster VM reimage.
The key features of ephemeral disks are:
Ideal for stateless applications.
They can be used with both Marketplace and custom images.
Ability to fast reset or reimage VMs and scale set instances to the original boot state.
Lower latency, similar to a temporary disk.
Ephemeral OS disks are free, you incur no storage cost for OS disk.
They are available in all Azure regions.
Ephemeral OS Disk is supported by Shared Image Gallery.
Key differences between persistent and ephemeral OS disks:

PERSISTENT OS DISK EPHEMERAL OS DISK

Size limit for OS disk 2 TiB Cache size for the VM size or
2TiB, whichever is smaller.
For the cache size in GiB,
see DS, ES, M, FS, and GS

VM sizes supported All DSv1, DSv2, DSv3, Esv3, Fs,


FsV2, GS, M

Disk type support Managed and unmanaged Managed OS disk only


OS disk

Region support All regions All regions

Data persistence OS disk data written to OS Data written to OS disk is


disk are stored in Azure stored to the local VM
Storage storage and is not persisted
to Azure Storage.

Stop-deallocated state VMs and scale set instances VMs and scale set instances
can be stop-deallocated and cannot be stop-deallocated
restarted from the stop-
deallocated state

Specialized OS disk support Yes No

OS disk resize Supported during VM Supported during VM


creation and after VM is creation only
stop-deallocated
PERSISTENT OS DISK EPHEMERAL OS DISK

Resizing to a new VM size OS disk data is preserved Data on the OS disk is


deleted, OS is re-provisioned

Size requirements
You can deploy VM and instance images up to the size of the VM cache. For example, Standard Windows Server
images from the marketplace are about 127 GiB, which means that you need a VM size that has a cache larger than
127 GiB. In this case, the Standard_DS2_v2 has a cache size of 86 GiB, which is not large enough. The
Standard_DS3_v2 has a cache size of 172 GiB, which is large enough. In this case, the Standard_DS3_v2 is the
smallest size in the DSv2 series that you can use with this image. Basic Linux images in the Marketplace and
Windows Server images that are denoted by [smallsize] tend to be around 30 GiB and can use most of the
available VM sizes.
Ephemeral disks also require that the VM size supports Premium storage. The sizes usually (but not always) have
an s in the name, like DSv2 and EsV3. For more information, see Azure VM sizes for details around which sizes
support Premium storage.

PowerShell
To use an ephemeral disk for a PowerShell VM deployment, use Set-AzVMOSDisk in your VM configuration. Set
the -DiffDiskSetting to Local and -Caching to ReadOnly .

Set-AzVMOSDisk -DiffDiskSetting Local -Caching ReadOnly

For scale set deployments, use the Set-AzVmssStorageProfile cmdlet in your configuration. Set the
-DiffDiskSetting to Local and -Caching to ReadOnly .

Set-AzVmssStorageProfile -DiffDiskSetting Local -OsDiskCaching ReadOnly

CLI
To use an ephemeral disk for a CLI VM deployment, set the --ephemeral-os-disk parameter in az vm create to
true and the --os-disk-caching parameter to ReadOnly .

az vm create \
--resource-group myResourceGroup \
--name myVM \
--image UbuntuLTS \
--ephemeral-os-disk true \
--os-disk-caching ReadOnly \
--admin-username azureuser \
--generate-ssh-keys

For scale sets, you use the same --ephemeral-os-disk true parameter for az-vmss-create and set the
--os-disk-caching parameter to ReadOnly .

Portal
In the Azure portal, you can choose to use ephemeral disks when deploying a VM by opening the Advanced
section of the Disks tab. For Use ephemeral OS disk select Yes.
If the option for using an ephemeral disk is greyed out, you might have selected a VM size that does not have a
cache size larger than the OS image or that doesn't support Premium storage. Go back to the Basics page and try
choosing another VM size.
You can also create scale-sets with ephemeral OS disks using the portal. Just make sure you select a VM size with a
large enough cache size and then in Use ephemeral OS disk select Yes.

Scale set template deployment


The process to create a scale set that uses an ephemeral OS disk is to add the diffDiskSettings property to the
Microsoft.Compute/virtualMachineScaleSets/virtualMachineProfile resource type in the template. Also, the caching
policy must be set to ReadOnly for the ephemeral OS disk.
{
"type": "Microsoft.Compute/virtualMachineScaleSets",
"name": "myScaleSet",
"location": "East US 2",
"apiVersion": "2018-06-01",
"sku": {
"name": "Standard_DS2_v2",
"capacity": "2"
},
"properties": {
"upgradePolicy": {
"mode": "Automatic"
},
"virtualMachineProfile": {
"storageProfile": {
"osDisk": {
"diffDiskSettings": {
"option": "Local"
},
"caching": "ReadOnly",
"createOption": "FromImage"
},
"imageReference": {
"publisher": "Canonical",
"offer": "UbuntuServer",
"sku": "16.04-LTS",
"version": "latest"
}
},
"osProfile": {
"computerNamePrefix": "myvmss",
"adminUsername": "azureuser",
"adminPassword": "P@ssw0rd!"
}
}
}
}

VM template deployment
You can deploy a VM with an ephemeral OS disk using a template. The process to create a VM that uses
ephemeral OS disks is to add the diffDiskSettings property to the Microsoft.Compute/virtualMachines resource
type in the template. Also, the caching policy must be set to ReadOnly for the ephemeral OS disk.
{
"type": "Microsoft.Compute/virtualMachines",
"name": "myVirtualMachine",
"location": "East US 2",
"apiVersion": "2018-06-01",
"properties": {
"storageProfile": {
"osDisk": {
"diffDiskSettings": {
"option": "Local"
},
"caching": "ReadOnly",
"createOption": "FromImage"
},
"imageReference": {
"publisher": "MicrosoftWindowsServer",
"offer": "WindowsServer",
"sku": "2016-Datacenter-smalldisk",
"version": "latest"
},
"hardwareProfile": {
"vmSize": "Standard_DS2_v2"
}
},
"osProfile": {
"computerNamePrefix": "myvirtualmachine",
"adminUsername": "azureuser",
"adminPassword": "P@ssw0rd!"
}
}
}

Reimage a VM using REST


You can reimage a Virtual Machine instance with ephemeral OS disk using REST API as described below and via
Azure Portal by going to Overview pane of the VM. For scale sets, reimaging is already available through
Powershell, CLI, and the portal.

POST https://management.azure.com/subscriptions/{sub-
id}/resourceGroups/{rgName}/providers/Microsoft.Compute/VirtualMachines/{vmName}/reimage?a pi-version=2018-06-
01"

Frequently asked questions


Q: What is the size of the local OS Disks?
A: We support platform and custom images, up to the VM cache size, where all read/writes to the OS disk will be
local on the same node as the Virtual Machine.
Q: Can the ephemeral OS disk be resized?
A: No, once the ephemeral OS disk is provisioned, the OS disk cannot be resized.
Q: Can I attach a Managed Disks to an Ephemeral VM?
A: Yes, you can attach a managed data disk to a VM that uses an ephemeral OS disk.
Q: Will all VM sizes be supported for ephemeral OS disks?
A: No, all Premium Storage VM sizes are supported (DS, ES, FS, GS and M ) except the B -series, N -series, and H-
series sizes.
Q: Can the ephemeral OS disk be applied to existing VMs and scale sets?
A: No, ephemeral OS disk can only be used during VM and scale set creation.
Q: Can you mix ephemeral and normal OS disks in a scale set?
A: No, you can't have a mix of ephemeral and persistent OS disk instances within the same scale set.
Q: Can the ephemeral OS disk be created using Powershell or CLI?
A: Yes, you can create VMs with Ephemeral OS Disk using REST, Templates, PowerShell and CLI.
Q: What features are not supported with ephemeral OS disk?
A: Ephemeral disks do not support:
Capturing VM images
Disk snapshots
Azure Disk Encryption
Azure Backup
Azure Site Recovery
OS Disk Swap

Next steps
You can create a VM with an ephemeral OS disk using Azure PowerShell.
Virtual networks and virtual machines in Azure
11/13/2019 • 13 minutes to read • Edit Online

When you create an Azure virtual machine (VM ), you must create a virtual network (VNet) or use an existing VNet.
You also need to decide how your VMs are intended to be accessed on the VNet. It is important to plan before
creating resources and make sure that you understand the limits of networking resources.
In the following figure, VMs are represented as web servers and database servers. Each set of VMs are assigned to
separate subnets in the VNet.

You can create a VNet before you create a VM or you can as you create a VM. You create these resources to
support communication with a VM:
Network interfaces
IP addresses
Virtual network and subnets
In addition to those basic resources, you should also consider these optional resources:
Network security groups
Load balancers

Network interfaces
A network interface (NIC ) is the interconnection between a VM and a virtual network (VNet). A VM must have at
least one NIC, but can have more than one, depending on the size of the VM you create. Learn about how many
NICs each VM size supports for Windows or Linux.
You can create a VM with multiple NICs, and add or remove NICs through the lifecycle of a VM. Multiple NICs
allow a VM to connect to different subnets and send or receive traffic over the most appropriate interface. VMs
with any number of network interfaces can exist in the same availability set, up to the number supported by the
VM size.
Each NIC attached to a VM must exist in the same location and subscription as the VM. Each NIC must be
connected to a VNet that exists in the same Azure location and subscription as the NIC. You can change the subnet
a VM is connected to after it's created, but you cannot change the VNet. Each NIC attached to a VM is assigned a
MAC address that doesn’t change until the VM is deleted.
This table lists the methods that you can use to create a network interface.

METHOD DESCRIPTION

Azure portal When you create a VM in the Azure portal, a network


interface is automatically created for you (you cannot use a
NIC you create separately). The portal creates a VM with only
one NIC. If you want to create a VM with more than one NIC,
you must create it with a different method.

Azure PowerShell Use New-AzNetworkInterface with the -PublicIpAddressId


parameter to provide the identifier of the public IP address
that you previously created.

Azure CLI To provide the identifier of the public IP address that you
previously created, use az network nic create with the --
public-ip-address parameter.

Template Use Network Interface in a Virtual Network with Public IP


Address as a guide for deploying a network interface using a
template.

IP addresses
You can assign these types of IP addresses to a NIC in Azure:
Public IP addresses - Used to communicate inbound and outbound (without network address translation
(NAT)) with the Internet and other Azure resources not connected to a VNet. Assigning a public IP address to a
NIC is optional. Public IP addresses have a nominal charge, and there's a maximum number that can be used
per subscription.
Private IP addresses - Used for communication within a VNet, your on-premises network, and the Internet
(with NAT). You must assign at least one private IP address to a VM. To learn more about NAT in Azure, read
Understanding outbound connections in Azure.
You can assign public IP addresses to VMs or internet-facing load balancers. You can assign private IP addresses to
VMs and internal load balancers. You assign IP addresses to a VM using a network interface.
There are two methods in which an IP address is allocated to a resource - dynamic or static. The default allocation
method is dynamic, where an IP address is not allocated when it's created. Instead, the IP address is allocated when
you create a VM or start a stopped VM. The IP address is released when you stop or delete the VM.
To ensure the IP address for the VM remains the same, you can set the allocation method explicitly to static. In this
case, an IP address is assigned immediately. It is released only when you delete the VM or change its allocation
method to dynamic.
This table lists the methods that you can use to create an IP address.

METHOD DESCRIPTION

Azure portal By default, public IP addresses are dynamic and the address
associated to them may change when the VM is stopped or
deleted. To guarantee that the VM always uses the same
public IP address, create a static public IP address. By default,
the portal assigns a dynamic private IP address to a NIC when
creating a VM. You can change this IP address to static after
the VM is created.

Azure PowerShell You use New-AzPublicIpAddress with the -AllocationMethod


parameter as Dynamic or Static.

Azure CLI You use az network public-ip create with the --allocation-
method parameter as Dynamic or Static.

Template Use Network Interface in a Virtual Network with Public IP


Address as a guide for deploying a public IP address using a
template.

After you create a public IP address, you can associate it with a VM by assigning it to a NIC.

Virtual network and subnets


A subnet is a range of IP addresses in the VNet. You can divide a VNet into multiple subnets for organization and
security. Each NIC in a VM is connected to one subnet in one VNet. NICs connected to subnets (same or different)
within a VNet can communicate with each other without any extra configuration.
When you set up a VNet, you specify the topology, including the available address spaces and subnets. If the VNet
is to be connected to other VNets or on-premises networks, you must select address ranges that don't overlap. The
IP addresses are private and can't be accessed from the Internet, which was true only for the non-routable IP
addresses such as 10.0.0.0/8, 172.16.0.0/12, or 192.168.0.0/16. Now, Azure treats any address range as part of the
private VNet IP address space that is only reachable within the VNet, within interconnected VNets, and from your
on-premises location.
If you work within an organization in which someone else is responsible for the internal networks, you should talk
to that person before selecting your address space. Make sure there is no overlap and let them know the space you
want to use so they don’t try to use the same range of IP addresses.
By default, there is no security boundary between subnets, so VMs in each of these subnets can talk to one another.
However, you can set up Network Security Groups (NSGs), which allow you to control the traffic flow to and from
subnets and to and from VMs.
This table lists the methods that you can use to create a VNet and subnets.
METHOD DESCRIPTION

Azure portal If you let Azure create a VNet when you create a VM, the
name is a combination of the resource group name that
contains the VNet and -vnet. The address space is
10.0.0.0/24, the required subnet name is default, and the
subnet address range is 10.0.0.0/24.

Azure PowerShell You use New-AzVirtualNetworkSubnetConfig and New-


AzVirtualNetwork to create a subnet and a VNet. You can also
use Add-AzVirtualNetworkSubnetConfig to add a subnet to an
existing VNet.

Azure CLI The subnet and the VNet are created at the same time.
Provide a --subnet-name parameter to az network vnet
create with the subnet name.

Template The easiest way to create a VNet and subnets is to download


an existing template, such as Virtual Network with two
subnets, and modify it for your needs.

Network security groups


A network security group (NSG ) contains a list of Access Control List (ACL ) rules that allow or deny network traffic
to subnets, NICs, or both. NSGs can be associated with either subnets or individual NICs connected to a subnet.
When an NSG is associated with a subnet, the ACL rules apply to all the VMs in that subnet. In addition, traffic to
an individual NIC can be restricted by associating an NSG directly to a NIC.
NSGs contain two sets of rules: inbound and outbound. The priority for a rule must be unique within each set. Each
rule has properties of protocol, source and destination port ranges, address prefixes, direction of traffic, priority,
and access type.
All NSGs contain a set of default rules. The default rules cannot be deleted, but because they are assigned the
lowest priority, they can be overridden by the rules that you create.
When you associate an NSG to a NIC, the network access rules in the NSG are applied only to that NIC. If an NSG
is applied to a single NIC on a multi-NIC VM, it does not affect traffic to the other NICs. You can associate different
NSGs to a NIC (or VM, depending on the deployment model) and the subnet that a NIC or VM is bound to.
Priority is given based on the direction of traffic.
Be sure to plan your NSGs when you plan your VMs and VNet.
This table lists the methods that you can use to create a network security group.

METHOD DESCRIPTION

Azure portal When you create a VM in the Azure portal, an NSG is


automatically created and associated to the NIC the portal
creates. The name of the NSG is a combination of the name of
the VM and -nsg. This NSG contains one inbound rule with a
priority of 1000, service set to RDP, the protocol set to TCP,
port set to 3389, and action set to Allow. If you want to allow
any other inbound traffic to the VM, you must add additional
rules to the NSG.
METHOD DESCRIPTION

Azure PowerShell Use New-AzNetworkSecurityRuleConfig and provide the


required rule information. Use New-AzNetworkSecurityGroup
to create the NSG. Use Set-AzVirtualNetworkSubnetConfig to
configure the NSG for the subnet. Use Set-AzVirtualNetwork
to add the NSG to the VNet.

Azure CLI Use az network nsg create to initially create the NSG. Use az
network nsg rule create to add rules to the NSG. Use az
network vnet subnet update to add the NSG to the subnet.

Template Use Create a Network Security Group as a guide for deploying


a network security group using a template.

Load balancers
Azure Load Balancer delivers high availability and network performance to your applications. A load balancer can
be configured to balance incoming Internet traffic to VMs or balance traffic between VMs in a VNet. A load
balancer can also balance traffic between on-premises computers and VMs in a cross-premises network, or
forward external traffic to a specific VM.
The load balancer maps incoming and outgoing traffic between the public IP address and port on the load balancer
and the private IP address and port of the VM.
When you create a load balancer, you must also consider these configuration elements:
Front-end IP configuration – A load balancer can include one or more front-end IP addresses, otherwise
known as virtual IPs (VIPs). These IP addresses serve as ingress for the traffic.
Back-end address pool – IP addresses that are associated with the NIC to which load is distributed.
NAT rules - Defines how inbound traffic flows through the front-end IP and distributed to the back-end IP.
Load balancer rules - Maps a given front-end IP and port combination to a set of back-end IP addresses and
port combination. A single load balancer can have multiple load balancing rules. Each rule is a combination of a
front-end IP and port and back-end IP and port associated with VMs.
Probes - Monitors the health of VMs. When a probe fails to respond, the load balancer stops sending new
connections to the unhealthy VM. The existing connections are not affected, and new connections are sent to
healthy VMs.
This table lists the methods that you can use to create an internet-facing load balancer.

METHOD DESCRIPTION

Azure portal You can load balance internet traffic to VMs using the Azure
portal.

Azure PowerShell To provide the identifier of the public IP address that you
previously created, use New-AzLoadBalancerFrontendIpConfig
with the -PublicIpAddress parameter. Use New-
AzLoadBalancerBackendAddressPoolConfig to create the
configuration of the back-end address pool. Use New-
AzLoadBalancerInboundNatRuleConfig to create inbound NAT
rules associated with the front-end IP configuration that you
created. Use New-AzLoadBalancerProbeConfig to create the
probes that you need. Use New-AzLoadBalancerRuleConfig to
create the load balancer configuration. Use New-
AzLoadBalancer to create the load balancer.
METHOD DESCRIPTION

Azure CLI Use az network lb create to create the initial load balancer
configuration. Use az network lb frontend-ip create to add the
public IP address that you previously created. Use az network
lb address-pool create to add the configuration of the back-
end address pool. Use az network lb inbound-nat-rule create
to add NAT rules. Use az network lb rule create to add the
load balancer rules. Use az network lb probe create to add the
probes.

Template Use 2 VMs in a Load Balancer and configure NAT rules on the
LB as a guide for deploying a load balancer using a template.

This table lists the methods that you can use to create an internal load balancer.

METHOD DESCRIPTION

Azure portal You can balance internal traffic load with a Basic load balancer
in the Azure portal.

Azure PowerShell To provide a private IP address in the network subnet, use


New-AzLoadBalancerFrontendIpConfig with the -
PrivateIpAddress parameter. Use New-
AzLoadBalancerBackendAddressPoolConfig to create the
configuration of the back-end address pool. Use New-
AzLoadBalancerInboundNatRuleConfig to create inbound NAT
rules associated with the front-end IP configuration that you
created. Use New-AzLoadBalancerProbeConfig to create the
probes that you need. Use New-AzLoadBalancerRuleConfig to
create the load balancer configuration. Use New-
AzLoadBalancer to create the load balancer.

Azure CLI Use the az network lb create command to create the initial
load balancer configuration. To define the private IP address,
use az network lb frontend-ip create with the --private-ip-
address parameter. Use az network lb address-pool create to
add the configuration of the back-end address pool. Use az
network lb inbound-nat-rule create to add NAT rules. Use az
network lb rule create to add the load balancer rules. Use az
network lb probe create to add the probes.

Template Use 2 VMs in a Load Balancer and configure NAT rules on the
LB as a guide for deploying a load balancer using a template.

VMs
VMs can be created in the same VNet and they can connect to each other using private IP addresses. They can
connect even if they are in different subnets without the need to configure a gateway or use public IP addresses. To
put VMs into a VNet, you create the VNet and then as you create each VM, you assign it to the VNet and subnet.
VMs acquire their network settings during deployment or startup.
VMs are assigned an IP address when they are deployed. If you deploy multiple VMs into a VNet or subnet, they
are assigned IP addresses as they boot up. You can also allocate a static IP to a VM. If you allocate a static IP, you
should consider using a specific subnet to avoid accidentally reusing a static IP for another VM.
If you create a VM and later want to migrate it into a VNet, it is not a simple configuration change. You must
redeploy the VM into the VNet. The easiest way to redeploy is to delete the VM, but not any disks attached to it,
and then re-create the VM using the original disks in the VNet.
This table lists the methods that you can use to create a VM in a VNet.

METHOD DESCRIPTION

Azure portal Uses the default network settings that were previously
mentioned to create a VM with a single NIC. To create a VM
with multiple NICs, you must use a different method.

Azure PowerShell Includes the use of Add-AzVMNetworkInterface to add the


NIC that you previously created to the VM configuration.

Azure CLI Create and connect a VM to a Vnet, subnet, and NIC that
build as individual steps.

Template Use Very simple deployment of a Windows VM as a guide for


deploying a VM using a template.

Next steps
For VM -specific steps on how to manage Azure virtual networks for VMs, see the Windows or Linux tutorials.
There are also tutorials on how to load balance VMs and create highly available applications for Windows or Linux.
Learn how to configure user-defined routes and IP forwarding.
Learn how to configure VNet to VNet connections.
Learn how to Troubleshoot routes.
Learn more about Virtual machine network bandwidth.
What are virtual machine scale sets?
1/19/2020 • 4 minutes to read • Edit Online

Azure virtual machine scale sets let you create and manage a group of identical, load balanced VMs. The number of
VM instances can automatically increase or decrease in response to demand or a defined schedule. Scale sets
provide high availability to your applications, and allow you to centrally manage, configure, and update a large
number of VMs. With virtual machine scale sets, you can build large-scale services for areas such as compute, big
data, and container workloads.

Why use virtual machine scale sets?


To provide redundancy and improved performance, applications are typically distributed across multiple instances.
Customers may access your application through a load balancer that distributes requests to one of the application
instances. If you need to perform maintenance or update an application instance, your customers must be
distributed to another available application instance. To keep up with additional customer demand, you may need
to increase the number of application instances that run your application.
Azure virtual machine scale sets provide the management capabilities for applications that run across many VMs,
automatic scaling of resources, and load balancing of traffic. Scale sets provide the following key benefits:
Easy to create and manage multiple VMs
When you have many VMs that run your application, it's important to maintain a consistent
configuration across your environment. For reliable performance of your application, the VM size, disk
configuration, and application installs should match across all VMs.
With scale sets, all VM instances are created from the same base OS image and configuration. This
approach lets you easily manage hundreds of VMs without additional configuration tasks or network
management.
Scale sets support the use of the Azure load balancer for basic layer-4 traffic distribution, and Azure
Application Gateway for more advanced layer-7 traffic distribution and SSL termination.
Provides high availability and application resiliency
Scale sets are used to run multiple instances of your application. If one of these VM instances has a
problem, customers continue to access your application through one of the other VM instances with
minimal interruption.
For additional availability, you can use Availability Zones to automatically distribute VM instances in a
scale set within a single datacenter or across multiple datacenters.
Allows your application to automatically scale as resource demand changes
Customer demand for your application may change throughout the day or week. To match customer
demand, scale sets can automatically increase the number of VM instances as application demand
increases, then reduce the number of VM instances as demand decreases.
Autoscale also minimizes the number of unnecessary VM instances that run your application when
demand is low, while customers continue to receive an acceptable level of performance as demand grows
and additional VM instances are automatically added. This ability helps reduce costs and efficiently create
Azure resources as required.
Works at large-scale
Scale sets support up to 1,000 VM instances. If you create and upload your own custom VM images, the
limit is 600 VM instances.
For the best performance with production workloads, use Azure Managed Disks.

Differences between virtual machines and scale sets


Scale sets are built from virtual machines. With scale sets, the management and automation layers are provided to
run and scale your applications. You could instead manually create and manage individual VMs, or integrate
existing tools to build a similar level of automation. The following table outlines the benefits of scale sets compared
to manually managing multiple VM instances.

SCENARIO MANUAL GROUP OF VMS VIRTUAL MACHINE SCALE SET

Add additional VM instances Manual process to create, configure, Automatically create from central
and ensure compliance configuration

Traffic balancing and distribution Manual process to create and configure Can automatically create and integrate
Azure load balancer or Application with Azure load balancer or Application
Gateway Gateway

High availability and redundancy Manually create Availability Set or Automatic distribution of VM instances
distribute and track VMs across across Availability Zones or Availability
Availability Zones Sets

Scaling of VMs Manual monitoring and Azure Autoscale based on host metrics, in-
Automation guest metrics, Application Insights, or
schedule

There is no additional cost to scale sets. You only pay for the underlying compute resources such as the VM
instances, load balancer, or Managed Disk storage. The management and automation features, such as autoscale
and redundancy, incur no additional charges over the use of VMs.

How to monitor your scale sets


Use Azure Monitor for VMs, which has a simple onboarding process and will automate the collection of important
CPU, memory, disk, and network performance counters from the VMs in your scale set. It also includes additional
monitoring capabilities and pre-defined visualizations that help you focus on the availability and performance of
your scale sets.
Enable monitoring for your virtual machine scale set application with Application Insights to collect detailed
information about your application including page views, application requests, and exceptions. Further verify the
availability of your application by configuring an availability test to simulate user traffic.

Next steps
To get started, create your first virtual machine scale set in the Azure portal.
Create a scale set in the Azure portal
Use infrastructure automation tools with virtual
machines in Azure
11/13/2019 • 6 minutes to read • Edit Online

To create and manage Azure virtual machines (VMs) in a consistent manner at scale, some form of automation is
typically desired. There are many tools and solutions that allow you to automate the complete Azure infrastructure
deployment and management lifecycle. This article introduces some of the infrastructure automation tools that you
can use in Azure. These tools commonly fit in to one of the following approaches:
Automate the configuration of VMs
Tools include Ansible, Chef, and Puppet.
Tools specific to VM customization include cloud-init for Linux VMs, PowerShell Desired State
Configuration (DSC ), and the Azure Custom Script Extension for all Azure VMs.
Automate infrastructure management
Tools include Packer to automate custom VM image builds, and Terraform to automate the infrastructure
build process.
Azure Automation can perform actions across your Azure and on-premises infrastructure.
Automate application deployment and delivery
Examples include Azure DevOps Services and Jenkins.

Ansible
Ansible is an automation engine for configuration management, VM creation, or application deployment. Ansible
uses an agent-less model, typically with SSH keys, to authenticate and manage target machines. Configuration
tasks are defined in playbooks, with a number of Ansible modules available to carry out specific tasks. For more
information, see How Ansible works.
Learn how to:
Install and configure Ansible on Linux for use with Azure.
Create a Linux virtual machine.
Manage a Linux virtual machine.

Chef
Chef is an automation platform that helps define how your infrastructure is configured, deployed, and managed.
Additional components included Chef Habitat for application lifecycle automation rather than the infrastructure,
and Chef InSpec that helps automate compliance with security and policy requirements. Chef Clients are installed
on target machines, with one or more central Chef Servers that store and manage the configurations. For more
information, see An Overview of Chef.
Learn how to:
Deploy Chef Automate from the Azure Marketplace.
Install Chef on Windows and create Azure VMs.

Puppet
Puppet is an enterprise-ready automation platform that handles the application delivery and deployment process.
Agents are installed on target machines to allow Puppet Master to run manifests that define the desired
configuration of the Azure infrastructure and VMs. Puppet can integrate with other solutions such as Jenkins and
GitHub for an improved devops workflow. For more information, see How Puppet works.
Learn how to:
Deploy Puppet from the Azure Marketplace.

Cloud-init
Cloud-init is a widely used approach to customize a Linux VM as it boots for the first time. You can use cloud-init to
install packages and write files, or to configure users and security. Because cloud-init is called during the initial boot
process, there are no additional steps or required agents to apply your configuration. For more information on how
to properly format your #cloud-config files, see the cloud-init documentation site. #cloud-config files are text files
encoded in base64.
Cloud-init also works across distributions. For example, you don't use apt-get install or yum install to install a
package. Instead you can define a list of packages to install. Cloud-init automatically uses the native package
management tool for the distro you select.
We are actively working with our endorsed Linux distro partners in order to have cloud-init enabled images
available in the Azure marketplace. These images make your cloud-init deployments and configurations work
seamlessly with VMs and virtual machine scale sets. Learn more details about cloud-init on Azure:
Cloud-init support for Linux virtual machines in Azure
Try a tutorial on automated VM configuration using cloud-init.

PowerShell DSC
PowerShell Desired State Configuration (DSC ) is a management platform to define the configuration of target
machines. DSC can also be used on Linux through the Open Management Infrastructure (OMI) server.
DSC configurations define what to install on a machine and how to configure the host. A Local Configuration
Manager (LCM ) engine runs on each target node that processes requested actions based on pushed configurations.
A pull server is a web service that runs on a central host to store the DSC configurations and associated resources.
The pull server communicates with the LCM engine on each target host to provide the required configurations and
report on compliance.
Learn how to:
Create a basic DSC configuration.
Configure a DSC pull server.
Use DSC for Linux.

Azure Custom Script Extension


The Azure Custom Script Extension for Linux or Windows downloads and executes scripts on Azure VMs. You can
use the extension when you create a VM, or any time after the VM is in use.
Scripts can be downloaded from Azure storage or any public location such as a GitHub repository. With the
Custom Script Extension, you can write scripts in any language that runs on the source VM. These scripts can be
used to install applications or configure the VM as desired. To secure credentials, sensitive information such as
passwords can be stored in a protected configuration. These credentials are only decrypted inside the VM.
Learn how to:
Create a Linux VM with the Azure CLI and use the Custom Script Extension.
Create a Windows VM with Azure PowerShell and use the Custom Script Extension.

Packer
Packer automates the build process when you create a custom VM image in Azure. You use Packer to define the
OS and run post-configuration scripts that customize the VM for your specific needs. Once configured, the VM is
then captured as a Managed Disk image. Packer automates the process to create the source VM, network and
storage resources, run configuration scripts, and then create the VM image.
Learn how to:
Use Packer to create a Linux VM image in Azure.
Use Packer to create a Windows VM image in Azure.

Terraform
Terraform is an automation tool that allows you to define and create an entire Azure infrastructure with a single
template format language - the HashiCorp Configuration Language (HCL ). With Terraform, you define templates
that automate the process to create network, storage, and VM resources for a given application solution. You can
use your existing Terraform templates for other platforms with Azure to ensure consistency and simplify the
infrastructure deployment without needing to convert to an Azure Resource Manager template.
Learn how to:
Install and configure Terraform with Azure.
Create an Azure infrastructure with Terraform.

Azure Automation
Azure Automation uses runbooks to process a set of tasks on the VMs you target. Azure Automation is used to
manage existing VMs rather than to create an infrastructure. Azure Automation can run across both Linux and
Windows VMs, as well as on-premises virtual or physical machines with a hybrid runbook worker. Runbooks can
be stored in a source control repository, such as GitHub. These runbooks can then run manually or on a defined
schedule.
Azure Automation also provides a Desired State Configuration (DSC ) service that allows you to create definitions
for how a given set of VMs should be configured. DSC then ensures that the required configuration is applied and
the VM stays consistent. Azure Automation DSC runs on both Windows and Linux machines.
Learn how to:
Create a PowerShell runbook.
Use Hybrid Runbook Worker to manage on-premises resources.
Use Azure Automation DSC.

Azure DevOps Services


Azure DevOps Services is a suite of tools that help you share and track code, use automated builds, and create a
complete continuous integration and development (CI/CD ) pipeline. Azure DevOps Services integrates with Visual
Studio and other editors to simplify usage. Azure DevOps Services can also create and configure Azure VMs and
then deploy code to them.
Learn more about:
Azure DevOps Services.
Jenkins
Jenkins is a continuous integration server that helps deploy and test applications, and create automated pipelines
for code delivery. There are hundreds of plugins to extend the core Jenkins platform, and you can also integrate
with many other products and solutions through webhooks. You can manually install Jenkins on an Azure VM, run
Jenkins from within a Docker container, or use a pre-built Azure Marketplace image.
Learn how to:
Create a development infrastructure on a Linux VM in Azure with Jenkins, GitHub, and Docker.

Next steps
There are many different options to use infrastructure automation tools in Azure. You have the freedom to use the
solution that best fits your needs and environment. To get started and try some of the tools built-in to Azure, see
how to automate the customization of a Linux or Windows VM.
Secure and use policies on virtual machines in Azure
11/13/2019 • 4 minutes to read • Edit Online

It’s important to keep your virtual machine (VM ) secure for the applications that you run. Securing your VMs can
include one or more Azure services and features that cover secure access to your VMs and secure storage of your
data. This article provides information that enables you to keep your VM and applications secure.

Antimalware
The modern threat landscape for cloud environments is dynamic, increasing the pressure to maintain effective
protection in order to meet compliance and security requirements. Microsoft Antimalware for Azure is a free real-
time protection capability that helps identify and remove viruses, spyware, and other malicious software. Alerts can
be configured to notify you when known malicious or unwanted software attempts to install itself or run on your
VM. It is not supported on VMs running Linux or Windows Server 2008.

Azure Security Center


Azure Security Center helps you prevent, detect, and respond to threats to your VMs. Security Center provides
integrated security monitoring and policy management across your Azure subscriptions, helps detect threats that
might otherwise go unnoticed, and works with a broad ecosystem of security solutions.
Security Center’s just-in-time access can be applied across your VM deployment to lock down inbound traffic to
your Azure VMs, reducing exposure to attacks while providing easy access to connect to VMs when needed. When
just-in-time is enabled and a user requests access to a VM, Security Center checks what permissions the user has
for the VM. If they have the correct permissions, the request is approved and Security Center automatically
configures the Network Security Groups (NSGs) to allow inbound traffic to the selected ports for a limited amount
of time. After the time has expired, Security Center restores the NSGs to their previous states.

Encryption
For enhanced Windows VM and Linux VM security and compliance, virtual disks in Azure can be encrypted.
Virtual disks on Windows VMs are encrypted at rest using BitLocker. Virtual disks on Linux VMs are encrypted at
rest using dm-crypt.
There is no charge for encrypting virtual disks in Azure. Cryptographic keys are stored in Azure Key Vault using
software-protection, or you can import or generate your keys in Hardware Security Modules (HSMs) certified to
FIPS 140-2 level 2 standards. These cryptographic keys are used to encrypt and decrypt virtual disks attached to
your VM. You retain control of these cryptographic keys and can audit their use. An Azure Active Directory service
principal provides a secure mechanism for issuing these cryptographic keys as VMs are powered on and off.

Key Vault and SSH Keys


Secrets and certificates can be modeled as resources and provided by Key Vault. You can use Azure PowerShell to
create key vaults for Windows VMs and the Azure CLI for Linux VMs. You can also create keys for encryption.
Key vault access policies grant permissions to keys, secrets, and certificates separately. For example, you can give a
user access to only keys, but no permissions for secrets. However, permissions to access keys or secrets or
certificates are at the vault level. In other words, key vault access policy does not support object level permissions.
When you connect to VMs, you should use public-key cryptography to provide a more secure way to sign in to
them. This process involves a public and private key exchange using the secure shell (SSH) command to
authenticate yourself rather than a username and password. Passwords are vulnerable to brute-force attacks,
especially on Internet-facing VMs such as web servers. With a secure shell (SSH) key pair, you can create a Linux
VM that uses SSH keys for authentication, eliminating the need for passwords to sign-in. You can also use SSH
keys to connect from a Windows VM to a Linux VM.

Managed identities for Azure resources


A common challenge when building cloud applications is how to manage the credentials in your code for
authenticating to cloud services. Keeping the credentials secure is an important task. Ideally, the credentials never
appear on developer workstations and aren't checked into source control. Azure Key Vault provides a way to
securely store credentials, secrets, and other keys, but your code has to authenticate to Key Vault to retrieve them.
The managed identities for Azure resources feature in Azure Active Directory (Azure AD ) solves this problem. The
feature provides Azure services with an automatically managed identity in Azure AD. You can use the identity to
authenticate to any service that supports Azure AD authentication, including Key Vault, without any credentials in
your code. Your code that's running on a VM can request a token from two endpoints that are accessible only from
within the VM. For more detailed information about this service, review the managed identities for Azure resources
overview page.

Policies
Azure policies can be used to define the desired behavior for your organization's Windows VMs and Linux VMs. By
using policies, an organization can enforce various conventions and rules throughout the enterprise. Enforcement
of the desired behavior can help mitigate risk while contributing to the success of the organization.

Role-based access control


Using role-based access control (RBAC ), you can segregate duties within your team and grant only the amount of
access to users on your VM that they need to perform their jobs. Instead of giving everybody unrestricted
permissions on the VM, you can allow only certain actions. You can configure access control for the VM in the
Azure portal, using the Azure CLI, orAzure PowerShell.

Next steps
Walk through the steps to monitor virtual machine security by using Azure Security Center for Linux or
Windows.
Azure Disk Encryption for Windows VMs
10/16/2019 • 4 minutes to read • Edit Online

Azure Disk Encryption helps protect and safeguard your data to meet your organizational security and
compliance commitments. It uses the Bitlocker feature of Windows to provide volume encryption for the OS and
data disks of Azure virtual machines (VMs), and is integrated with Azure Key Vault to help you control and
manage the disk encryption keys and secrets.
If you use Azure Security Center, you're alerted if you have VMs that aren't encrypted. The alerts show as High
Severity and the recommendation is to encrypt these VMs.

WARNING
If you have previously used Azure Disk Encryption with Azure AD to encrypt a VM, you must continue use this option
to encrypt your VM. See Azure Disk Encryption with Azure AD (previous release) for details.
Certain recommendations might increase data, network, or compute resource usage, resulting in additional license or
subscription costs. You must have a valid active Azure subscription to create resources in Azure in the supported
regions.

You can learn the fundamentals of Azure Disk Encryption for Windows in just a few minutes with the Create and
encrypt a Windows VM with Azure CLI quickstart or the Create and encrypt a Windows VM with Azure
Powershell quickstart.

Supported VMs and operating systems


Supported VM sizes
Windows VMs are available in a range of sizes. Azure Disk Encryption is not available on Basic, A-series VMs, or
on virtual machines with a less than 2 GB of memory.
Azure Disk Encryption is also available for VMs with premium storage.
Supported operating systems
Windows client: Windows 8 and later.
Windows Server: Windows Server 2008 R2 and later.
NOTE
Windows Server 2008 R2 requires the .NET Framework 4.5 to be installed for encryption; install it from Windows Update
with the optional update Microsoft .NET Framework 4.5.2 for Windows Server 2008 R2 x64-based systems (KB2901983).
Windows Server 2012 R2 Core and Windows Server 2016 Core requires the bdehdcfg component to be installed on the
VM for encryption.

Networking requirements
To enable Azure Disk Encryption, the VMs must meet the following network endpoint configuration
requirements:
To get a token to connect to your key vault, the Windows VM must be able to connect to an Azure Active
Directory endpoint, [login.microsoftonline.com].
To write the encryption keys to your key vault, the Windows VM must be able to connect to the key vault
endpoint.
The Windows VM must be able to connect to an Azure storage endpoint that hosts the Azure extension
repository and an Azure storage account that hosts the VHD files.
If your security policy limits access from Azure VMs to the Internet, you can resolve the preceding URI and
configure a specific rule to allow outbound connectivity to the IPs. For more information, see Azure Key Vault
behind a firewall.

Group Policy requirements


Azure Disk Encryption uses the BitLocker external key protector for Windows VMs. For domain joined VMs,
don't push any group policies that enforce TPM protectors. For information about the group policy for “Allow
BitLocker without a compatible TPM,” see BitLocker Group Policy Reference.
BitLocker policy on domain joined virtual machines with custom group policy must include the following setting:
Configure user storage of BitLocker recovery information -> Allow 256-bit recovery key . Azure Disk Encryption
will fail when custom group policy settings for BitLocker are incompatible. On machines that didn't have the
correct policy setting, apply the new policy, force the new policy to update (gpupdate.exe /force), and then
restarting may be required.
Azure Disk Encryption will fail if domain level group policy blocks the AES -CBC algorithm, which is used by
BitLocker.

Encryption key storage requirements


Azure Disk Encryption requires an Azure Key Vault to control and manage disk encryption keys and secrets. Your
key vault and VMs must reside in the same Azure region and subscription.
For details, see Creating and configuring a key vault for Azure Disk Encryption.

Terminology
The following table defines some of the common terms used in Azure disk encryption documentation:

TERMINOLOGY DEFINITION
TERMINOLOGY DEFINITION

Azure Key Vault Key Vault is a cryptographic, key management service that's
based on Federal Information Processing Standards (FIPS)
validated hardware security modules. These standards help to
safeguard your cryptographic keys and sensitive secrets. For
more information, see the Azure Key Vault documentation
and Creating and configuring a key vault for Azure Disk
Encryption.

Azure CLI The Azure CLI is optimized for managing and administering
Azure resources from the command line.

BitLocker BitLocker is an industry-recognized Windows volume


encryption technology that's used to enable disk encryption
on Windows VMs.

Key encryption key (KEK) The asymmetric key (RSA 2048) that you can use to protect
or wrap the secret. You can provide a hardware security
module (HSM)-protected key or software-protected key. For
more information, see the Azure Key Vault documentation
and Creating and configuring a key vault for Azure Disk
Encryption.

PowerShell cmdlets For more information, see Azure PowerShell cmdlets.

Next steps
Quickstart - Create and encrypt a Windows VM with Azure CLI
Quickstart - Create and encrypt a Windows VM with Azure Powershell
Azure Disk Encryption scenarios on Windows VMs
Azure Disk Encryption prerequisites CLI script
Azure Disk Encryption prerequisites PowerShell script
Creating and configuring a key vault for Azure Disk Encryption
Security controls for Windows Virtual Machines
2/12/2020 • 2 minutes to read • Edit Online

This article documents the security controls built into Windows Virtual Machines.
A security control is a quality or feature of an Azure service that contributes to the service's ability to prevent,
detect, and respond to security vulnerabilities.
For each control, we use "Yes" or "No" to indicate whether it is currently in place for the service, "N/A" for a control
that is not applicable to the service. We might also provide a note or links to more information about an attribute.

Network
SECURITY CONTROL YES/NO NOTES

Service endpoint support Yes

VNet injection support Yes

Network Isolation and Firewalling Yes


support

Forced tunneling support Yes See Configure forced tunneling using


the Azure Resource Manager
deployment model.

Monitoring & logging


SECURITY CONTROL YES/NO NOTES

Azure monitoring support (Log Yes Monitor and update a Windows virtual
analytics, App insights, etc.) machine in Azure.

Control and management plane logging Yes


and audit

Data plane logging and audit No

Identity
SECURITY CONTROL YES/NO NOTES

Authentication Yes

Authorization Yes

Data protection
SECURITY CONTROL YES/NO NOTES

Server-side encryption at rest: Yes See Encrypt virtual disks on a Windows


Microsoft-managed keys VM.

Encryption in transit (such as Yes Azure Virtual Machines supports


ExpressRoute encryption, in VNet ExpressRoute and VNet encryption. See
encryption, and VNet-VNet encryption ) In-transit encryption in VMs.

Server-side encryption at rest: Yes Customer-managed keys is a supported


customer-managed keys (BYOK) Azure encryption scenario; see Azure
encryption overview.

Column level encryption (Azure Data N/A


Services)

API calls encrypted Yes Via HTTPS and TLS.

Configuration management
SECURITY CONTROL YES/NO NOTES

Configuration management support Yes


(versioning of configuration, etc.)

Next steps
Learn more about the built-in security controls across Azure services.
Virtual machines lifecycle and states
11/13/2019 • 3 minutes to read • Edit Online

Azure Virtual Machines (VMs) go through different states that can be categorized into provisioning and power
states. The purpose of this article is to describe these states and specifically highlight when customers are billed for
instance usage.

Power states
The power state represents the last known state of the VM.

The following table provides a description of each instance state and indicates whether it is billed for instance usage or
not.
STATE DESCRIPTION INSTANCE USAGE BILLING

Starting VM is starting up. Not billed


"statuses": [
{
"code": "PowerState/starting",
"level": "Info",
"displayStatus": "VM starting"
}
]

Running Normal working state for a VM Billed


"statuses": [
{
"code": "PowerState/running",
"level": "Info",
"displayStatus": "VM running"
}
]
Stopping This is a transitional state. When Billed
completed, it will show as
**Stopped**.
"statuses": [
{
"code": "PowerState/stopping",
"level": "Info",
"displayStatus": "VM stopping"
}
]

Stopped The VM has been shut down from Billed*


within the guest OS or using the
PowerOff APIs.
Hardware is still allocated to the VM
and it remains on the host.
"statuses": [
{
"code": "PowerState/stopped",
"level": "Info",
"displayStatus": "VM stopped"
}
]

Deallocating Transitional state. When completed, Not billed*


the VM will show as
**Deallocated**.
"statuses": [
{
"code":
"PowerState/deallocating",
"level": "Info",
"displayStatus": "VM
deallocating"
}
]

Deallocated The VM has been stopped Not billed


successfully and removed from the
host.
"statuses": [
{
"code": "PowerState/deallocated",
"level": "Info",
"displayStatus": "VM deallocated"
}
]

*Some Azure resources, such as Disks and Networking, incur charges. Software licenses on the instance do not
incur charges.

Provisioning states
A provisioning state is the status of a user-initiated, control-plane operation on the VM. These states are separate
from the power state of a VM.
Create – VM creation.
Update – updates the model for an existing VM. Some non-model changes to VM such as Start/Restart
also fall under update.
Delete – VM deletion.
Deallocate – is where a VM is stopped and removed from the host. Deallocating a VM is considered an
update, so it will display provisioning states related to updating.
Here are the transitional operation states after the platform has accepted a user-initiated action:

States Description

Creating "statuses": [
{
"code": "ProvisioningState/creating",
"level": "Info",
"displayStatus": "Creating"
}

Updating "statuses": [
{
"code": "ProvisioningState/updating",
"level": "Info",
"displayStatus": "Updating"
}
]

Deleting "statuses": [
{
"code": "ProvisioningState/deleting",
"level": "Info",
"displayStatus": "Deleting"
}
]

OS provisioning states If a VM is created with an OS image and not with a specialized image, then following
substates can be observed:
1. OSProvisioningInprogress – The VM is running, and installation of guest OS is
in progress.
"statuses": [
{
"code": "ProvisioningState/creating/OSProvisioningInprogress",
"level": "Info",
"displayStatus": "OS Provisioning In progress"
}
]

2. OSProvisioningComplete – Short-lived state. The VM quickly transitions to


**Success** unless any extensions need to be installed. Installing extensions can take
time.
"statuses": [
{
"code": "ProvisioningState/creating/OSProvisioningComplete",
"level": "Info",
"displayStatus": "OS Provisioning Complete"
}
]

Note: OS Provisioning can transition to **Failed** if there is an OS failure or the OS


doesn't install in time. Customers will be billed for the deployed VM on the
infrastructure.

Once the operation is complete, the VM will transition into one of the following states:
Succeeded – the user-initiated actions have completed.
"statuses": [
{
"code": "ProvisioningState/succeeded",
"level": "Info",
"displayStatus": "Provisioning succeeded",
"time": "time"
}
]

Failed – represents a failed operation. Refer to the error codes to get more information and possible
solutions.

"statuses": [
{
"code": "ProvisioningState/failed/InternalOperationError",
"level": "Error",
"displayStatus": "Provisioning failed",
"message": "Operation abandoned due to internal error. Please try again later.",
"time": "time"
}
]

VM instance view
The instance view API provides VM running-state information. For more information, see the Virtual Machines -
Instance View API documentation.
Azure Resources explorer provides a simple UI for viewing the VM running state: Resource Explorer.
Provisioning states are visible on VM properties and instance view. Power states are available in instance view of
VM.

Next steps
To learn more about monitoring your VM, see How to monitor virtual machines in Azure.
How to monitor virtual machines in Azure
11/13/2019 • 5 minutes to read • Edit Online

With the significant growth of VMs hosted in Azure, it's important to identify performance and health issues that
impact applications and infrastructure services they support. Basic monitoring is delivered by default with Azure by
the metric types CPU usage, disk utilization, memory utilization, and network traffic collected by the host
hypervisor. Additional metric and log data can be collected using extensions to configure diagnostics on your VMs
from the guest operating system.
To detect and help diagnose performance and health issues with the guest operating system, .NET based or Java
web application components running inside the VM, Azure Monitor delivers centralized monitoring with
comprehensive features such as Azure Monitor for VMs and Application Insights.

Diagnostics and metrics


You can set up and monitor the collection of diagnostics data using metrics in the Azure portal, the Azure CLI,
Azure PowerShell, and programming Applications Programming Interfaces (APIs). For example, you can:
Observe basic metrics for the VM. On the Overview screen of the Azure portal, the basic metrics shown
include CPU usage, network usage, total of disk bytes, and disk operations per second.
Enable the collection of boot diagnostics and view it using the Azure portal. When bringing your
own image to Azure or even booting one of the platform images, there can be many reasons why a VM gets
into a non-bootable state. You can easily enable boot diagnostics when you create a VM by clicking Enabled
for Boot Diagnostics under the Monitoring section of the Settings screen.
As VMs boot, the boot diagnostic agent captures boot output and stores it in Azure storage. This data can be
used to troubleshoot VM boot issues. Boot diagnostics are not automatically enabled when you create a VM
from command-line tools. Before enabling boot diagnostics, a storage account needs to be created for
storing boot logs. If you enable boot diagnostics in the Azure portal, a storage account is automatically
created for you.
If you didn’t enable boot diagnostics when the VM was created, you can always enable it later by using
Azure CLI, Azure PowerShell, or an Azure Resource Manager template.
Enable the collection of guest OS diagnostics data. When you create a VM, you have the opportunity
on the settings screen to enable guest OS diagnostics. When you do enable the collection of diagnostics
data, the IaaSDiagnostics extension for Linux or the IaaSDiagnostics extension for Windows is added to the
VM, which enables you to collect additional disk, CPU, and memory data.
Using the collected diagnostics data, you can configure autoscaling for your VMs. You can also configure
Azure Monitor Logs to store the data and set up alerts to let you know when performance isn't right.

Alerts
You can create alerts based on specific performance metrics. Examples of the issues you can be alerted about
include when average CPU usage exceeds a certain threshold, or available free disk space drops below a certain
amount. Alerts can be configured in the Azure portal, using Azure Resource Manager templates, or Azure CLI.

Azure Service Health


Azure Service Health provides personalized guidance and support when issues in Azure services affect you, and
helps you prepare for upcoming planned maintenance. Azure Service Health alerts you and your teams using
targeted and flexible notifications.

Azure Resource Health


Azure Resource health helps you diagnose and get support when an Azure issue impacts your resources. It informs
you about the current and past health of your resources and helps you mitigate issues. Resource health provides
technical support when you need help with Azure service issues.

Azure Activity Log


The Azure Activity Log is a subscription log that provides insight into subscription-level events that have occurred
in Azure. The log includes a range of data, from Azure Resource Manager operational data to updates on Service
Health events. You can click Activity Log in the Azure portal to view the log for your VM.
Some of the things you can do with the activity log include:
Create an alert on an Activity Log event.
Stream it to an Event Hub for ingestion by a third-party service or custom analytics solution such as Power BI.
Analyze it in Power BI using the Power BI content pack.
Save it to a storage account for archival or manual inspection. You can specify the retention time (in days) using
the Log Profile.
You can also access activity log data by using Azure PowerShell, the Azure CLI, or Monitor REST APIs.
Azure Resource Logs are logs emitted by your VM that provide rich, frequent data about its operation. Resource
logs differ from the activity log by providing insight about operations that were performed within the VM.
Some of the things you can do with diagnostics logs include:
Save them to a storage account for auditing or manual inspection. You can specify the retention time (in days)
using Resource Diagnostic Settings.
Stream them to Event Hubs for ingestion by a third-party service or custom analytics solution such as Power BI.
Analyze them with Log Analytics.

Advanced monitoring
For visibility of the application or service supported by the Azure VM and virtual machine scale sets, identification
of issues with the guest OS or workload running in the VM to understand if it is impacting availability or
performance of the application, or is an issue with the application, enable both Azure Monitor for VMs and
Application Insights.
Azure Monitor for VMs monitors your Azure virtual machines (VM ) at scale by analyzing the performance and
health of your Windows and Linux VMs, including the different processes and interconnected dependencies on
other resources and external processes it discovers. It includes several trend performance charts to help during
investigation of problems and assess capacity of your VMs. The dependency map shows monitored and
unmonitored machines, failed and active network connections between processes and these machines, and shows
trend charts with standard network connection metrics. Combined with Application Insights, you monitor your
application and capture telemetry such as HTTP requests, exceptions, etc. so you can correlate issues between the
VMs and your application. Configure Azure Monitor alerts to alert you on important conditions detected from
monitoring data collected by Azure Monitor for VMs.

Next steps
Walk through the steps in Monitor a Windows Virtual Machine with Azure PowerShell or Monitor a Linux
Virtual Machine with the Azure CLI.
Learn more about the best practices around Monitoring and diagnostics.
Backup and restore options for virtual machines in
Azure
11/13/2019 • 2 minutes to read • Edit Online

You can protect your data by taking backups at regular intervals. There are several backup options available for
VMs, depending on your use-case.

Azure Backup
For backing up Azure VMs running production workloads, use Azure Backup. Azure Backup supports application-
consistent backups for both Windows and Linux VMs. Azure Backup creates recovery points that are stored in geo-
redundant recovery vaults. When you restore from a recovery point, you can restore the whole VM or just specific
files.
For a simple, hands-on introduction to Azure Backup for Azure VMs, see the "Back up Azure virtual machines"
tutorial for Linux or Windows.
For more information on how Azure Backup works, see Plan your VM backup infrastructure in Azure

Azure Site Recovery


Azure Site Recovery protects your VMs from a major disaster scenario, when a whole region experiences an
outage due to major natural disaster or widespread service interruption. You can configure Azure Site Recovery for
your VMs so that you can recover your application with a single click in matter of minutes. You can replicate to an
Azure region of your choice, it is not restricted to paired regions.
You can run disaster-recovery drills with on-demand test failovers, without affecting your production workloads or
ongoing replication. Create recovery plans to orchestrate failover and failback of the entire application running on
multiple VMs. The recovery plan feature is integrated with Azure automation runbooks.
You can get started by replicating your virtual machines.

Managed snapshots
In development and test environments, snapshots provide a quick and simple option for backing up VMs that use
Managed Disks. A managed snapshot is a read-only full copy of a managed disk. Snapshots exist independent of
the source disk and can be used to create new managed disks for rebuilding a VM. They are billed based on the
used portion of the disk. For example, if you create a snapshot of a managed disk with provisioned capacity of 64
GB and actual used data size of 10 GB, snapshot will be billed only for the used data size of 10 GB.
For more information on creating snapshots, see:
Create copy of VHD stored as a Managed Disk using Snapshots in Windows
Create copy of VHD stored as a Managed Disk using Snapshots in Linux

Next steps
You can try out Azure Backup by following the "Back up Windows virtual machines tutorial" for Linux or Windows.
Example Azure infrastructure walkthrough for
Windows VMs
11/13/2019 • 3 minutes to read • Edit Online

This article walks through building out an example application infrastructure. We detail designing an infrastructure
for a simple online store that brings together all the guidelines and decisions around naming conventions,
availability sets, virtual networks and load balancers, and actually deploying your virtual machines (VMs).

Example workload
Adventure Works Cycles wants to build an online store application in Azure that consists of:
Two IIS servers running the client front-end in a web tier
Two IIS servers processing data and orders in an application tier
Two Microsoft SQL Server instances with AlwaysOn availability groups (two SQL Servers and a majority node
witness) for storing product data and orders in a database tier
Two Active Directory domain controllers for customer accounts and suppliers in an authentication tier
All the servers are located in two subnets:
a front-end subnet for the web servers
a back-end subnet for the application servers, SQL cluster, and domain controllers

Incoming secure web traffic must be load-balanced among the web servers as customers browse the online store.
Order processing traffic in the form of HTTP requests from the web servers must be balanced among the
application servers. Additionally, the infrastructure must be designed for high availability.
The resulting design must incorporate:
An Azure subscription and account
A single resource group
Azure Managed Disks
A virtual network with two subnets
Availability sets for the VMs with a similar role
Virtual machines
All the above follow these naming conventions:
Adventure Works Cycles uses [IT workload]-[location]-[Azure resource] as a prefix
For this example, "azos" (Azure Online Store) is the IT workload name and "use" (East US 2) is the
location
Virtual networks use AZOS -USE -VN**[number]**
Availability sets use azos-use-as-[role]
Virtual machine names use azos-use-vm-[vmname]

Azure subscriptions and accounts


Adventure Works Cycles is using their Enterprise subscription, named Adventure Works Enterprise Subscription, to
provide billing for this IT workload.

Storage
Adventure Works Cycles determined that they should use Azure Managed Disks. When creating VMs, both
available storage tiers are used:
Standard storage for the web servers, application servers, and domain controllers and their data disks.
Premium storage for the SQL Server VMs and their data disks.

Virtual network and subnets


Because the virtual network does not need ongoing connectivity to the Adventure Work Cycles on-premises
network, they decided on a cloud-only virtual network.
They created a cloud-only virtual network with the following settings using the Azure portal:
Name: AZOS -USE -VN01
Location: East US 2
Virtual network address space: 10.0.0.0/8
First subnet:
Name: FrontEnd
Address space: 10.0.1.0/24
Second subnet:
Name: BackEnd
Address space: 10.0.2.0/24

Availability sets
To maintain high availability of all four tiers of their online store, Adventure Works Cycles decided on four
availability sets:
azos-use-as-web for the web servers
azos-use-as-app for the application servers
azos-use-as-sql for the SQL Servers
azos-use-as-dc for the domain controllers

Virtual machines
Adventure Works Cycles decided on the following names for their Azure VMs:
azos-use-vm -web01 for the first web server
azos-use-vm -web02 for the second web server
azos-use-vm -app01 for the first application server
azos-use-vm -app02 for the second application server
azos-use-vm -sql01 for the first SQL Server server in the cluster
azos-use-vm -sql02 for the second SQL Server server in the cluster
azos-use-vm -dc01 for the first domain controller
azos-use-vm -dc02 for the second domain controller
Here is the resulting configuration.

This configuration incorporates:


A cloud-only virtual network with two subnets (FrontEnd and BackEnd)
Azure Managed Disks with both Standard and Premium disks
Four availability sets, one for each tier of the online store
The virtual machines for the four tiers
An external load balanced set for HTTPS -based web traffic from the Internet to the web servers
An internal load balanced set for unencrypted web traffic from the web servers to the application servers
A single resource group
Deploy VMs to dedicated hosts using the Azure
PowerShell
2/12/2020 • 3 minutes to read • Edit Online

This article guides you through how to create an Azure dedicated host to host your virtual machines (VMs).
Make sure that you have installed Azure PowerShell version 2.8.0 or later, and you are signed in to an Azure
account in with Connect-AzAccount .

Limitations
Virtual machine scale sets are not currently supported on dedicated hosts.
The following VM series are supported: DSv3, ESv3, and Fsv2.

Create a host group


A host group is a resource that represents a collection of dedicated hosts. You create a host group in a region and
an availability zone, and add hosts to it. When planning for high availability, there are additional options. You can
use one or both of the following options with your dedicated hosts:
Span across multiple availability zones. In this case, you are required to have a host group in each of the zones
you wish to use.
Span across multiple fault domains which are mapped to physical racks.
In either case, you are need to provide the fault domain count for your host group. If you do not want to span fault
domains in your group, use a fault domain count of 1.
You can also decide to use both availability zones and fault domains. This example creates a host group in zone 1,
with 2 fault domains.

$rgName = "myDHResourceGroup"
$location = "East US"

New-AzResourceGroup -Location $location -Name $rgName


$hostGroup = New-AzHostGroup `
-Location $location `
-Name myHostGroup `
-PlatformFaultDomain 2 `
-ResourceGroupName $rgName `
-Zone 1

Create a host
Now let's create a dedicated host in the host group. In addition to a name for the host, you are required to provide
the SKU for the host. Host SKU captures the supported VM series as well as the hardware generation for your
dedicated host.
For more information about the host SKUs and pricing, see Azure Dedicated Host pricing.
If you set a fault domain count for your host group, you will be asked to specify the fault domain for your host. In
this example, we set the fault domain for the host to 1.
$dHost = New-AzHost `
-HostGroupName $hostGroup.Name `
-Location $location -Name myHost `
-ResourceGroupName $rgName `
-Sku DSv3-Type1 `
-AutoReplaceOnFailure 1 `
-PlatformFaultDomain 1

Create a VM
Create a virtual machine on the dedicated host.
If you specified an availability zone when creating your host group, you are required to use the same zone when
creating the virtual machine. For this example, because our host group is in zone 1, we need to create the VM in
zone 1.

$cred = Get-Credential
New-AzVM `
-Credential $cred `
-ResourceGroupName $rgName `
-Location $location `
-Name myVM `
-HostId $dhost.Id `
-Image Win2016Datacenter `
-Zone 1 `
-Size Standard_D4s_v3

WARNING
If you create a virtual machine on a host which does not have enough resources, the virtual machine will be created in a
FAILED state.

Check the status of the host


You can check the host health status and how many virtual machines you can still deploy to the host using
GetAzHost with the -InstanceView parameter.

Get-AzHost `
-ResourceGroupName $rgName `
-Name myHost `
-HostGroupName $hostGroup.Name `
-InstanceView

The output will look similar to this:


ResourceGroupName : myDHResourceGroup
PlatformFaultDomain : 1
AutoReplaceOnFailure : True
HostId : 12345678-1234-1234-abcd-abc123456789
ProvisioningTime : 7/28/2019 5:31:01 PM
ProvisioningState : Succeeded
InstanceView :
AssetId : abc45678-abcd-1234-abcd-123456789abc
AvailableCapacity :
AllocatableVMs[0] :
VmSize : Standard_D2s_v3
Count : 32
AllocatableVMs[1] :
VmSize : Standard_D4s_v3
Count : 16
AllocatableVMs[2] :
VmSize : Standard_D8s_v3
Count : 8
AllocatableVMs[3] :
VmSize : Standard_D16s_v3
Count : 4
AllocatableVMs[4] :
VmSize : Standard_D32-8s_v3
Count : 2
AllocatableVMs[5] :
VmSize : Standard_D32-16s_v3
Count : 2
AllocatableVMs[6] :
VmSize : Standard_D32s_v3
Count : 2
AllocatableVMs[7] :
VmSize : Standard_D64-16s_v3
Count : 1
AllocatableVMs[8] :
VmSize : Standard_D64-32s_v3
Count : 1
AllocatableVMs[9] :
VmSize : Standard_D64s_v3
Count : 1
Statuses[0] :
Code : ProvisioningState/succeeded
Level : Info
DisplayStatus : Provisioning succeeded
Time : 7/28/2019 5:31:01 PM
Statuses[1] :
Code : HealthState/available
Level : Info
DisplayStatus : Host available
Sku :
Name : DSv3-Type1
Id : /subscriptions/10101010-1010-1010-1010-101010101010/re
sourceGroups/myDHResourceGroup/providers/Microsoft.Compute/hostGroups/myHostGroup/hosts
/myHost
Name : myHost
Location : eastus
Tags : {}

Clean up
You are being charged for your dedicated hosts even when no virtual machines are deployed. You should delete
any hosts you are currently not using to save costs.
You can only delete a host when there are no any longer virtual machines using it. Delete the VMs using Remove-
AzVM.
Remove-AzVM -ResourceGroupName $rgName -Name myVM

After deleting the VMs, you can delete the host using Remove-AzHost.

Remove-AzHost -ResourceGroupName $rgName -Name myHost

Once you have deleted all of your hosts, you may delete the host group using Remove-AzHostGroup.

Remove-AzHost -ResourceGroupName $rgName -Name myHost

You can also delete the entire resource group in a single command using Remove-AzResourceGroup. This will
delete all resources created in the group, including all of the VMs, hosts and host groups.

Remove-AzResourceGroup -Name $rgName

Next steps
There is sample template, found here, that uses both zones and fault domains for maximum resiliency in a
region.
You can also deploy dedicated hosts using the Azure portal.
Deploy VMs to dedicated hosts using the portal
1/9/2020 • 3 minutes to read • Edit Online

This article guides you through how to create an Azure dedicated host to host your virtual machines (VMs).

Limitations
Virtual machine scale sets are not currently supported on dedicated hosts.
The initial release supports the following VM series: DSv3, ESv3, FSv2, LSv2, and MSv2.

Create a host group


A host group is a new resource that represents a collection of dedicated hosts. You create a host group in a region
and an availability zone, and add hosts to it. When planning for high availability, there are additional options. You
can use one or both of the following options with your dedicated hosts:
Span across multiple availability zones. In this case, you are required to have a host group in each of the zones
you wish to use.
Span across multiple fault domains which are mapped to physical racks.
In either case, you are need to provide the fault domain count for your host group. If you do not want to span fault
domains in your group, use a fault domain count of 1.
You can also decide to use both availability zones and fault domains.
In this example, we will create a host group using 1 availability zone and 2 fault domains.
1. Open the Azure portal.
2. Select Create a resource in the upper left corner.
3. Search for Host group and then select Host Groups from the results.

4. In the Host Groups page, select Create.


5. Select the subscription you would like to use, and then select Create new to create a new resource group.
6. Type myDedicatedHostsRG as the Name and then select OK.
7. For Host group name, type myHostGroup.
8. For Location, select East US.
9. For Availability Zone, select 1.
10. For Fault domain count, select 2.
11. Select Review + create and then wait for validation.

12. Once you see the Validation passed message, select Create to create the host group.
It should only take a few moments to create the host group.

Create a dedicated host


Now create a dedicated host in the host group. In addition to a name for the host, you are required to provide the
SKU for the host. Host SKU captures the supported VM series as well as the hardware generation for your
dedicated host.
For more information about the host SKUs and pricing, see Azure Dedicated Host pricing.
If you set a fault domain count for your host group, you will be asked to specify the fault domain for your host.
1. Select Create a resource in the upper left corner.
2. Search for Dedicated host and then select Dedicated hosts from the results.
3. In the Dedicated Hosts page, select Create.
4. Select the subscription you would like to use.
5. Select myDedicatedHostsRG as the Resource group.
6. In Instance details, type myHost for the Name and select East US for the location.
7. In Hardware profile, select Standard Es3 family - Type 1 for the Size family, select myHostGrup for the
Host group and then select 1 for the Fault domain. Leave the defaults for the rest of the fields.
8. When you are done, select Review + create and wait for validation.

9. Once you see the Validation passed message, select Create to create the host.

Create a VM
1. Choose Create a resource in the upper left-hand corner of the Azure portal.
2. In the New page, under Popular, select Windows Server 2016 Datacenter.
3. In the Basics tab, under Project details, make sure the correct subscription is selected and then select
myDedicatedHostsRG as the Resource group.
4. Under Instance details, type myVM for the Virtual machine name and choose East US for your Location.
5. In Availability options select Availability zone, select 1 from the drop-down.
6. For the size, select Change size. In the list of available sizes, choose one from the Esv3 series, like Standard
E2s v3. You may need to clear the filter in order to see all of the available sizes.
7. Under Administrator account, provide a username, such as azureuser and a password. The password must
be at least 12 characters long and meet the defined complexity requirements.
8. Under Inbound port rules, choose Allow selected ports and then select RDP (3389) from the drop-down.
9. At the top of the page, select the Advanced tab and in the Host section, select myHostGroup for Host group
and myHost for the Host.

10. Leave the remaining defaults and then select the Review + create button at the bottom of the page.
11. When you see the message that validation has passed, select Create.

Next steps
For more information, see the Dedicated hosts overview.
There is sample template, found here, that uses both zones and fault domains for maximum resiliency in a
region.
You can also deploy a dedicated host using Azure PowerShell.
Preview: Deploy Spot VMs using the Azure portal
2/12/2020 • 2 minutes to read • Edit Online

Using Spot VMs allows you to take advantage of our unused capacity at a significant cost savings. At any point in
time when Azure needs the capacity back, the Azure infrastructure will evict Spot VMs. Therefore, Spot VMs are
great for workloads that can handle interruptions like batch processing jobs, dev/test environments, large compute
workloads, and more.
Pricing for Spot VMs is variable, based on region and SKU. For more information, see VM pricing for Linux and
Windows. For more information about setting the max price, see Spot VMs - Pricing.
You have option to set a max price you are willing to pay, per hour, for the VM. The max price for a Spot VM can be
set in US dollars (USD ), using up to 5 decimal places. For example, the value 0.05701 would be a max price of
$0.05701 USD per hour. If you set the max price to be -1 , the VM won't be evicted based on price. The price for
the VM will be the current price for spot or the price for a standard VM, which ever is less, as long as there is
capacity and quota available.

IMPORTANT
Spot instances are currently in public preview. This preview version is not recommended for production workloads. Certain
features might not be supported or might have constrained capabilities. For more information, see Supplemental Terms of
Use for Microsoft Azure Previews.

Create the VM
The process to create a VM that uses Spot VMs is the same as detailed in the quickstart. When you are deploying a
VM, you can choose to use an Azure spot instance.
On the Basics tab, in the Instance details section, No is the default for using an Azure spot instance.

It you select Yes, the section expands and you can choose your eviction type and eviction policy.
Next steps
You can also create Spot VMs using PowerShell.
Preview: Deploy Spot VMs using Azure PowerShell
2/12/2020 • 2 minutes to read • Edit Online

Using Spot VMs allows you to take advantage of our unused capacity at a significant cost savings. At any point in
time when Azure needs the capacity back, the Azure infrastructure will evict Spot VMs. Therefore, Spot VMs are
great for workloads that can handle interruptions like batch processing jobs, dev/test environments, large compute
workloads, and more.
Pricing for Spot VMs is variable, based on region and SKU. For more information, see VM pricing for Linux and
Windows. For more information about setting the max price, see Spot VMs - Pricing.
You have option to set a max price you are willing to pay, per hour, for the VM. The max price for a Spot VM can be
set in US dollars (USD ), using up to 5 decimal places. For example, the value 0.98765 would be a max price of
$0.98765 USD per hour. If you set the max price to be -1 , the VM won't be evicted based on price. The price for
the VM will be the current price for spot or the price for a standard VM, which ever is less, as long as there is
capacity and quota available.

IMPORTANT
Spot instances are currently in public preview. This preview version is not recommended for production workloads. Certain
features might not be supported or might have constrained capabilities. For more information, see Supplemental Terms of
Use for Microsoft Azure Previews.

Create the VM
Create a spotVM using New -AzVmConfig to create the configuration. Include -Priority Spot and set -MaxPrice
to either:
-1 so the VM is not evicted based on price.
a dollar amount, up to 5 digits. For example, -MaxPrice .98765 means that the VM will be deallocated once the
price for a spotVM goes about $.98765 per hour.
This example creates a spotVM that will not be deallocated based on pricing (only when Azure needs the capacity
back).
$resourceGroup = "mySpotRG"
$location = "eastus"
$vmName = "mySpotVM"
$cred = Get-Credential -Message "Enter a username and password for the virtual machine."
New-AzResourceGroup -Name $resourceGroup -Location $location
$subnetConfig = New-AzVirtualNetworkSubnetConfig `
-Name mySubnet -AddressPrefix 192.168.1.0/24
$vnet = New-AzVirtualNetwork -ResourceGroupName $resourceGroup `
-Location $location -Name MYvNET -AddressPrefix 192.168.0.0/16 `
-Subnet $subnetConfig
$pip = New-AzPublicIpAddress -ResourceGroupName $resourceGroup -Location $location `
-Name "mypublicdns$(Get-Random)" -AllocationMethod Static -IdleTimeoutInMinutes 4
$nsgRuleRDP = New-AzNetworkSecurityRuleConfig -Name myNetworkSecurityGroupRuleRDP -Protocol Tcp `
-Direction Inbound -Priority 1000 -SourceAddressPrefix * -SourcePortRange * -DestinationAddressPrefix * `
-DestinationPortRange 3389 -Access Allow
$nsg = New-AzNetworkSecurityGroup -ResourceGroupName $resourceGroup -Location $location `
-Name myNetworkSecurityGroup -SecurityRules $nsgRuleRDP
$nic = New-AzNetworkInterface -Name myNic -ResourceGroupName $resourceGroup -Location $location `
-SubnetId $vnet.Subnets[0].Id -PublicIpAddressId $pip.Id -NetworkSecurityGroupId $nsg.Id

# Create a virtual machine configuration and set this to be a Spot VM

$vmConfig = New-AzVMConfig -VMName $vmName -VMSize Standard_D1 -Priority "Spot" -MaxPrice -1| `
Set-AzVMOperatingSystem -Windows -ComputerName $vmName -Credential $cred | `
Set-AzVMSourceImage -PublisherName MicrosoftWindowsServer -Offer WindowsServer -Skus 2016-Datacenter -Version
latest | `
Add-AzVMNetworkInterface -Id $nic.Id

New-AzVM -ResourceGroupName $resourceGroup -Location $location -VM $vmConfig

After the VM is created, you can query to see the max price for all of the VMs in the resource group.

Get-AzVM -ResourceGroupName $resourceGroup | `


Select-Object Name,@{Name="maxPrice"; Expression={$_.BillingProfile.MaxPrice}}

Next steps
You can also create a Spot VM using the Azure CLI or a template.
If you encounter an error, see Error codes.
Deploy Spot VMs using a Resource Manager
template
2/12/2020 • 2 minutes to read • Edit Online

Using Spot VMs allows you to take advantage of our unused capacity at a significant cost savings. At any point in
time when Azure needs the capacity back, the Azure infrastructure will evict Spot VMs. Therefore, Spot VMs are
great for workloads that can handle interruptions like batch processing jobs, dev/test environments, large compute
workloads, and more.
Pricing for Spot VMs is variable, based on region and SKU. For more information, see VM pricing for Linux and
Windows.
You have option to set a max price you are willing to pay, per hour, for the VM. The max price for a Spot VM can be
set in US dollars (USD ), using up to 5 decimal places. For example, the value 0.98765 would be a max price of
$0.98765 USD per hour. If you set the max price to be -1 , the VM won't be evicted based on price. The price for
the VM will be the current price for Spot or the price for a standard VM, which ever is less, as long as there is
capacity and quota available. For more information about setting the max price, see Spot VMs - Pricing.

IMPORTANT
Spot instances are currently in public preview. This preview version is not recommended for production workloads. Certain
features might not be supported or might have constrained capabilities. For more information, see Supplemental Terms of
Use for Microsoft Azure Previews.

Use a template
For Spot template deployments, use "apiVersion": "2019-03-01" or later. Add the priority , evictionPolicy and
billingProfile properties to in your template:

"priority": "Spot",
"evictionPolicy": "Deallocate",
"billingProfile": {
"maxPrice": -1
}

Here is a sample template with the added properties for a Spot VM. Replace the resource names with your own
and <password> with a password for the local administrator account on the VM.

{
"$schema": "http://schema.management.azure.com/schemas/2019-03-01/deploymentTemplate.json#",
"contentVersion": "1.0.0.0",
"parameters": {
},
"variables": {
"vnetId": "/subscriptions/ec9fcd04-e188-48b9-abfc-
abcd515f1836/resourceGroups/spotVM/providers/Microsoft.Network/virtualNetworks/spotVM",
"subnetName": "default",
"networkInterfaceName": "spotVMNIC",
"publicIpAddressName": "spotVM-ip",
"publicIpAddressType": "Dynamic",
"publicIpAddressSku": "Basic",
"virtualMachineName": "spotVM",
"osDiskType": "Premium_LRS",
"osDiskType": "Premium_LRS",
"virtualMachineSize": "Standard_D2s_v3",
"adminUsername": "azureuser",
"adminPassword": "<password>",
"diagnosticsStorageAccountName": "diagstoragespot2019",
"diagnosticsStorageAccountId": "Microsoft.Storage/storageAccounts/diagstoragespot2019",
"diagnosticsStorageAccountType": "Standard_LRS",
"diagnosticsStorageAccountKind": "Storage",
"subnetRef": "[concat(variables('vnetId'), '/subnets/', variables('subnetName'))]"
},
"resources": [
{
"name": "spotVM",
"type": "Microsoft.Network/networkInterfaces",
"apiVersion": "2019-03-01",
"location": "eastus",
"dependsOn": [
"[concat('Microsoft.Network/publicIpAddresses/', variables('publicIpAddressName'))]"
],
"properties": {
"ipConfigurations": [
{
"name": "ipconfig1",
"properties": {
"subnet": {
"id": "[variables('subnetRef')]"
},
"privateIPAllocationMethod": "Dynamic",
"publicIpAddress": {
"id": "[resourceId(resourceGroup().name,
'Microsoft.Network/publicIpAddresses', variables('publicIpAddressName'))]"
}
}
}
]
}
},
{
"name": "[variables('publicIpAddressName')]",
"type": "Microsoft.Network/publicIpAddresses",
"apiVersion": "2019-02-01",
"location": "eastus",
"properties": {
"publicIpAllocationMethod": "[variables('publicIpAddressType')]"
},
"sku": {
"name": "[variables('publicIpAddressSku')]"
}
},
{
"name": "[variables('virtualMachineName')]",
"type": "Microsoft.Compute/virtualMachines",
"apiVersion": "2019-03-01",
"location": "eastus",
"dependsOn": [
"[concat('Microsoft.Network/networkInterfaces/', variables('networkInterfaceName'))]",
"[concat('Microsoft.Storage/storageAccounts/', variables('diagnosticsStorageAccountName'))]"
],
"properties": {
"hardwareProfile": {
"vmSize": "[variables('virtualMachineSize')]"
},
"storageProfile": {
"osDisk": {
"createOption": "fromImage",
"managedDisk": {
"storageAccountType": "[variables('osDiskType')]"
}
},
"imageReference": {
"publisher": "Canonical",
"offer": "UbuntuServer",
"sku": "18.04-LTS",
"version": "latest"
}
},
"networkProfile": {
"networkInterfaces": [
{
"id": "[resourceId('Microsoft.Network/networkInterfaces',
variables('networkInterfaceName'))]"
}
]
},
"osProfile": {
"computerName": "[variables('virtualMachineName')]",
"adminUsername": "[variables('adminUsername')]",
"adminPassword": "[variables('adminPassword')]"
},
"diagnosticsProfile": {
"bootDiagnostics": {
"enabled": true,
"storageUri": "[concat('https://', variables('diagnosticsStorageAccountName'),
'.blob.core.windows.net/')]"
}
},
"priority": "Spot",
"evictionPolicy": "Deallocate",
"billingProfile": {
"maxPrice": -1
}
}
},
{
"name": "[variables('diagnosticsStorageAccountName')]",
"type": "Microsoft.Storage/storageAccounts",
"apiVersion": "2019-04-01",
"location": "eastus",
"properties": {},
"kind": "[variables('diagnosticsStorageAccountKind')]",
"sku": {
"name": "[variables('diagnosticsStorageAccountType')]"
}
}
],
"outputs": {
"adminUsername": {
"type": "string",
"value": "[variables('adminUsername')]"
}
}
}

Next steps
You can also create a Spot VM using Azure PowerShell or the Azure CLI.
If you encounter an error, see Error codes.
Preview: Error messages for Spot VMs and scale sets
2/10/2020 • 2 minutes to read • Edit Online

IMPORTANT
Spot VMs and virtual machine scale sets are currently in public preview. This preview version is provided without a service
level agreement, and it's not recommended for production workloads. Certain features might not be supported or might
have constrained capabilities. For more information, see Supplemental Terms of Use for Microsoft Azure Previews.

Here are some possible error codes you could receive when using Spot VMs and scale sets.

KEY MESSAGE DESCRIPTION

SkuNotAvailable The requested tier for resource There is not enough Azure Spot
'<resource>' is currently not available capacity in this location to create your
in location '<location>' for subscription VM or scale set instance.
'<subscriptionID>'. Please try another
tier or deploy to a different location.

EvictionPolicyCanBeSetOnlyOnAzureSp Eviction policy can be set only on Azure This VM is not a Spot VM, so you can't
otVirtualMachines Spot Virtual Machines. set the eviction policy.

AzureSpotVMNotSupportedInAvailabilit Azure Spot Virtual Machine is not You need to choose to either use a
ySet supported in Availability Set. Spot VM or use a VM in an availability
set, you can't choose both.

AzureSpotFeatureNotEnabledForSubscri Subscription not enabled with Azure You need to have a subscription that
ption Spot feature. supports Spot VMs.

VMPriorityCannotBeApplied The specified priority value '{0}' cannot You need to specify the priority when
be applied to the Virtual Machine '{1}' the VM is created.
since no priority was specified when the
Virtual Machine was created.

SpotPriceGreaterThanProvidedMaxPrice Unable to perform operation '{0}' since Select a higher max price. For more
the provided max price '{1} USD' is information, see pricing information for
lower than the current spot price '{2} Linux or Windows.
USD' for Azure Spot VM size '{3}'.

MaxPriceValueInvalid Invalid max price value. The only Enter a valid max price. For more
supported values for max price are -1 information, see pricing for Linux or
or a decimal greater than zero. Max Windows.
price value of -1 indicates the Azure
Spot virtual machine will not be evicted
for price reasons.

MaxPriceChangeNotAllowedForAllocate Max price change is not allowed when Stop\Deallocate the VM so that you
dVMs the VM '{0}' is currently allocated. can change the max price.
Please deallocate and try again.

MaxPriceChangeNotAllowed Max price change is not allowed. You cannot change the max price for
this VM.
KEY MESSAGE DESCRIPTION

AzureSpotIsNotSupportedForThisAPIVe Azure Spot is not supported for this The API version needs to be 2019-03-
rsion API version. 01.

AzureSpotIsNotSupportedForThisVMSiz Azure Spot is not supported for this Select another VM size. For more
e VM size {0}. information, see Spot Virtual Machines.

MaxPriceIsSupportedOnlyForAzureSpot Max price is supported only for Azure For more information, see Spot Virtual
VirtualMachines Spot Virtual Machines. Machines.

MoveResourcesWithAzureSpotVMNotS The Move resources request contains a You cannot move Spot VMs.
upported Azure Spot virtual machine. This is
currently not supported. Please check
the error details for virtual machine Ids.

MoveResourcesWithAzureSpotVmssNot The Move resources request contains a You cannot move Spot scale set
Supported Azure Spot virtual machine scale set. instances.
This is currently not supported. Please
check the error details for virtual
machine scale set Ids.

EphemeralOSDisksNotSupportedForSpo Ephemeral OS disks are not supported You need to be using a regular OS disk
tVMs for Spot VMs. for your Spot VM.

AzureSpotVMNotSupportedInVmssWit Azure Spot Virtual Machine is not Set the orchestration mode to virtual
hVMOrchestrationMode supported in Virtual Machine Scale Set machine scale set in order to use Spot
with VM Orchestration mode. instances.

Next steps For more information, see spot Virtual Machines.


Create and manage Windows VMs in Azure using C#
12/23/2019 • 7 minutes to read • Edit Online

An Azure Virtual Machine (VM ) needs several supporting Azure resources. This article covers creating, managing,
and deleting VM resources using C#. You learn how to:
Create a Visual Studio project
Install the package
Create credentials
Create resources
Perform management tasks
Delete resources
Run the application
It takes about 20 minutes to do these steps.

Create a Visual Studio project


1. If you haven't already, install Visual Studio. Select .NET desktop development on the Workloads page, and
then click Install. In the summary, you can see that .NET Framework 4 - 4.6 development tools is
automatically selected for you. If you have already installed Visual Studio, you can add the .NET workload using
the Visual Studio Launcher.
2. In Visual Studio, click File > New > Project.
3. In Templates > Visual C#, select Console App (.NET Framework), enter myDotnetProject for the name of
the project, select the location of the project, and then click OK.

Install the package


NuGet packages are the easiest way to install the libraries that you need to finish these steps. To get the libraries
that you need in Visual Studio, do these steps:
1. Click Tools > Nuget Package Manager, and then click Package Manager Console.
2. Type this command in the console:

Install-Package Microsoft.Azure.Management.Fluent

Create credentials
Before you start this step, make sure that you have access to an Active Directory service principal. You should also
record the application ID, the authentication key, and the tenant ID that you need in a later step.
Create the authorization file
1. In Solution Explorer, right-click myDotnetProject > Add > New Item, and then select Text File in Visual
C# Items. Name the file azureauth.properties, and then click Add.
2. Add these authorization properties:
subscription=<subscription-id>
client=<application-id>
key=<authentication-key>
tenant=<tenant-id>
managementURI=https://management.core.windows.net/
baseURL=https://management.azure.com/
authURL=https://login.windows.net/
graphURL=https://graph.windows.net/

Replace <subscription-id> with your subscription identifier, <application-id> with the Active Directory
application identifier, <authentication-key> with the application key, and <tenant-id> with the tenant
identifier.
3. Save the azureauth.properties file.
4. Set an environment variable in Windows named AZURE_AUTH_LOCATION with the full path to
authorization file that you created. For example, the following PowerShell command can be used:

[Environment]::SetEnvironmentVariable("AZURE_AUTH_LOCATION", "C:\Visual Studio


2019\Projects\myDotnetProject\myDotnetProject\azureauth.properties", "User")

Create the management client


1. Open the Program.cs file for the project that you created. Then, add these using statements to the existing
statements at top of the file:

using Microsoft.Azure.Management.Compute.Fluent;
using Microsoft.Azure.Management.Compute.Fluent.Models;
using Microsoft.Azure.Management.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core;

2. To create the management client, add this code to the Main method:

var credentials = SdkContext.AzureCredentialsFactory


.FromFile(Environment.GetEnvironmentVariable("AZURE_AUTH_LOCATION"));

var azure = Azure


.Configure()
.WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
.Authenticate(credentials)
.WithDefaultSubscription();

Create resources
Create the resource group
All resources must be contained in a Resource group.
To specify values for the application and create the resource group, add this code to the Main method:
var groupName = "myResourceGroup";
var vmName = "myVM";
var location = Region.USWest;

Console.WriteLine("Creating resource group...");


var resourceGroup = azure.ResourceGroups.Define(groupName)
.WithRegion(location)
.Create();

Create the availability set


Availability sets make it easier for you to maintain the virtual machines used by your application.
To create the availability set, add this code to the Main method:

Console.WriteLine("Creating availability set...");


var availabilitySet = azure.AvailabilitySets.Define("myAVSet")
.WithRegion(location)
.WithExistingResourceGroup(groupName)
.WithSku(AvailabilitySetSkuTypes.Managed)
.Create();

Create the public IP address


A Public IP address is needed to communicate with the virtual machine.
To create the public IP address for the virtual machine, add this code to the Main method:

Console.WriteLine("Creating public IP address...");


var publicIPAddress = azure.PublicIPAddresses.Define("myPublicIP")
.WithRegion(location)
.WithExistingResourceGroup(groupName)
.WithDynamicIP()
.Create();

Create the virtual network


A virtual machine must be in a subnet of a Virtual network.
To create a subnet and a virtual network, add this code to the Main method:

Console.WriteLine("Creating virtual network...");


var network = azure.Networks.Define("myVNet")
.WithRegion(location)
.WithExistingResourceGroup(groupName)
.WithAddressSpace("10.0.0.0/16")
.WithSubnet("mySubnet", "10.0.0.0/24")
.Create();

Create the network interface


A virtual machine needs a network interface to communicate on the virtual network.
To create a network interface, add this code to the Main method:
Console.WriteLine("Creating network interface...");
var networkInterface = azure.NetworkInterfaces.Define("myNIC")
.WithRegion(location)
.WithExistingResourceGroup(groupName)
.WithExistingPrimaryNetwork(network)
.WithSubnet("mySubnet")
.WithPrimaryPrivateIPAddressDynamic()
.WithExistingPrimaryPublicIPAddress(publicIPAddress)
.Create();

Create the virtual machine


Now that you created all the supporting resources, you can create a virtual machine.
To create the virtual machine, add this code to the Main method:

Console.WriteLine("Creating virtual machine...");


azure.VirtualMachines.Define(vmName)
.WithRegion(location)
.WithExistingResourceGroup(groupName)
.WithExistingPrimaryNetworkInterface(networkInterface)
.WithLatestWindowsImage("MicrosoftWindowsServer", "WindowsServer", "2012-R2-Datacenter")
.WithAdminUsername("azureuser")
.WithAdminPassword("Azure12345678")
.WithComputerName(vmName)
.WithExistingAvailabilitySet(availabilitySet)
.WithSize(VirtualMachineSizeTypes.StandardDS1)
.Create();

NOTE
This tutorial creates a virtual machine running a version of the Windows Server operating system. To learn more about
selecting other images, see Navigate and select Azure virtual machine images with Windows PowerShell and the Azure CLI.

If you want to use an existing disk instead of a marketplace image, use this code:

var managedDisk = azure.Disks.Define("myosdisk")


.WithRegion(location)
.WithExistingResourceGroup(groupName)
.WithWindowsFromVhd("https://mystorage.blob.core.windows.net/vhds/myosdisk.vhd")
.WithSizeInGB(128)
.WithSku(DiskSkuTypes.PremiumLRS)
.Create();

azure.VirtualMachines.Define("myVM")
.WithRegion(location)
.WithExistingResourceGroup(groupName)
.WithExistingPrimaryNetworkInterface(networkInterface)
.WithSpecializedOSDisk(managedDisk, OperatingSystemTypes.Windows)
.WithExistingAvailabilitySet(availabilitySet)
.WithSize(VirtualMachineSizeTypes.StandardDS1)
.Create();

Perform management tasks


During the lifecycle of a virtual machine, you may want to run management tasks such as starting, stopping, or
deleting a virtual machine. Additionally, you may want to create code to automate repetitive or complex tasks.
When you need to do anything with the VM, you need to get an instance of it:
var vm = azure.VirtualMachines.GetByResourceGroup(groupName, vmName);

Get information about the VM


To get information about the virtual machine, add this code to the Main method:
Console.WriteLine("Getting information about the virtual machine...");
Console.WriteLine("hardwareProfile");
Console.WriteLine(" vmSize: " + vm.Size);
Console.WriteLine("storageProfile");
Console.WriteLine(" imageReference");
Console.WriteLine(" publisher: " + vm.StorageProfile.ImageReference.Publisher);
Console.WriteLine(" offer: " + vm.StorageProfile.ImageReference.Offer);
Console.WriteLine(" sku: " + vm.StorageProfile.ImageReference.Sku);
Console.WriteLine(" version: " + vm.StorageProfile.ImageReference.Version);
Console.WriteLine(" osDisk");
Console.WriteLine(" osType: " + vm.StorageProfile.OsDisk.OsType);
Console.WriteLine(" name: " + vm.StorageProfile.OsDisk.Name);
Console.WriteLine(" createOption: " + vm.StorageProfile.OsDisk.CreateOption);
Console.WriteLine(" caching: " + vm.StorageProfile.OsDisk.Caching);
Console.WriteLine("osProfile");
Console.WriteLine(" computerName: " + vm.OSProfile.ComputerName);
Console.WriteLine(" adminUsername: " + vm.OSProfile.AdminUsername);
Console.WriteLine(" provisionVMAgent: " + vm.OSProfile.WindowsConfiguration.ProvisionVMAgent.Value);
Console.WriteLine(" enableAutomaticUpdates: " +
vm.OSProfile.WindowsConfiguration.EnableAutomaticUpdates.Value);
Console.WriteLine("networkProfile");
foreach (string nicId in vm.NetworkInterfaceIds)
{
Console.WriteLine(" networkInterface id: " + nicId);
}
Console.WriteLine("vmAgent");
Console.WriteLine(" vmAgentVersion" + vm.InstanceView.VmAgent.VmAgentVersion);
Console.WriteLine(" statuses");
foreach (InstanceViewStatus stat in vm.InstanceView.VmAgent.Statuses)
{
Console.WriteLine(" code: " + stat.Code);
Console.WriteLine(" level: " + stat.Level);
Console.WriteLine(" displayStatus: " + stat.DisplayStatus);
Console.WriteLine(" message: " + stat.Message);
Console.WriteLine(" time: " + stat.Time);
}
Console.WriteLine("disks");
foreach (DiskInstanceView disk in vm.InstanceView.Disks)
{
Console.WriteLine(" name: " + disk.Name);
Console.WriteLine(" statuses");
foreach (InstanceViewStatus stat in disk.Statuses)
{
Console.WriteLine(" code: " + stat.Code);
Console.WriteLine(" level: " + stat.Level);
Console.WriteLine(" displayStatus: " + stat.DisplayStatus);
Console.WriteLine(" time: " + stat.Time);
}
}
Console.WriteLine("VM general status");
Console.WriteLine(" provisioningStatus: " + vm.ProvisioningState);
Console.WriteLine(" id: " + vm.Id);
Console.WriteLine(" name: " + vm.Name);
Console.WriteLine(" type: " + vm.Type);
Console.WriteLine(" location: " + vm.Region);
Console.WriteLine("VM instance status");
foreach (InstanceViewStatus stat in vm.InstanceView.Statuses)
{
Console.WriteLine(" code: " + stat.Code);
Console.WriteLine(" level: " + stat.Level);
Console.WriteLine(" displayStatus: " + stat.DisplayStatus);
}
Console.WriteLine("Press enter to continue...");
Console.ReadLine();

Stop the VM
You can stop a virtual machine and keep all its settings, but continue to be charged for it, or you can stop a virtual
machine and deallocate it. When a virtual machine is deallocated, all resources associated with it are also
deallocated and billing ends for it.
To stop the virtual machine without deallocating it, add this code to the Main method:

Console.WriteLine("Stopping vm...");
vm.PowerOff();
Console.WriteLine("Press enter to continue...");
Console.ReadLine();

If you want to deallocate the virtual machine, change the PowerOff call to this code:

vm.Deallocate();

Start the VM
To start the virtual machine, add this code to the Main method:

Console.WriteLine("Starting vm...");
vm.Start();
Console.WriteLine("Press enter to continue...");
Console.ReadLine();

Resize the VM
Many aspects of deployment should be considered when deciding on a size for your virtual machine. For more
information, see VM sizes.
To change size of the virtual machine, add this code to the Main method:

Console.WriteLine("Resizing vm...");
vm.Update()
.WithSize(VirtualMachineSizeTypes.StandardDS2)
.Apply();
Console.WriteLine("Press enter to continue...");
Console.ReadLine();

Add a data disk to the VM


To add a data disk to the virtual machine, add this code to the Main method. This example adds a data disk that is 2
GB in size, han a LUN of 0 and a caching type of ReadWrite:

Console.WriteLine("Adding data disk to vm...");


vm.Update()
.WithNewDataDisk(2, 0, CachingTypes.ReadWrite)
.Apply();
Console.WriteLine("Press enter to delete resources...");
Console.ReadLine();

Delete resources
Because you are charged for resources used in Azure, it is always good practice to delete resources that are no
longer needed. If you want to delete the virtual machines and all the supporting resources, all you have to do is
delete the resource group.
To delete the resource group, add this code to the Main method:
azure.ResourceGroups.DeleteByName(groupName);

Run the application


It should take about five minutes for this console application to run completely from start to finish.
1. To run the console application, click Start.
2. Before you press Enter to start deleting resources, you could take a few minutes to verify the creation of the
resources in the Azure portal. Click the deployment status to see information about the deployment.

Next steps
Take advantage of using a template to create a virtual machine by using the information in Deploy an Azure
Virtual Machine using C# and a Resource Manager template.
Learn more about using the Azure libraries for .NET.
Create a VM from a VHD by using the Azure portal
11/13/2019 • 3 minutes to read • Edit Online

There are several ways to create a virtual machine (VM ) in Azure:


If you already have a virtual hard disk (VHD ) to use or you want to copy the VHD from an existing VM to
use, you can create a new VM by attaching the VHD to the new VM as an OS disk.
You can create a new VM from the VHD of a VM that has been deleted. For example, if you have an Azure
VM that isn't working correctly, you can delete the VM and use its VHD to create a new VM. You can either
reuse the same VHD or create a copy of the VHD by creating a snapshot and then creating a new managed
disk from the snapshot. Although creating a snapshot takes a few more steps, it preserves the original VHD
and provides you with a fallback.
Take a classic VM and use the VHD to create a new VM that uses the Resource Manager deployment model
and managed disks. For the best results, Stop the classic VM in the Azure portal before creating the
snapshot.
You can create an Azure VM from an on-premises VHD by uploading the on-premises VHD and attaching it
to a new VM. You use PowerShell or another tool to upload the VHD to a storage account, and then you
create a managed disk from the VHD. For more information, see Upload a specialized VHD.
Don't use a specialized disk if you want to create multiple VMs. Instead, for larger deployments, create an image
and then use that image to create multiple VMs.
We recommend that you limit the number of concurrent deployments to 20 VMs from a single snapshot or VHD.

Copy a disk
Create a snapshot and then create a disk from the snapshot. This strategy allows you to keep the original VHD as a
fallback:
1. From the Azure portal, on the left menu, select All services.
2. In the All services search box, enter disks and then select Disks to display the list of available disks.
3. Select the disk that you would like to use. The Disk page for that disk appears.
4. From the menu at the top, select Create snapshot.
5. Enter a Name for the snapshot.
6. Choose a Resource group for the snapshot. You can use either an existing resource group or create a new one.
7. For Account type, choose either Standard (HDD ) or Premium (SSD ) storage.
8. When you're done, select Create to create the snapshot.
9. After the snapshot has been created, select Create a resource in the left menu.
10. In the search box, enter managed disk and then select Managed Disks from the list.
11. On the Managed Disks page, select Create.
12. Enter a Name for the disk.
13. Choose a Resource group for the disk. You can use either an existing resource group or create a new one. This
selection will also be used as the resource group where you create the VM from the disk.
14. For Account type, choose either Standard (HDD ) or Premium (SSD ) storage.
15. In Source type, ensure Snapshot is selected.
16. In the Source snapshot drop-down, select the snapshot you want to use.
17. Make any other adjustments as needed and then select Create to create the disk.
Create a VM from a disk
After you have the managed disk VHD that you want to use, you can create the VM in the portal:
1. From the Azure portal, on the left menu, select All services.
2. In the All services search box, enter disks and then select Disks to display the list of available disks.
3. Select the disk that you would like to use. The Disk page for that disk opens.
4. In the Overview page, ensure that DISK STATE is listed as Unattached. If it isn't, you might need to either
detach the disk from the VM or delete the VM to free up the disk.
5. In the menu at the top of the page, select Create VM.
6. On the Basics page for the new VM, enter a Virtual machine name and either select an existing Resource
group or create a new one.
7. For Size, select Change size to access the Size page.
8. Select a VM size row and then choose Select.
9. On the Networking page, you can either let the portal create all new resources or you can select an existing
Virtual network and Network security group. The portal always creates a new network interface and public
IP address for the new VM.
10. On the Management page, make any changes to the monitoring options.
11. On the Guest config page, add any extensions as needed.
12. When you're done, select Review + create.
13. If the VM configuration passes validation, select Create to start the deployment.

Next steps
You can also use PowerShell to upload a VHD to Azure and create a specialized VM.
Create a Windows VM from a specialized disk by
using PowerShell
12/18/2019 • 6 minutes to read • Edit Online

Create a new VM by attaching a specialized managed disk as the OS disk. A specialized disk is a copy of a virtual
hard disk (VHD ) from an existing VM that contains the user accounts, applications, and other state data from your
original VM.
When you use a specialized VHD to create a new VM, the new VM retains the computer name of the original VM.
Other computer-specific information is also kept and, in some cases, this duplicate information could cause issues.
When copying a VM, be aware of what types of computer-specific information your applications rely on.
You have several options:
Use an existing managed disk. This option is useful if you have a VM that isn't working correctly. You can delete
the VM and then reuse the managed disk to create a new VM.
Upload a VHD
Copy an existing Azure VM by using snapshots
You can also use the Azure portal to create a new VM from a specialized VHD.
This article shows you how to use managed disks. If you have a legacy deployment that requires using a storage
account, see Create a VM from a specialized VHD in a storage account.
We recommend that you limit the number of concurrent deployments to 20 VMs from a single VHD or snapshot.

Option 1: Use an existing disk


If you had a VM that you deleted and you want to reuse the OS disk to create a new VM, use Get-AzDisk.

$resourceGroupName = 'myResourceGroup'
$osDiskName = 'myOsDisk'
$osDisk = Get-AzDisk `
-ResourceGroupName $resourceGroupName `
-DiskName $osDiskName

You can now attach this disk as the OS disk to a new VM.

Option 2: Upload a specialized VHD


You can upload the VHD from a specialized VM created with an on-premises virtualization tool, like Hyper-V, or a
VM exported from another cloud.
Prepare the VM
Use the VHD as-is to create a new VM.
Prepare a Windows VHD to upload to Azure. Do not generalize the VM by using Sysprep.
Remove any guest virtualization tools and agents that are installed on the VM (such as VMware tools).
Make sure the VM is configured to get the IP address and DNS settings from DHCP. This ensures that the
server obtains an IP address within the virtual network when it starts up.
Upload the VHD
You can now upload a VHD straight into a managed disk. For instructions, see Upload a VHD to Azure using
Azure PowerShell.

Option 3: Copy an existing Azure VM


You can create a copy of a VM that uses managed disks by taking a snapshot of the VM, and then by using that
snapshot to create a new managed disk and a new VM.
If you want to copy an existing VM to another region, you might want to use azcopy to create a copy of a disk in
another region.
Take a snapshot of the OS disk
You can take a snapshot of an entire VM (including all disks) or of just a single disk. The following steps show you
how to take a snapshot of just the OS disk of your VM with the New -AzSnapshot cmdlet.
First, set some parameters.

$resourceGroupName = 'myResourceGroup'
$vmName = 'myVM'
$location = 'westus'
$snapshotName = 'mySnapshot'

Get the VM object.

$vm = Get-AzVM -Name $vmName `


-ResourceGroupName $resourceGroupName

Get the OS disk name.

$disk = Get-AzDisk -ResourceGroupName $resourceGroupName `


-DiskName $vm.StorageProfile.OsDisk.Name

Create the snapshot configuration.

$snapshotConfig = New-AzSnapshotConfig `
-SourceUri $disk.Id `
-OsType Windows `
-CreateOption Copy `
-Location $location

Take the snapshot.

$snapShot = New-AzSnapshot `
-Snapshot $snapshotConfig `
-SnapshotName $snapshotName `
-ResourceGroupName $resourceGroupName

To use this snapshot to create a VM that needs to be high-performing, add the parameter
-AccountType Premium_LRS to the New -AzSnapshotConfig command. This parameter creates the snapshot so that
it's stored as a Premium Managed Disk. Premium Managed Disks are more expensive than Standard, so be sure
you'll need Premium before using this parameter.
Create a new disk from the snapshot
Create a managed disk from the snapshot by using New -AzDisk. This example uses myOSDisk for the disk name.
Create a new resource group for the new VM.

$destinationResourceGroup = 'myDestinationResourceGroup'
New-AzResourceGroup -Location $location `
-Name $destinationResourceGroup

Set the OS disk name.

$osDiskName = 'myOsDisk'

Create the managed disk.

$osDisk = New-AzDisk -DiskName $osDiskName -Disk `


(New-AzDiskConfig -Location $location -CreateOption Copy `
-SourceResourceId $snapshot.Id) `
-ResourceGroupName $destinationResourceGroup

Create the new VM


Create networking and other VM resources to be used by the new VM.
Create the subnet and virtual network
Create the virtual network and subnet for the VM.
1. Create the subnet. This example creates a subnet named mySubNet, in the resource group
myDestinationResourceGroup, and sets the subnet address prefix to 10.0.0.0/24.

$subnetName = 'mySubNet'
$singleSubnet = New-AzVirtualNetworkSubnetConfig `
-Name $subnetName `
-AddressPrefix 10.0.0.0/24

2. Create the virtual network. This example sets the virtual network name to myVnetName, the location to
West US, and the address prefix for the virtual network to 10.0.0.0/16.

$vnetName = "myVnetName"
$vnet = New-AzVirtualNetwork `
-Name $vnetName -ResourceGroupName $destinationResourceGroup `
-Location $location `
-AddressPrefix 10.0.0.0/16 `
-Subnet $singleSubnet

Create the network security group and an RDP rule


To be able to sign in to your VM with remote desktop protocol (RDP ), you'll need to have a security rule that
allows RDP access on port 3389. In our example, the VHD for the new VM was created from an existing
specialized VM, so you can use an account that existed on the source virtual machine for RDP.
This example sets the network security group (NSG ) name to myNsg and the RDP rule name to myRdpRule.
$nsgName = "myNsg"

$rdpRule = New-AzNetworkSecurityRuleConfig -Name myRdpRule -Description "Allow RDP" `


-Access Allow -Protocol Tcp -Direction Inbound -Priority 110 `
-SourceAddressPrefix Internet -SourcePortRange * `
-DestinationAddressPrefix * -DestinationPortRange 3389
$nsg = New-AzNetworkSecurityGroup `
-ResourceGroupName $destinationResourceGroup `
-Location $location `
-Name $nsgName -SecurityRules $rdpRule

For more information about endpoints and NSG rules, see Opening ports to a VM in Azure by using PowerShell.
Create a public IP address and NIC
To enable communication with the virtual machine in the virtual network, you'll need a public IP address and a
network interface.
1. Create the public IP. In this example, the public IP address name is set to myIP.

$ipName = "myIP"
$pip = New-AzPublicIpAddress `
-Name $ipName -ResourceGroupName $destinationResourceGroup `
-Location $location `
-AllocationMethod Dynamic

2. Create the NIC. In this example, the NIC name is set to myNicName.

$nicName = "myNicName"
$nic = New-AzNetworkInterface -Name $nicName `
-ResourceGroupName $destinationResourceGroup `
-Location $location -SubnetId $vnet.Subnets[0].Id `
-PublicIpAddressId $pip.Id `
-NetworkSecurityGroupId $nsg.Id

Set the VM name and size


This example sets the VM name to myVM and the VM size to Standard_A2.

$vmName = "myVM"
$vmConfig = New-AzVMConfig -VMName $vmName -VMSize "Standard_A2"

Add the NIC

$vm = Add-AzVMNetworkInterface -VM $vmConfig -Id $nic.Id

Add the OS disk


Add the OS disk to the configuration by using Set-AzVMOSDisk. This example sets the size of the disk to 128 GB
and attaches the managed disk as a Windows OS disk.

$vm = Set-AzVMOSDisk -VM $vm -ManagedDiskId $osDisk.Id -StorageAccountType Standard_LRS `


-DiskSizeInGB 128 -CreateOption Attach -Windows

Complete the VM
Create the VM by using New -AzVM with the configurations that we just created.
New-AzVM -ResourceGroupName $destinationResourceGroup -Location $location -VM $vm

If this command is successful, you'll see output like this:

RequestId IsSuccessStatusCode StatusCode ReasonPhrase


--------- ------------------- ---------- ------------
True OK OK

Verify that the VM was created


You should see the newly created VM either in the Azure portal under Browse > Virtual machines, or by using
the following PowerShell commands.

$vmList = Get-AzVM -ResourceGroupName $destinationResourceGroup


$vmList.Name

Next steps
Sign in to your new virtual machine. For more information, see How to connect and log on to an Azure virtual
machine running Windows.
Deploy an Azure Virtual Machine using C# and a
Resource Manager template
11/13/2019 • 5 minutes to read • Edit Online

This article shows you how to deploy an Azure Resource Manager template using C#. The template that you create
deploys a single virtual machine running Windows Server in a new virtual network with a single subnet.
For a detailed description of the virtual machine resource, see Virtual machines in an Azure Resource Manager
template. For more information about all the resources in a template, see Azure Resource Manager template
walkthrough.
It takes about 10 minutes to do these steps.

Create a Visual Studio project


In this step, you make sure that Visual Studio is installed and you create a console application used to deploy the
template.
1. If you haven't already, install Visual Studio. Select .NET desktop development on the Workloads page, and
then click Install. In the summary, you can see that .NET Framework 4 - 4.6 development tools is
automatically selected for you. If you have already installed Visual Studio, you can add the .NET workload using
the Visual Studio Launcher.
2. In Visual Studio, click File > New > Project.
3. In Templates > Visual C#, select Console App (.NET Framework), enter myDotnetProject for the name of
the project, select the location of the project, and then click OK.

Install the packages


NuGet packages are the easiest way to install the libraries that you need to finish these steps. To get the libraries
that you need in Visual Studio, do these steps:
1. Click Tools > Nuget Package Manager, and then click Package Manager Console.
2. Type these commands in the console:

Install-Package Microsoft.Azure.Management.Fluent
Install-Package WindowsAzure.Storage

Create the files


In this step, you create a template file that deploys the resources and a parameters file that supplies parameter
values to the template. You also create an authorization file that is used to perform Azure Resource Manager
operations.
Create the template file
1. In Solution Explorer, right-click myDotnetProject > Add > New Item, and then select Text File in Visual
C# Items. Name the file CreateVMTemplate.json, and then click Add.
2. Add this JSON code to the file that you created:

{
{
"$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
"contentVersion": "1.0.0.0",
"parameters": {
"adminUsername": { "type": "string" },
"adminPassword": { "type": "securestring" }
},
"variables": {
"vnetID": "[resourceId('Microsoft.Network/virtualNetworks','myVNet')]",
"subnetRef": "[concat(variables('vnetID'),'/subnets/mySubnet')]",
},
"resources": [
{
"apiVersion": "2016-03-30",
"type": "Microsoft.Network/publicIPAddresses",
"name": "myPublicIPAddress",
"location": "[resourceGroup().location]",
"properties": {
"publicIPAllocationMethod": "Dynamic",
"dnsSettings": {
"domainNameLabel": "myresourcegroupdns1"
}
}
},
{
"apiVersion": "2016-03-30",
"type": "Microsoft.Network/virtualNetworks",
"name": "myVNet",
"location": "[resourceGroup().location]",
"properties": {
"addressSpace": { "addressPrefixes": [ "10.0.0.0/16" ] },
"subnets": [
{
"name": "mySubnet",
"properties": { "addressPrefix": "10.0.0.0/24" }
}
]
}
},
{
"apiVersion": "2016-03-30",
"type": "Microsoft.Network/networkInterfaces",
"name": "myNic",
"location": "[resourceGroup().location]",
"dependsOn": [
"[resourceId('Microsoft.Network/publicIPAddresses/', 'myPublicIPAddress')]",
"[resourceId('Microsoft.Network/virtualNetworks/', 'myVNet')]"
],
"properties": {
"ipConfigurations": [
{
"name": "ipconfig1",
"properties": {
"privateIPAllocationMethod": "Dynamic",
"publicIPAddress": { "id": "
[resourceId('Microsoft.Network/publicIPAddresses','myPublicIPAddress')]" },
"subnet": { "id": "[variables('subnetRef')]" }
}
}
]
}
},
{
"apiVersion": "2016-04-30-preview",
"type": "Microsoft.Compute/virtualMachines",
"name": "myVM",
"location": "[resourceGroup().location]",
"dependsOn": [
"[resourceId('Microsoft.Network/networkInterfaces/', 'myNic')]"
],
"properties": {
"hardwareProfile": { "vmSize": "Standard_DS1" },
"osProfile": {
"computerName": "myVM",
"adminUsername": "[parameters('adminUsername')]",
"adminPassword": "[parameters('adminPassword')]"
},
"storageProfile": {
"imageReference": {
"publisher": "MicrosoftWindowsServer",
"offer": "WindowsServer",
"sku": "2012-R2-Datacenter",
"version": "latest"
},
"osDisk": {
"name": "myManagedOSDisk",
"caching": "ReadWrite",
"createOption": "FromImage"
}
},
"networkProfile": {
"networkInterfaces": [
{
"id": "[resourceId('Microsoft.Network/networkInterfaces','myNic')]"
}
]
}
}
}
]
}

3. Save the CreateVMTemplate.json file.


Create the parameters file
To specify values for the resource parameters in the template, you create a parameters file that contains the values.
1. In Solution Explorer, right-click myDotnetProject > Add > New Item, and then select Text File in Visual
C# Items. Name the file Parameters.json, and then click Add.
2. Add this JSON code to the file that you created:

{
"$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json",
"contentVersion": "1.0.0.0",
"parameters": {
"adminUserName": { "value": "azureuser" },
"adminPassword": { "value": "Azure12345678" }
}
}

3. Save the Parameters.json file.


Create the authorization file
Before you can deploy a template, make sure that you have access to an Active Directory service principal. From
the service principal, you acquire a token for authenticating requests to Azure Resource Manager. You should also
record the application ID, the authentication key, and the tenant ID that you need in the authorization file.
1. In Solution Explorer, right-click myDotnetProject > Add > New Item, and then select Text File in Visual
C# Items. Name the file azureauth.properties, and then click Add.
2. Add these authorization properties:
subscription=<subscription-id>
client=<application-id>
key=<authentication-key>
tenant=<tenant-id>
managementURI=https://management.core.windows.net/
baseURL=https://management.azure.com/
authURL=https://login.windows.net/
graphURL=https://graph.windows.net/

Replace <subscription-id> with your subscription identifier, <application-id> with the Active Directory
application identifier, <authentication-key> with the application key, and <tenant-id> with the tenant
identifier.
3. Save the azureauth.properties file.
4. Set an environment variable in Windows named AZURE_AUTH_LOCATION with the full path to
authorization file that you created, for example you can use the following PowerShell command:

[Environment]::SetEnvironmentVariable("AZURE_AUTH_LOCATION", "C:\Visual Studio


2019\Projects\myDotnetProject\myDotnetProject\azureauth.properties", "User")

Create the management client


1. Open the Program.cs file for the project that you created. Then, add these using statements to the existing
statements at top of the file:

using Microsoft.Azure.Management.Compute.Fluent;
using Microsoft.Azure.Management.Compute.Fluent.Models;
using Microsoft.Azure.Management.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;

2. To create the management client, add this code to the Main method:

var credentials = SdkContext.AzureCredentialsFactory


.FromFile(Environment.GetEnvironmentVariable("AZURE_AUTH_LOCATION"));

var azure = Azure


.Configure()
.WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
.Authenticate(credentials)
.WithDefaultSubscription();

Create a resource group


To specify values for the application, add code to the Main method:

var groupName = "myResourceGroup";


var location = Region.USWest;

var resourceGroup = azure.ResourceGroups.Define(groupName)


.WithRegion(location)
.Create();
Create a storage account
The template and parameters are deployed from a storage account in Azure. In this step, you create the account
and upload the files.
To create the account, add this code to the Main method:

string storageAccountName = SdkContext.RandomResourceName("st", 10);

Console.WriteLine("Creating storage account...");


var storage = azure.StorageAccounts.Define(storageAccountName)
.WithRegion(Region.USWest)
.WithExistingResourceGroup(resourceGroup)
.Create();

var storageKeys = storage.GetKeys();


string storageConnectionString = "DefaultEndpointsProtocol=https;"
+ "AccountName=" + storage.Name
+ ";AccountKey=" + storageKeys[0].Value
+ ";EndpointSuffix=core.windows.net";

var account = CloudStorageAccount.Parse(storageConnectionString);


var serviceClient = account.CreateCloudBlobClient();

Console.WriteLine("Creating container...");
var container = serviceClient.GetContainerReference("templates");
container.CreateIfNotExistsAsync().Wait();
var containerPermissions = new BlobContainerPermissions()
{ PublicAccess = BlobContainerPublicAccessType.Container };
container.SetPermissionsAsync(containerPermissions).Wait();

Console.WriteLine("Uploading template file...");


var templateblob = container.GetBlockBlobReference("CreateVMTemplate.json");
templateblob.UploadFromFileAsync("..\\..\\CreateVMTemplate.json").Result();

Console.WriteLine("Uploading parameters file...");


var paramblob = container.GetBlockBlobReference("Parameters.json");
paramblob.UploadFromFileAsync("..\\..\\Parameters.json").Result();

Deploy the template


Deploy the template and parameters from the storage account that was created.
To deploy the template, add this code to the Main method:

var templatePath = "https://" + storageAccountName + ".blob.core.windows.net/templates/CreateVMTemplate.json";


var paramPath = "https://" + storageAccountName + ".blob.core.windows.net/templates/Parameters.json";
var deployment = azure.Deployments.Define("myDeployment")
.WithExistingResourceGroup(groupName)
.WithTemplateLink(templatePath, "1.0.0.0")
.WithParametersLink(paramPath, "1.0.0.0")
.WithMode(Microsoft.Azure.Management.ResourceManager.Fluent.Models.DeploymentMode.Incremental)
.Create();
Console.WriteLine("Press enter to delete the resource group...");
Console.ReadLine();

Delete the resources


Because you are charged for resources used in Azure, it is always good practice to delete resources that are no
longer needed. You don’t need to delete each resource separately from a resource group. Delete the resource
group and all its resources are automatically deleted.
To delete the resource group, add this code to the Main method:

azure.ResourceGroups.DeleteByName(groupName);

Run the application


It should take about five minutes for this console application to run completely from start to finish.
1. To run the console application, click Start.
2. Before you press Enter to start deleting resources, you could take a few minutes to verify the creation of the
resources in the Azure portal. Click the deployment status to see information about the deployment.

Next steps
If there were issues with the deployment, a next step would be to look at Troubleshoot common Azure
deployment errors with Azure Resource Manager.
Learn how to deploy a virtual machine and its supporting resources by reviewing Deploy an Azure Virtual
Machine Using C#.
Quickstart - Configure a Windows virtual machine in
Azure using Chef
2/24/2020 • 7 minutes to read • Edit Online

Chef enables you to deliver automation and desired state configurations.


With the latest cloud API release, Chef provides seamless integration with Azure, giving you the ability to provision
and deploy configuration states through a single command.
In this article, you set up your Chef environment to provision Azure virtual machines and walk through creating a
policy or cookbook and then deploying this cookbook to an Azure virtual machine.

Chef basics
Before you begin with this article, review the basic concepts of Chef.
The following diagram shows the high-level Chef architecture.

Chef has three main architectural components:


Chef Server - The management point and there are two options for the Chef Server: a hosted solution or an on-
premises solution.
Chef Client (node) - The agent that sits on the servers you are managing.
Chef Workstation - The name for both the admin workstation (where you create policies and run management
commands) and the software package of Chef tools.
Generally, you see your workstation as the location where you run commands and Chef Workstation for the
software package.
For example, you download the knife command as part of the Chef Workstation, but you run knife commands
from your workstation to manage infrastructure.
Chef also uses the concepts of cookbooks and recipes. These terms are the policies that are defined and applied to
the servers, respectively.

Preparing your workstation


First, prep your workstation by creating a directory to store Chef configuration files and cookbooks.
Create a directory named C:\Chef .
Download and install the latest Azure CLI version on to your workstation.

Configure Azure Service Principal


We'll be using a Service Principal to help us create Azure resources from our Chef Workstation. To create the
relevant Service Principal with the required permissions, run the following commands within PowerShell:

Login-AzureRmAccount
Get-AzureRmSubscription
Select-AzureRmSubscription -SubscriptionName "<yourSubscriptionName>"
$myApplication = New-AzureRmADApplication -DisplayName "automation-app" -HomePage "https://chef-automation-
test.com" -IdentifierUris "https://chef-automation-test.com" -Password "#1234p$wdchef19"
New-AzureRmADServicePrincipal -ApplicationId $myApplication.ApplicationId
New-AzureRmRoleAssignment -RoleDefinitionName Contributor -ServicePrincipalName $myApplication.ApplicationId

Take note of your SubscriptionID, TenantID, ClientID, and Client Secret (the password you set previously in this
tutorial) as you will need these values.

Setup Chef Server


This guide assumes that you'll sign up for Hosted Chef.
If you're not already using a Chef Server, you can:
Sign up for Hosted Chef, which is the fastest way to get started with Chef.
Install a standalone Chef Server on linux-based machine, following the installation instructions from Chef Docs.
Creating a Hosted Chef account
Sign up for a Hosted Chef account here.
During the sign-up process, you will be asked to create a new organization.
Once your organization is created, download the starter kit.

NOTE
If you receive a prompt warning you that your keys will be reset, it’s okay to proceed as we have no existing infrastructure
configured as yet.

This starter kit zip file contains your organization configuration files and user key in the .chef directory.
The organization-validator.pem must be downloaded separately, because it's a private key and private keys should
not be stored on the Chef Server. From Chef Manage, go into the Administration section, and select "Reset
Validation Key", which provides a file for you to download separately. Save the file to c:\chef.
Configuring your Chef workstation
Extract the content of the chef-starter.zip to c:\chef .
Copy all files under chef-starter\chef-repo\.chef to your c:\chef directory.
Copy the organization-validator.pem file to c:\chef , if it's saved in c:\Downloads .
Your directory should now look something like the following example.

Directory: C:\Users\username\chef

Mode LastWriteTime Length Name


---- ------------- ------ ----
d----- 12/6/2018 6:41 PM .chef
d----- 12/6/2018 5:40 PM chef-repo
d----- 12/6/2018 5:38 PM cookbooks
d----- 12/6/2018 5:38 PM roles
-a---- 12/6/2018 5:38 PM 495 .gitignore
-a---- 12/6/2018 5:37 PM 1678 azuredocs-validator.pem
-a---- 12/6/2018 5:38 PM 1674 user.pem
-a---- 12/6/2018 5:53 PM 414 knife.rb
-a---- 12/6/2018 5:38 PM 2341 README.md

You should now have five files and four directories (including the empty chef-repo directory) in the root of c:\chef.
Edit knife.rb
The PEM files contain your organization and administrative private keys for communication and the knife.rb file
contains your knife configuration. We will need to edit the knife.rb file.
Open the knife.rb file in the editor of your choice. The unaltered file should look something like:

current_dir = File.dirname(__FILE__)
log_level :info
log_location STDOUT
node_name "mynode"
client_key "#{current_dir}/user.pem"
chef_server_url "https://api.chef.io/organizations/myorg"
cookbook_path ["#{current_dir}/cookbooks"]

Add the following information to your knife.rb, replacing the placeholders with your information:

validation_client_name "myorg-validator"
validation_key "#{current_dir}/myorg.pem"
knife[:azure_tenant_id] = "0000000-1111-aaaa-bbbb-222222222222"
knife[:azure_subscription_id] = "11111111-bbbbb-cccc-1111-222222222222"
knife[:azure_client_id] = "11111111-bbbbb-cccc-1111-2222222222222"
knife[:azure_client_secret] = "#1234p$wdchef19"

These lines will ensure that Knife references the cookbooks directory under c:\chef\cookbooks .
Your knife.rb file should now look similar to the following example:
current_dir = File.dirname(__FILE__)
log_level :info
log_location STDOUT
node_name "myorg"
client_key "#{current_dir}/myorg.pem"
validation_client_name "myorg-validator"
validation_key "#{current_dir}/myorg-validator.pem"
chef_server_url "https://api.chef.io/organizations/myorg"
cookbook_path ["#{current_dir}/../cookbooks"]
knife[:azure_tenant_id] = "0000000-1111-aaaa-bbbb-222222222222"
knife[:azure_subscription_id] = "11111111-bbbbb-cccc-1111-222222222222"
knife[:azure_client_id] = "11111111-bbbbb-cccc-1111-2222222222222"
knife[:azure_client_secret] = "#1234p$wdchef19"

Install Chef Workstation


Next, download, and install the Chef Workstation.
Install Chef Workstation to the default location.
On the desktop, you'll see a CW PowerShell. This tool is used to interact with Chef products. The CW PowerShell
makes new commands available, such as chef-run and Chef CLI commands (such as chef ). See your installed
version of Chef Workstation and the Chef tools with chef -v . You can also check your Workstation version by
selecting About Chef Workstation from the Chef Workstation App.
chef --version should return something like:

Chef Workstation: 0.4.2


chef-run: 0.3.0
chef-client: 15.0.300
delivery-cli: 0.0.52 (9d07501a3b347cc687c902319d23dc32dd5fa621)
berks: 7.0.8
test-kitchen: 2.2.5
inspec: 4.3.2

NOTE
The order of the path is important! If your opscode paths are not in the correct order, problems will result.

Reboot your workstation before you continue.


Install Knife Azure
This tutorial assumes that you're using the Azure Resource Manager to interact with your virtual machine.
Install the Knife Azure extension, which includes the Azure Plugin.
Run the following command.

chef gem install knife-azure ––pre

NOTE
The –-pre argument ensures you are receiving the latest RC version of the Knife Azure Plugin which provides access to the
latest set of APIs.
It’s likely that a number of dependencies will also be installed at the same time.

To ensure everything is configured correctly, run the following command.

knife azurerm server list

If everything is configured correctly, you will see a list of available Azure images scroll through.
Congratulations. Your workstation is set up!

Creating a cookbook
A cookbook is used by Chef to define a set of commands that you wish to run on your managed client. Creating a
cookbook is straightforward, just use the chef generate cookbook command to generate the cookbook template.
This cookbook is for a web server that automatically deploys IIS.
Under your C:\Chef directory , run the following command.

chef generate cookbook webserver

This command generates a set of files under the directory C:\Chef\cookbooks\webserver. Next, define the set of
commands for the Chef client to run on the managed virtual machine.
The commands are stored in the file default.rb. In this file, define a set of commands that installs IIS, starts IIS, and
copies a template file to the wwwroot folder.
Modify the C:\chef\cookbooks\webserver\recipes\default.rb file and add the following lines.

powershell_script 'Install IIS' do


action :run
code 'add-windowsfeature Web-Server'
end

service 'w3svc' do
action [ :enable, :start ]
end

template 'c:\inetpub\wwwroot\Default.htm' do
source 'Default.htm.erb'
rights :read, 'Everyone'
end

Save the file once you are done.


Creating a template
In this step, you'll generate a template file to use as the default.html page.
Run the following command to generate the template:

chef generate template webserver Default.htm

Navigate to the C:\chef\cookbooks\webserver\templates\default\Default.htm.erb file. Edit the file by adding some


simple Hello World HTML code, and then save the file.

Upload the cookbook to the Chef Server


In this step, you make a copy of the cookbook that you have created on the local machine and upload it to the Chef
Hosted Server. Once uploaded, the cookbook appears under the Policy tab.

knife cookbook upload webserver

Deploy a virtual machine with Knife Azure


Deploy an Azure virtual machine and apply the Webserver cookbook using the knife command.
The knife command will also install the IIS web service and default web page.

knife azurerm server create `


--azure-resource-group-name rg-chefdeployment `
--azure-storage-account store `
--azure-vm-name chefvm `
--azure-vm-size 'Standard_DS2_v2' `
--azure-service-location 'westus' `
--azure-image-reference-offer 'WindowsServer' `
--azure-image-reference-publisher 'MicrosoftWindowsServer' `
--azure-image-reference-sku '2016-Datacenter' `
--azure-image-reference-version 'latest' `
-x myuser -P myPassword123 `
--tcp-endpoints '80,3389' `
--chef-daemon-interval 1 `
-r "recipe[webserver]"

The knife command example creates a Standard_DS2_v2 virtual machine with Windows Server 2016 installed
within the West US region. Modify these values to per your app needs.
After running the command, browse to the Azure portal to see your machine begin to provision.

The command prompt appears next.


Once the deployment is complete, the public IP address of the new virtual machine is displayed. Paste this value
into a web browser to view the new website. When we deployed the virtual machine, we opened port 80 so it
should be available externally.

This example uses creative HTML code.


You can also view the node's status Chef Manage.

Don’t forget you can also connect through an RDP session from the Azure portal via port 3389.
Next steps
Chef on Azure
Create and manage Windows VMs in Azure using
Java
12/23/2019 • 7 minutes to read • Edit Online

An Azure Virtual Machine (VM ) needs several supporting Azure resources. This article covers creating, managing,
and deleting VM resources using Java. You learn how to:
Create a Maven project
Add dependencies
Create credentials
Create resources
Perform management tasks
Delete resources
Run the application
It takes about 20 minutes to do these steps.

Create a Maven project


1. If you haven't already done so, install Java.
2. Install Maven.
3. Create a new folder and the project:

mkdir java-azure-test
cd java-azure-test

mvn archetype:generate -DgroupId=com.fabrikam -DartifactId=testAzureApp -DarchetypeArtifactId=maven-


archetype-quickstart -DinteractiveMode=false

Add dependencies
1. Under the testAzureApp folder, open the pom.xml file and add the build configuration to <project> to
enable the building of your application:

<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<configuration>
<mainClass>com.fabrikam.testAzureApp.App</mainClass>
</configuration>
</plugin>
</plugins>
</build>

2. Add the dependencies that are needed to access the Azure Java SDK.
<dependency>
<groupId>com.microsoft.azure</groupId>
<artifactId>azure</artifactId>
<version>1.1.0</version>
</dependency>
<dependency>
<groupId>com.microsoft.azure</groupId>
<artifactId>azure-mgmt-compute</artifactId>
<version>1.1.0</version>
</dependency>
<dependency>
<groupId>com.microsoft.azure</groupId>
<artifactId>azure-mgmt-resources</artifactId>
<version>1.1.0</version>
</dependency>
<dependency>
<groupId>com.microsoft.azure</groupId>
<artifactId>azure-mgmt-network</artifactId>
<version>1.1.0</version>
</dependency>
<dependency>
<groupId>com.squareup.okio</groupId>
<artifactId>okio</artifactId>
<version>1.13.0</version>
</dependency>
<dependency>
<groupId>com.nimbusds</groupId>
<artifactId>nimbus-jose-jwt</artifactId>
<version>3.6</version>
</dependency>
<dependency>
<groupId>net.minidev</groupId>
<artifactId>json-smart</artifactId>
<version>1.0.6.3</version>
</dependency>
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.5</version>
</dependency>

3. Save the file.

Create credentials
Before you start this step, make sure that you have access to an Active Directory service principal. You should also
record the application ID, the authentication key, and the tenant ID that you need in a later step.
Create the authorization file
1. Create a file named azureauth.properties and add these properties to it:

subscription=<subscription-id>
client=<application-id>
key=<authentication-key>
tenant=<tenant-id>
managementURI=https://management.core.windows.net/
baseURL=https://management.azure.com/
authURL=https://login.windows.net/
graphURL=https://graph.windows.net/

Replace <subscription-id> with your subscription identifier, <application-id> with the Active Directory
application identifier, <authentication-key> with the application key, and <tenant-id> with the tenant
identifier.
2. Save the file.
3. Set an environment variable named AZURE_AUTH_LOCATION in your shell with the full path to the
authentication file.
Create the management client
1. Open the App.java file under src\main\java\com\fabrikam and make sure this package statement is at the
top:

package com.fabrikam.testAzureApp;

2. Under the package statement, add these import statements:

import com.microsoft.azure.management.Azure;
import com.microsoft.azure.management.compute.AvailabilitySet;
import com.microsoft.azure.management.compute.AvailabilitySetSkuTypes;
import com.microsoft.azure.management.compute.CachingTypes;
import com.microsoft.azure.management.compute.InstanceViewStatus;
import com.microsoft.azure.management.compute.DiskInstanceView;
import com.microsoft.azure.management.compute.VirtualMachine;
import com.microsoft.azure.management.compute.VirtualMachineSizeTypes;
import com.microsoft.azure.management.network.PublicIPAddress;
import com.microsoft.azure.management.network.Network;
import com.microsoft.azure.management.network.NetworkInterface;
import com.microsoft.azure.management.resources.ResourceGroup;
import com.microsoft.azure.management.resources.fluentcore.arm.Region;
import com.microsoft.azure.management.resources.fluentcore.model.Creatable;
import com.microsoft.rest.LogLevel;
import java.io.File;
import java.util.Scanner;

3. To create the Active Directory credentials that you need to make requests, add this code to the main method
of the App class:

try {
final File credFile = new File(System.getenv("AZURE_AUTH_LOCATION"));
Azure azure = Azure.configure()
.withLogLevel(LogLevel.BASIC)
.authenticate(credFile)
.withDefaultSubscription();
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}

Create resources
Create the resource group
All resources must be contained in a Resource group.
To specify values for the application and create the resource group, add this code to the try block in the main
method:
System.out.println("Creating resource group...");
ResourceGroup resourceGroup = azure.resourceGroups()
.define("myResourceGroup")
.withRegion(Region.US_EAST)
.create();

Create the availability set


Availability sets make it easier for you to maintain the virtual machines used by your application.
To create the availability set, add this code to the try block in the main method:

System.out.println("Creating availability set...");


AvailabilitySet availabilitySet = azure.availabilitySets()
.define("myAvailabilitySet")
.withRegion(Region.US_EAST)
.withExistingResourceGroup("myResourceGroup")
.withSku(AvailabilitySetSkuTypes.MANAGED)
.create();

Create the public IP address


A Public IP address is needed to communicate with the virtual machine.
To create the public IP address for the virtual machine, add this code to the try block in the main method:

System.out.println("Creating public IP address...");


PublicIPAddress publicIPAddress = azure.publicIPAddresses()
.define("myPublicIP")
.withRegion(Region.US_EAST)
.withExistingResourceGroup("myResourceGroup")
.withDynamicIP()
.create();

Create the virtual network


A virtual machine must be in a subnet of a Virtual network.
To create a subnet and a virtual network, add this code to the try block in the main method:

System.out.println("Creating virtual network...");


Network network = azure.networks()
.define("myVN")
.withRegion(Region.US_EAST)
.withExistingResourceGroup("myResourceGroup")
.withAddressSpace("10.0.0.0/16")
.withSubnet("mySubnet","10.0.0.0/24")
.create();

Create the network interface


A virtual machine needs a network interface to communicate on the virtual network.
To create a network interface, add this code to the try block in the main method:
System.out.println("Creating network interface...");
NetworkInterface networkInterface = azure.networkInterfaces()
.define("myNIC")
.withRegion(Region.US_EAST)
.withExistingResourceGroup("myResourceGroup")
.withExistingPrimaryNetwork(network)
.withSubnet("mySubnet")
.withPrimaryPrivateIPAddressDynamic()
.withExistingPrimaryPublicIPAddress(publicIPAddress)
.create();

Create the virtual machine


Now that you created all the supporting resources, you can create a virtual machine.
To create the virtual machine, add this code to the try block in the main method:

System.out.println("Creating virtual machine...");


VirtualMachine virtualMachine = azure.virtualMachines()
.define("myVM")
.withRegion(Region.US_EAST)
.withExistingResourceGroup("myResourceGroup")
.withExistingPrimaryNetworkInterface(networkInterface)
.withLatestWindowsImage("MicrosoftWindowsServer", "WindowsServer", "2012-R2-Datacenter")
.withAdminUsername("azureuser")
.withAdminPassword("Azure12345678")
.withComputerName("myVM")
.withExistingAvailabilitySet(availabilitySet)
.withSize("Standard_DS1")
.create();
Scanner input = new Scanner(System.in);
System.out.println("Press enter to get information about the VM...");
input.nextLine();

NOTE
This tutorial creates a virtual machine running a version of the Windows Server operating system. To learn more about
selecting other images, see Navigate and select Azure virtual machine images with Windows PowerShell and the Azure CLI.

If you want to use an existing disk instead of a marketplace image, use this code:

ManagedDisk managedDisk = azure.disks.define("myosdisk")


.withRegion(Region.US_EAST)
.withExistingResourceGroup("myResourceGroup")
.withWindowsFromVhd("https://mystorage.blob.core.windows.net/vhds/myosdisk.vhd")
.withSizeInGB(128)
.withSku(DiskSkuTypes.PremiumLRS)
.create();

azure.virtualMachines.define("myVM")
.withRegion(Region.US_EAST)
.withExistingResourceGroup("myResourceGroup")
.withExistingPrimaryNetworkInterface(networkInterface)
.withSpecializedOSDisk(managedDisk, OperatingSystemTypes.Windows)
.withExistingAvailabilitySet(availabilitySet)
.withSize(VirtualMachineSizeTypes.StandardDS1)
.create();

Perform management tasks


During the lifecycle of a virtual machine, you may want to run management tasks such as starting, stopping, or
deleting a virtual machine. Additionally, you may want to create code to automate repetitive or complex tasks.
When you need to do anything with the VM, you need to get an instance of it. Add this code to the try block of the
main method:

VirtualMachine vm = azure.virtualMachines().getByResourceGroup("myResourceGroup", "myVM");

Get information about the VM


To get information about the virtual machine, add this code to the try block in the main method:

System.out.println("hardwareProfile");
System.out.println(" vmSize: " + vm.size());
System.out.println("storageProfile");
System.out.println(" imageReference");
System.out.println(" publisher: " + vm.storageProfile().imageReference().publisher());
System.out.println(" offer: " + vm.storageProfile().imageReference().offer());
System.out.println(" sku: " + vm.storageProfile().imageReference().sku());
System.out.println(" version: " + vm.storageProfile().imageReference().version());
System.out.println(" osDisk");
System.out.println(" osType: " + vm.storageProfile().osDisk().osType());
System.out.println(" name: " + vm.storageProfile().osDisk().name());
System.out.println(" createOption: " + vm.storageProfile().osDisk().createOption());
System.out.println(" caching: " + vm.storageProfile().osDisk().caching());
System.out.println("osProfile");
System.out.println(" computerName: " + vm.osProfile().computerName());
System.out.println(" adminUserName: " + vm.osProfile().adminUsername());
System.out.println(" provisionVMAgent: " + vm.osProfile().windowsConfiguration().provisionVMAgent());
System.out.println(" enableAutomaticUpdates: " +
vm.osProfile().windowsConfiguration().enableAutomaticUpdates());
System.out.println("networkProfile");
System.out.println(" networkInterface: " + vm.primaryNetworkInterfaceId());
System.out.println("vmAgent");
System.out.println(" vmAgentVersion: " + vm.instanceView().vmAgent().vmAgentVersion());
System.out.println(" statuses");
for(InstanceViewStatus status : vm.instanceView().vmAgent().statuses()) {
System.out.println(" code: " + status.code());
System.out.println(" displayStatus: " + status.displayStatus());
System.out.println(" message: " + status.message());
System.out.println(" time: " + status.time());
}
System.out.println("disks");
for(DiskInstanceView disk : vm.instanceView().disks()) {
System.out.println(" name: " + disk.name());
System.out.println(" statuses");
for(InstanceViewStatus status : disk.statuses()) {
System.out.println(" code: " + status.code());
System.out.println(" displayStatus: " + status.displayStatus());
System.out.println(" time: " + status.time());
}
}
System.out.println("VM general status");
System.out.println(" provisioningStatus: " + vm.provisioningState());
System.out.println(" id: " + vm.id());
System.out.println(" name: " + vm.name());
System.out.println(" type: " + vm.type());
System.out.println("VM instance status");
for(InstanceViewStatus status : vm.instanceView().statuses()) {
System.out.println(" code: " + status.code());
System.out.println(" displayStatus: " + status.displayStatus());
}
System.out.println("Press enter to continue...");
input.nextLine();
Stop the VM
You can stop a virtual machine and keep all its settings, but continue to be charged for it, or you can stop a virtual
machine and deallocate it. When a virtual machine is deallocated, all resources associated with it are also
deallocated and billing ends for it.
To stop the virtual machine without deallocating it, add this code to the try block in the main method:

System.out.println("Stopping vm...");
vm.powerOff();
System.out.println("Press enter to continue...");
input.nextLine();

If you want to deallocate the virtual machine, change the PowerOff call to this code:

vm.deallocate();

Start the VM
To start the virtual machine, add this code to the try block in the main method:

System.out.println("Starting vm...");
vm.start();
System.out.println("Press enter to continue...");
input.nextLine();

Resize the VM
Many aspects of deployment should be considered when deciding on a size for your virtual machine. For more
information, see VM sizes.
To change size of the virtual machine, add this code to the try block in the main method:

System.out.println("Resizing vm...");
vm.update()
.withSize(VirtualMachineSizeTypes.STANDARD_DS2)
.apply();
System.out.println("Press enter to continue...");
input.nextLine();

Add a data disk to the VM


To add a data disk to the virtual machine that is 2 GB in size, has a LUN of 0, and a caching type of ReadWrite, add
this code to the try block in the main method:

System.out.println("Adding data disk...");


vm.update()
.withNewDataDisk(2, 0, CachingTypes.READ_WRITE)
.apply();
System.out.println("Press enter to delete resources...");
input.nextLine();

Delete resources
Because you are charged for resources used in Azure, it is always good practice to delete resources that are no
longer needed. If you want to delete the virtual machines and all the supporting resources, all you have to do is
delete the resource group.
1. To delete the resource group, add this code to the try block in the main method:

System.out.println("Deleting resources...");
azure.resourceGroups().deleteByName("myResourceGroup");

2. Save the App.java file.

Run the application


It should take about five minutes for this console application to run completely from start to finish.
1. To run the application, use this Maven command:

mvn compile exec:java

2. Before you press Enter to start deleting resources, you could take a few minutes to verify the creation of the
resources in the Azure portal. Click the deployment status to see information about the deployment.

Next steps
Learn more about using the Azure libraries for Java.
Create and manage Windows VMs in Azure using
Python
12/23/2019 • 10 minutes to read • Edit Online

An Azure Virtual Machine (VM ) needs several supporting Azure resources. This article covers creating, managing,
and deleting VM resources using Python. You learn how to:
Create a Visual Studio project
Install packages
Create credentials
Create resources
Perform management tasks
Delete resources
Run the application
It takes about 20 minutes to do these steps.

Create a Visual Studio project


1. If you haven't already, install Visual Studio. Select Python development on the Workloads page, and then click
Install. In the summary, you can see that Python 3 64-bit (3.6.0) is automatically selected for you. If you have
already installed Visual Studio, you can add the Python workload using the Visual Studio Launcher.
2. After installing and starting Visual Studio, click File > New > Project.
3. Click Templates > Python > Python Application, enter myPythonProject for the name of the project, select
the location of the project, and then click OK.

Install packages
1. In Solution Explorer, under myPythonProject, right-click Python Environments, and then select Add virtual
environment.
2. On the Add Virtual Environment screen, accept the default name of env, make sure that Python 3.6 (64 -bit) is
selected for the base interpreter, and then click Create.
3. Right-click the env environment that you created, click Install Python Package, enter azure in the search box,
and then press Enter.
You should see in the output windows that the azure packages were successfully installed.

Create credentials
Before you start this step, make sure that you have an Active Directory service principal. You should also record the
application ID, the authentication key, and the tenant ID that you need in a later step.
1. Open myPythonProject.py file that was created, and then add this code to enable your application to run:

if __name__ == "__main__":

2. To import the code that is needed, add these statements to the top of the .py file:
from azure.common.credentials import ServicePrincipalCredentials
from azure.mgmt.resource import ResourceManagementClient
from azure.mgmt.compute import ComputeManagementClient
from azure.mgmt.network import NetworkManagementClient
from azure.mgmt.compute.models import DiskCreateOption

3. Next in the .py file, add variables after the import statements to specify common values used in the code:

SUBSCRIPTION_ID = 'subscription-id'
GROUP_NAME = 'myResourceGroup'
LOCATION = 'westus'
VM_NAME = 'myVM'

Replace subscription-id with your subscription identifier.


4. To create the Active Directory credentials that you need to make requests, add this function after the
variables in the .py file:

def get_credentials():
credentials = ServicePrincipalCredentials(
client_id = 'application-id',
secret = 'authentication-key',
tenant = 'tenant-id'
)

return credentials

Replace application-id, authentication-key, and tenant-id with the values that you previously collected
when you created your Azure Active Directory service principal.
5. To call the function that you previously added, add this code under the if statement at the end of the .py file:

credentials = get_credentials()

Create resources
Initialize management clients
Management clients are needed to create and manage resources using the Python SDK in Azure. To create the
management clients, add this code under the if statement at then end of the .py file:

resource_group_client = ResourceManagementClient(
credentials,
SUBSCRIPTION_ID
)
network_client = NetworkManagementClient(
credentials,
SUBSCRIPTION_ID
)
compute_client = ComputeManagementClient(
credentials,
SUBSCRIPTION_ID
)

Create the VM and supporting resources


All resources must be contained in a Resource group.
1. To create a resource group, add this function after the variables in the .py file:

def create_resource_group(resource_group_client):
resource_group_params = { 'location':LOCATION }
resource_group_result = resource_group_client.resource_groups.create_or_update(
GROUP_NAME,
resource_group_params
)

2. To call the function that you previously added, add this code under the if statement at the end of the .py file:

create_resource_group(resource_group_client)
input('Resource group created. Press enter to continue...')

Availability sets make it easier for you to maintain the virtual machines used by your application.
1. To create an availability set, add this function after the variables in the .py file:

def create_availability_set(compute_client):
avset_params = {
'location': LOCATION,
'sku': { 'name': 'Aligned' },
'platform_fault_domain_count': 3
}
availability_set_result = compute_client.availability_sets.create_or_update(
GROUP_NAME,
'myAVSet',
avset_params
)

2. To call the function that you previously added, add this code under the if statement at the end of the .py file:

create_availability_set(compute_client)
print("------------------------------------------------------")
input('Availability set created. Press enter to continue...')

A Public IP address is needed to communicate with the virtual machine.


1. To create a public IP address for the virtual machine, add this function after the variables in the .py file:

def create_public_ip_address(network_client):
public_ip_addess_params = {
'location': LOCATION,
'public_ip_allocation_method': 'Dynamic'
}
creation_result = network_client.public_ip_addresses.create_or_update(
GROUP_NAME,
'myIPAddress',
public_ip_addess_params
)

return creation_result.result()

2. To call the function that you previously added, add this code under the if statement at the end of the .py file:
creation_result = create_public_ip_address(network_client)
print("------------------------------------------------------")
print(creation_result)
input('Press enter to continue...')

A virtual machine must be in a subnet of a Virtual network.


1. To create a virtual network, add this function after the variables in the .py file:

def create_vnet(network_client):
vnet_params = {
'location': LOCATION,
'address_space': {
'address_prefixes': ['10.0.0.0/16']
}
}
creation_result = network_client.virtual_networks.create_or_update(
GROUP_NAME,
'myVNet',
vnet_params
)
return creation_result.result()

2. To call the function that you previously added, add this code under the if statement at the end of the .py file:

creation_result = create_vnet(network_client)
print("------------------------------------------------------")
print(creation_result)
input('Press enter to continue...')

3. To add a subnet to the virtual network, add this function after the variables in the .py file:

def create_subnet(network_client):
subnet_params = {
'address_prefix': '10.0.0.0/24'
}
creation_result = network_client.subnets.create_or_update(
GROUP_NAME,
'myVNet',
'mySubnet',
subnet_params
)

return creation_result.result()

4. To call the function that you previously added, add this code under the if statement at the end of the .py file:

creation_result = create_subnet(network_client)
print("------------------------------------------------------")
print(creation_result)
input('Press enter to continue...')

A virtual machine needs a network interface to communicate on the virtual network.


1. To create a network interface, add this function after the variables in the .py file:
def create_nic(network_client):
subnet_info = network_client.subnets.get(
GROUP_NAME,
'myVNet',
'mySubnet'
)
publicIPAddress = network_client.public_ip_addresses.get(
GROUP_NAME,
'myIPAddress'
)
nic_params = {
'location': LOCATION,
'ip_configurations': [{
'name': 'myIPConfig',
'public_ip_address': publicIPAddress,
'subnet': {
'id': subnet_info.id
}
}]
}
creation_result = network_client.network_interfaces.create_or_update(
GROUP_NAME,
'myNic',
nic_params
)

return creation_result.result()

2. To call the function that you previously added, add this code under the if statement at the end of the .py file:

creation_result = create_nic(network_client)
print("------------------------------------------------------")
print(creation_result)
input('Press enter to continue...')

Now that you created all the supporting resources, you can create a virtual machine.
1. To create the virtual machine, add this function after the variables in the .py file:
def create_vm(network_client, compute_client):
nic = network_client.network_interfaces.get(
GROUP_NAME,
'myNic'
)
avset = compute_client.availability_sets.get(
GROUP_NAME,
'myAVSet'
)
vm_parameters = {
'location': LOCATION,
'os_profile': {
'computer_name': VM_NAME,
'admin_username': 'azureuser',
'admin_password': 'Azure12345678'
},
'hardware_profile': {
'vm_size': 'Standard_DS1'
},
'storage_profile': {
'image_reference': {
'publisher': 'MicrosoftWindowsServer',
'offer': 'WindowsServer',
'sku': '2012-R2-Datacenter',
'version': 'latest'
}
},
'network_profile': {
'network_interfaces': [{
'id': nic.id
}]
},
'availability_set': {
'id': avset.id
}
}
creation_result = compute_client.virtual_machines.create_or_update(
GROUP_NAME,
VM_NAME,
vm_parameters
)

return creation_result.result()

NOTE
This tutorial creates a virtual machine running a version of the Windows Server operating system. To learn more
about selecting other images, see Navigate and select Azure virtual machine images with Windows PowerShell and
the Azure CLI.

2. To call the function that you previously added, add this code under the if statement at the end of the .py file:

creation_result = create_vm(network_client, compute_client)


print("------------------------------------------------------")
print(creation_result)
input('Press enter to continue...')

Perform management tasks


During the lifecycle of a virtual machine, you may want to run management tasks such as starting, stopping, or
deleting a virtual machine. Additionally, you may want to create code to automate repetitive or complex tasks.
Get information about the VM
1. To get information about the virtual machine, add this function after the variables in the .py file:

def get_vm(compute_client):
vm = compute_client.virtual_machines.get(GROUP_NAME, VM_NAME, expand='instanceView')
print("hardwareProfile")
print(" vmSize: ", vm.hardware_profile.vm_size)
print("\nstorageProfile")
print(" imageReference")
print(" publisher: ", vm.storage_profile.image_reference.publisher)
print(" offer: ", vm.storage_profile.image_reference.offer)
print(" sku: ", vm.storage_profile.image_reference.sku)
print(" version: ", vm.storage_profile.image_reference.version)
print(" osDisk")
print(" osType: ", vm.storage_profile.os_disk.os_type.value)
print(" name: ", vm.storage_profile.os_disk.name)
print(" createOption: ", vm.storage_profile.os_disk.create_option.value)
print(" caching: ", vm.storage_profile.os_disk.caching.value)
print("\nosProfile")
print(" computerName: ", vm.os_profile.computer_name)
print(" adminUsername: ", vm.os_profile.admin_username)
print(" provisionVMAgent: {0}".format(vm.os_profile.windows_configuration.provision_vm_agent))
print(" enableAutomaticUpdates:
{0}".format(vm.os_profile.windows_configuration.enable_automatic_updates))
print("\nnetworkProfile")
for nic in vm.network_profile.network_interfaces:
print(" networkInterface id: ", nic.id)
print("\nvmAgent")
print(" vmAgentVersion", vm.instance_view.vm_agent.vm_agent_version)
print(" statuses")
for stat in vm_result.instance_view.vm_agent.statuses:
print(" code: ", stat.code)
print(" displayStatus: ", stat.display_status)
print(" message: ", stat.message)
print(" time: ", stat.time)
print("\ndisks");
for disk in vm.instance_view.disks:
print(" name: ", disk.name)
print(" statuses")
for stat in disk.statuses:
print(" code: ", stat.code)
print(" displayStatus: ", stat.display_status)
print(" time: ", stat.time)
print("\nVM general status")
print(" provisioningStatus: ", vm.provisioning_state)
print(" id: ", vm.id)
print(" name: ", vm.name)
print(" type: ", vm.type)
print(" location: ", vm.location)
print("\nVM instance status")
for stat in vm.instance_view.statuses:
print(" code: ", stat.code)
print(" displayStatus: ", stat.display_status)

2. To call the function that you previously added, add this code under the if statement at the end of the .py file:

get_vm(compute_client)
print("------------------------------------------------------")
input('Press enter to continue...')

Stop the VM
You can stop a virtual machine and keep all its settings, but continue to be charged for it, or you can stop a virtual
machine and deallocate it. When a virtual machine is deallocated, all resources associated with it are also
deallocated and billing ends for it.
1. To stop the virtual machine without deallocating it, add this function after the variables in the .py file:

def stop_vm(compute_client):
compute_client.virtual_machines.power_off(GROUP_NAME, VM_NAME)

If you want to deallocate the virtual machine, change the power_off call to this code:

compute_client.virtual_machines.deallocate(GROUP_NAME, VM_NAME)

2. To call the function that you previously added, add this code under the if statement at the end of the .py file:

stop_vm(compute_client)
input('Press enter to continue...')

Start the VM
1. To start the virtual machine, add this function after the variables in the .py file:

def start_vm(compute_client):
compute_client.virtual_machines.start(GROUP_NAME, VM_NAME)

2. To call the function that you previously added, add this code under the if statement at the end of the .py file:

start_vm(compute_client)
input('Press enter to continue...')

Resize the VM
Many aspects of deployment should be considered when deciding on a size for your virtual machine. For more
information, see VM sizes.
1. To change the size of the virtual machine, add this function after the variables in the .py file:

def update_vm(compute_client):
vm = compute_client.virtual_machines.get(GROUP_NAME, VM_NAME)
vm.hardware_profile.vm_size = 'Standard_DS3'
update_result = compute_client.virtual_machines.create_or_update(
GROUP_NAME,
VM_NAME,
vm
)

return update_result.result()

2. To call the function that you previously added, add this code under the if statement at the end of the .py file:

update_result = update_vm(compute_client)
print("------------------------------------------------------")
print(update_result)
input('Press enter to continue...')

Add a data disk to the VM


Virtual machines can have one or more data disks that are stored as VHDs.
1. To add a data disk to the virtual machine, add this function after the variables in the .py file:

def add_datadisk(compute_client):
disk_creation = compute_client.disks.create_or_update(
GROUP_NAME,
'myDataDisk1',
{
'location': LOCATION,
'disk_size_gb': 1,
'creation_data': {
'create_option': DiskCreateOption.empty
}
}
)
data_disk = disk_creation.result()
vm = compute_client.virtual_machines.get(GROUP_NAME, VM_NAME)
add_result = vm.storage_profile.data_disks.append({
'lun': 1,
'name': 'myDataDisk1',
'create_option': DiskCreateOption.attach,
'managed_disk': {
'id': data_disk.id
}
})
add_result = compute_client.virtual_machines.create_or_update(
GROUP_NAME,
VM_NAME,
vm)

return add_result.result()

2. To call the function that you previously added, add this code under the if statement at the end of the .py file:

add_result = add_datadisk(compute_client)
print("------------------------------------------------------")
print(add_result)
input('Press enter to continue...')

Delete resources
Because you are charged for resources used in Azure, it's always a good practice to delete resources that are no
longer needed. If you want to delete the virtual machines and all the supporting resources, all you have to do is
delete the resource group.
1. To delete the resource group and all resources, add this function after the variables in the .py file:

def delete_resources(resource_group_client):
resource_group_client.resource_groups.delete(GROUP_NAME)

2. To call the function that you previously added, add this code under the if statement at the end of the .py file:

delete_resources(resource_group_client)

3. Save myPythonProject.py.

Run the application


1. To run the console application, click Start in Visual Studio.
2. Press Enter after the status of each resource is returned. In the status information, you should see a
Succeeded provisioning state. After the virtual machine is created, you have the opportunity to delete all
the resources that you create. Before you press Enter to start deleting resources, you could take a few
minutes to verify their creation in the Azure portal. If you have the Azure portal open, you might have to
refresh the blade to see new resources.
It should take about five minutes for this console application to run completely from start to finish. It may
take several minutes after the application has finished before all the resources and the resource group are
deleted.

Next steps
If there were issues with the deployment, a next step would be to look at Troubleshooting resource group
deployments with Azure portal
Learn more about the Azure Python Library
Create a Windows virtual machine from a Resource
Manager template
11/13/2019 • 4 minutes to read • Edit Online

Learn how to create a Windows virtual machine by using an Azure Resource Manager template and Azure
PowerShell from the Azure Cloud shell. The template used in this article deploys a single virtual machine running
Windows Server in a new virtual network with a single subnet. For creating a Linux virtual machine, see How to
create a Linux virtual machine with Azure Resource Manager templates.

Create a virtual machine


Creating an Azure virtual machine usually includes two steps:
Create a resource group. An Azure resource group is a logical container into which Azure resources are
deployed and managed. A resource group must be created before a virtual machine.
Create a virtual machine.
The following example creates a VM from an Azure Quickstart template. Here is a copy of the template:

{
"$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
"contentVersion": "1.0.0.0",
"parameters": {
"adminUsername": {
"type": "string",
"metadata": {
"description": "Username for the Virtual Machine."
}
},
"adminPassword": {
"type": "securestring",
"metadata": {
"description": "Password for the Virtual Machine."
}
},
"dnsLabelPrefix": {
"type": "string",
"metadata": {
"description": "Unique DNS Name for the Public IP used to access the Virtual Machine."
}
},
"windowsOSVersion": {
"type": "string",
"defaultValue": "2016-Datacenter",
"allowedValues": [
"2008-R2-SP1",
"2012-Datacenter",
"2012-R2-Datacenter",
"2016-Nano-Server",
"2016-Datacenter-with-Containers",
"2016-Datacenter",
"2019-Datacenter"
],
"metadata": {
"description": "The Windows version for the VM. This will pick a fully patched image of this given
Windows version."
}
},
},
"vmSize": {
"type": "string",
"defaultValue": "Standard_A2_v2",
"metadata": {
"description": "Size of the virtual machine."
}
},
"location": {
"type": "string",
"defaultValue": "[resourceGroup().location]",
"metadata": {
"description": "Location for all resources."
}
}
},
"variables": {
"storageAccountName": "[concat(uniquestring(resourceGroup().id), 'sawinvm')]",
"nicName": "myVMNic",
"addressPrefix": "10.0.0.0/16",
"subnetName": "Subnet",
"subnetPrefix": "10.0.0.0/24",
"publicIPAddressName": "myPublicIP",
"vmName": "SimpleWinVM",
"virtualNetworkName": "MyVNET",
"subnetRef": "[resourceId('Microsoft.Network/virtualNetworks/subnets', variables('virtualNetworkName'),
variables('subnetName'))]",
"networkSecurityGroupName": "default-NSG"
},
"resources": [
{
"type": "Microsoft.Storage/storageAccounts",
"apiVersion": "2018-11-01",
"name": "[variables('storageAccountName')]",
"location": "[parameters('location')]",
"sku": {
"name": "Standard_LRS"
},
"kind": "Storage",
"properties": {}
},
{
"type": "Microsoft.Network/publicIPAddresses",
"apiVersion": "2018-11-01",
"name": "[variables('publicIPAddressName')]",
"location": "[parameters('location')]",
"properties": {
"publicIPAllocationMethod": "Dynamic",
"dnsSettings": {
"domainNameLabel": "[parameters('dnsLabelPrefix')]"
}
}
},
{
"comments": "Default Network Security Group for template",
"type": "Microsoft.Network/networkSecurityGroups",
"apiVersion": "2019-08-01",
"name": "[variables('networkSecurityGroupName')]",
"location": "[parameters('location')]",
"properties": {
"securityRules": [
{
"name": "default-allow-3389",
"properties": {
"priority": 1000,
"access": "Allow",
"direction": "Inbound",
"destinationPortRange": "3389",
"protocol": "Tcp",
"sourcePortRange": "*",
"sourcePortRange": "*",
"sourceAddressPrefix": "*",
"destinationAddressPrefix": "*"
}
}
]
}
},
{
"type": "Microsoft.Network/virtualNetworks",
"apiVersion": "2018-11-01",
"name": "[variables('virtualNetworkName')]",
"location": "[parameters('location')]",
"dependsOn": [
"[resourceId('Microsoft.Network/networkSecurityGroups', variables('networkSecurityGroupName'))]"
],
"properties": {
"addressSpace": {
"addressPrefixes": [
"[variables('addressPrefix')]"
]
},
"subnets": [
{
"name": "[variables('subnetName')]",
"properties": {
"addressPrefix": "[variables('subnetPrefix')]",
"networkSecurityGroup": {
"id": "[resourceId('Microsoft.Network/networkSecurityGroups',
variables('networkSecurityGroupName'))]"
}
}
}
]
}
},
{
"type": "Microsoft.Network/networkInterfaces",
"apiVersion": "2018-11-01",
"name": "[variables('nicName')]",
"location": "[parameters('location')]",
"dependsOn": [
"[resourceId('Microsoft.Network/publicIPAddresses/', variables('publicIPAddressName'))]",
"[resourceId('Microsoft.Network/virtualNetworks/', variables('virtualNetworkName'))]"
],
"properties": {
"ipConfigurations": [
{
"name": "ipconfig1",
"properties": {
"privateIPAllocationMethod": "Dynamic",
"publicIPAddress": {
"id": "[resourceId('Microsoft.Network/publicIPAddresses',variables('publicIPAddressName'))]"
},
"subnet": {
"id": "[variables('subnetRef')]"
}
}
}
]
}
},
{
"type": "Microsoft.Compute/virtualMachines",
"apiVersion": "2018-10-01",
"name": "[variables('vmName')]",
"location": "[parameters('location')]",
"dependsOn": [
"[resourceId('Microsoft.Storage/storageAccounts/', variables('storageAccountName'))]",
"[resourceId('Microsoft.Network/networkInterfaces/', variables('nicName'))]"
"[resourceId('Microsoft.Network/networkInterfaces/', variables('nicName'))]"
],
"properties": {
"hardwareProfile": {
"vmSize": "[parameters('vmSize')]"
},
"osProfile": {
"computerName": "[variables('vmName')]",
"adminUsername": "[parameters('adminUsername')]",
"adminPassword": "[parameters('adminPassword')]"
},
"storageProfile": {
"imageReference": {
"publisher": "MicrosoftWindowsServer",
"offer": "WindowsServer",
"sku": "[parameters('windowsOSVersion')]",
"version": "latest"
},
"osDisk": {
"createOption": "FromImage"
},
"dataDisks": [
{
"diskSizeGB": 1023,
"lun": 0,
"createOption": "Empty"
}
]
},
"networkProfile": {
"networkInterfaces": [
{
"id": "[resourceId('Microsoft.Network/networkInterfaces',variables('nicName'))]"
}
]
},
"diagnosticsProfile": {
"bootDiagnostics": {
"enabled": true,
"storageUri": "[reference(resourceId('Microsoft.Storage/storageAccounts/',
variables('storageAccountName'))).primaryEndpoints.blob]"
}
}
}
}
],
"outputs": {
"hostname": {
"type": "string",
"value": "[reference(variables('publicIPAddressName')).dnsSettings.fqdn]"
}
}
}

To run the PowerShell script, Select Try it to open the Azure Cloud shell. To paste the script, right-click the shell,
and then select Paste:
$resourceGroupName = Read-Host -Prompt "Enter the Resource Group name"
$location = Read-Host -Prompt "Enter the location (i.e. centralus)"
$adminUsername = Read-Host -Prompt "Enter the administrator username"
$adminPassword = Read-Host -Prompt "Enter the administrator password" -AsSecureString
$dnsLabelPrefix = Read-Host -Prompt "Enter an unique DNS name for the public IP"

New-AzResourceGroup -Name $resourceGroupName -Location "$location"


New-AzResourceGroupDeployment `
-ResourceGroupName $resourceGroupName `
-TemplateUri "https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/101-vm-simple-
windows/azuredeploy.json" `
-adminUsername $adminUsername `
-adminPassword $adminPassword `
-dnsLabelPrefix $dnsLabelPrefix

(Get-AzVm -ResourceGroupName $resourceGroupName).name

If you choose to install and use the PowerShell locally instead of from the Azure Cloud shell, this tutorial requires
the Azure PowerShell module. Run Get-Module -ListAvailable Az to find the version. If you need to upgrade, see
Install Azure PowerShell module. If you're running PowerShell locally, you also need to run Connect-AzAccount to
create a connection with Azure.
In the previous example, you specified a template stored in GitHub. You can also download or create a template
and specify the local path with the --template-file parameter.
Here are some additional resources:
To learn how to develop Resource Manager templates, see Azure Resource Manager documentation.
To see the Azure virtual machine schemas, see Azure template reference.
To see more virtual machine template samples, see Azure Quickstart templates.

Connect to the virtual machine


The last PowerShell command from the previous script shows the virtual machine name. To connect to the virtual
machine, see How to connect and sign on to an Azure virtual machine running Windows.

Next Steps
If there were issues with the deployment, you might take a look at Troubleshoot common Azure deployment
errors with Azure Resource Manager.
Learn how to create and manage a virtual machine in Create and manage Windows VMs with the Azure
PowerShell module.
To learn more about creating templates, view the JSON syntax and properties for the resources types you
deployed:
Microsoft.Network/publicIPAddresses
Microsoft.Network/virtualNetworks
Microsoft.Network/networkInterfaces
Microsoft.Compute/virtualMachines
How to connect and sign on to an Azure virtual
machine running Windows
12/4/2019 • 2 minutes to read • Edit Online

You'll use the Connect button in the Azure portal to start a Remote Desktop (RDP ) session from a Windows
desktop. First you connect to the virtual machine, and then you sign on.
To connect to a Windows VM from a Mac, you will need to install an RDP client for Mac such as Microsoft
Remote Desktop.

Connect to the virtual machine


1. Go to the Azure portal to connect to a VM. Search for and select Virtual machines.
2. Select the virtual machine from the list.
3. At the beginning of the virtual machine page, select Connect.
4. On the Connect to virtual machine page, select RDP, and then select the appropriate IP address and
Port number. In most cases, the default IP address and port should be used. Select Download RDP File.
If the VM has a just-in-time policy set, you first need to select the Request access button to request access
before you can download the RDP file. For more information about the just-in-time policy, see Manage
virtual machine access using the just in time policy.
5. Open the downloaded RDP file and select Connect when prompted. You will get a warning that the .rdp
file is from an unknown publisher. This is expected. In the Remote Desktop Connection window, select
Connect to continue.

6. In the Windows Security window, select More choices and then Use a different account. Enter the
credentials for an account on the virtual machine and then select OK.
Local account: This is usually the local account user name and password that you specified when you
created the virtual machine. In this case, the domain is the name of the virtual machine and it is entered as
vmname\username.
Domain joined VM: If the VM belongs to a domain, enter the user name in the format
Domain\Username. The account also needs to either be in the Administrators group or have been granted
remote access privileges to the VM.
Domain controller: If the VM is a domain controller, enter the user name and password of a domain
administrator account for that domain.
7. Select Yes to verify the identity of the virtual machine and finish logging on.

TIP
If the Connect button in the portal is grayed-out and you are not connected to Azure via an Express Route or Site-
to-Site VPN connection, you will need to create and assign your VM a public IP address before you can use RDP. For
more information, see Public IP addresses in Azure.

Connect to the virtual machine using PowerShell


If you are using PowerShell and have the Azure PowerShell module installed you may also connect using the
Get-AzRemoteDesktopFile cmdlet, as shown below.

This example will immediately launch the RDP connection, taking you through similar prompts as above.

Get-AzRemoteDesktopFile -ResourceGroupName "RgName" -Name "VmName" -Launch

You may also save the RDP file for future use.

Get-AzRemoteDesktopFile -ResourceGroupName "RgName" -Name "VmName" -LocalPath "C:\Path\to\folder"

Next steps
If you have difficulty connecting, see Troubleshoot Remote Desktop connections.
Azure Hybrid Benefit for Windows Server
12/23/2019 • 5 minutes to read • Edit Online

For customers with Software Assurance, Azure Hybrid Benefit for Windows Server allows you to use your on-
premises Windows Server licenses and run Windows virtual machines on Azure at a reduced cost. You can use
Azure Hybrid Benefit for Windows Server to deploy new virtual machines with Windows OS. This article goes
over the steps on how to deploy new VMs with Azure Hybrid Benefit for Windows Server and how you can update
existing running VMs. For more information about Azure Hybrid Benefit for Windows Server licensing and cost
savings, see the Azure Hybrid Benefit for Windows Server licensing page.

IMPORTANT
Each 2-processor license or each set of 16-core licenses are entitled to two instances of up to 8 cores, or one instance of up
to 16 cores. The Azure Hybrid Benefit for Standard Edition licenses can only be used once either on-premises or in Azure.
Datacenter Edition benefits allow for simultaneous usage both on-premises and in Azure.

IMPORTANT
Using Azure Hybrid Benefit for Windows Server with any VMs running Windows Server OS are now supported in all regions,
including VMs with additional software such as SQL Server or third-party marketplace software.

NOTE
For classic VMs, only deploying new VM from on premises custom images is supported. To take advantage of the capabilities
supported in this article, you must first migrate classic VMs to Resource Manager model.

Ways to use Azure Hybrid Benefit for Windows Server


There are few ways to use Windows virtual machines with the Azure Hybrid Benefit:
1. You can deploy VMs from one of the provided Windows Server images on the Azure Marketplace
2. You can upload a custom VM and deploy using a Resource Manager template or Azure PowerShell
3. You can toggle and convert existing VM between running with Azure Hybrid Benefit or pay on-demand cost for
Windows Server
4. You can also apply Azure Hybrid Benefit for Windows Server on virtual machine scale set as well

Create a VM with Azure Hybrid Benefit for Windows Server


All Windows Server OS based images are supported for Azure Hybrid Benefit for Windows Server. You can use
Azure platform support images or upload your own custom Windows Server images.
Portal
To create a VM with Azure Hybrid Benefit for Windows Server, use the toggle under the "Save money" section.
PowerShell
New-AzVm `
-ResourceGroupName "myResourceGroup" `
-Name "myVM" `
-Location "East US" `
-ImageName "Win2016Datacenter" `
-LicenseType "Windows_Server"

CLI

az vm create \
--resource-group myResourceGroup \
--name myVM \
--location eastus \
--license-type Windows_Server

Template
Within your Resource Manager templates, an additional parameter licenseType must be specified. You can read
more about authoring Azure Resource Manager templates

"properties": {
"licenseType": "Windows_Server",
"hardwareProfile": {
"vmSize": "[variables('vmSize')]"
}

Convert an existing VM using Azure Hybrid Benefit for Windows Server


If you have an existing VM that you would like to convert to take advantage of Azure Hybrid Benefit for Windows
Server, you can update your VM's license type by following the instructions below.

NOTE
Changing the license type on the VM does not cause the system to reboot or cause a service interuption. It is simply an
update to a metadata flag.

Portal
From portal VM blade, you can update the VM to use Azure Hybrid Benefit by selecting "Configuration" option
and toggle the "Azure hybrid benefit" option
PowerShell
Convert existing Windows Server VMs to Azure Hybrid Benefit for Windows Server

$vm = Get-AzVM -ResourceGroup "rg-name" -Name "vm-name"


$vm.LicenseType = "Windows_Server"
Update-AzVM -ResourceGroupName rg-name -VM $vm

Convert Windows Server VMs with benefit back to pay-as-you-go

$vm = Get-AzVM -ResourceGroup "rg-name" -Name "vm-name"


$vm.LicenseType = "None"
Update-AzVM -ResourceGroupName rg-name -VM $vm

CLI
Convert existing Windows Server VMs to Azure Hybrid Benefit for Windows Server

az vm update --resource-group myResourceGroup --name myVM --set licenseType=Windows_Server

How to verify your VM is utilizing the licensing benefit


Once you have deployed your VM through either PowerShell, Resource Manager template or portal, you can
verify the setting in the following methods.
Portal
From portal VM blade, you can view the toggle for Azure Hybrid Benefit for Windows Server by selecting
"Configuration" tab.
PowerShell
The following example shows the license type for a single VM

Get-AzVM -ResourceGroup "myResourceGroup" -Name "myVM"

Output:

Type : Microsoft.Compute/virtualMachines
Location : westus
LicenseType : Windows_Server

This output contrasts with the following VM deployed without Azure Hybrid Benefit for Windows Server licensing:

Type : Microsoft.Compute/virtualMachines
Location : westus
LicenseType :

CLI

az vm get-instance-view -g MyResourceGroup -n MyVM --query "[?licenseType=='Windows_Server']" -o table

NOTE
Changing the license type on the VM does not cause the system to reboot or cause a service interuption. It is a metadata
licensing flag only.

List all VMs with Azure Hybrid Benefit for Windows Server in a
subscription
To see and count all virtual machines deployed with Azure Hybrid Benefit for Windows Server, you can run the
following command from your subscription:
Portal
From the Virtual Machine or Virtual machine scale sets resource blade, you can view a list of all your VM (s) and
licensing type by configuring the table column to include "Azure Hybrid Benefit". The VM setting can either be in
"Enabled", "Not enabled" or "Not supported" state.
PowerShell
$vms = Get-AzVM
$vms | ?{$_.LicenseType -like "Windows_Server"} | select ResourceGroupName, Name, LicenseType

CLI

az vm list --query "[?licenseType=='Windows_Server']" -o table

Deploy a Virtual Machine Scale Set with Azure Hybrid Benefit for
Windows Server
Within your virtual machine scale set Resource Manager templates, an additional parameter licenseType must be
specified within your VirtualMachineProfile property. You can do this during create or update for your scale set
through ARM template, PowerShell, Azure CLI or REST.
The following example uses ARM template with a Windows Server 2016 Datacenter image:

"virtualMachineProfile": {
"storageProfile": {
"osDisk": {
"createOption": "FromImage"
},
"imageReference": {
"publisher": "MicrosoftWindowsServer",
"offer": "WindowsServer",
"sku": "2016-Datacenter",
"version": "latest"
}
},
"licenseType": "Windows_Server",
"osProfile": {
"computerNamePrefix": "[parameters('vmssName')]",
"adminUsername": "[parameters('adminUsername')]",
"adminPassword": "[parameters('adminPassword')]"
}

You can also learn more about how to Modify a virtual machine scale set for more ways to update your scale set.

Next steps
Read more about How to save money with the Azure Hybrid Benefit
Read more about Frequently asked questions for Azure Hybrid Benefit
Learn more about Azure Hybrid Benefit for Windows Server licensing detailed guidance
Learn more about Azure Hybrid Benefit for Windows Server and Azure Site Recovery make migrating
applications to Azure even more cost-effective
Learn more about Windows 10 on Azure with Multitenant Hosting Right
Learn more about Using Resource Manager templates
How to deploy Windows 10 on Azure with
Multitenant Hosting Rights
8/28/2019 • 3 minutes to read • Edit Online

For customers with Windows 10 Enterprise E3/E5 per user or Windows Virtual Desktop Access per user (User
Subscription Licenses or Add-on User Subscription Licenses), Multitenant Hosting Rights for Windows 10 allows
you to bring your Windows 10 Licenses to the cloud and run Windows 10 Virtual Machines on Azure without
paying for another license. For more information, please see Multitenant Hosting for Windows 10.

NOTE
This article shows you to implement the licensing benefit for Windows 10 Pro Desktop images on Azure Marketplace.
For Windows 7, 8.1, 10 Enterprise (x64) images on Azure Marketplace for MSDN Subscriptions, please refer to Windows
client in Azure for dev/test scenarios
For Windows Server licensing benefits, please refer to Azure Hybrid use benefits for Windows Server images.

Deploying Windows 10 Image from Azure Marketplace


For Powershell, CLI and Azure Resource Manager template deployments, the Windows 10 image can be found
with the following publishername, offer, sku.

OS PUBLISHERNAME OFFER SKU

Windows 10 Pro MicrosoftWindowsDesktop Windows-10 RS2-Pro

Windows 10 Pro N MicrosoftWindowsDesktop Windows-10 RS2-ProN

Windows 10 Pro MicrosoftWindowsDesktop Windows-10 RS3-Pro

Windows 10 Pro N MicrosoftWindowsDesktop Windows-10 RS3-ProN

Uploading Windows 10 VHD to Azure


if you are uploading a generalized Windows 10 VHD, please note Windows 10 does not have built-in
administrator account enabled by default. To enable the built-in administrator account, include the following
command as part of the Custom Script extension.

Net user <username> /active:yes

The following powershell snippet is to mark all administrator accounts as active, including the built-in
administrator. This example is useful if the built-in administrator username is unknown.
$adminAccount = Get-WmiObject Win32_UserAccount -filter "LocalAccount=True" | ? {$_.SID -Like "S-1-5-21-*-500"}
if($adminAccount.Disabled)
{
$adminAccount.Disabled = $false
$adminAccount.Put()
}

For more information:


How to upload VHD to Azure
How to prepare a Windows VHD to upload to Azure

Deploying Windows 10 with Multitenant Hosting Rights


Make sure you have installed and configured the latest Azure PowerShell. Once you have prepared your VHD,
upload the VHD to your Azure Storage account using the Add-AzVhd cmdlet as follows:

Add-AzVhd -ResourceGroupName "myResourceGroup" -LocalFilePath "C:\Path\To\myvhd.vhd" `


-Destination "https://mystorageaccount.blob.core.windows.net/vhds/myvhd.vhd"

Deploy using Azure Resource Manager Template Deployment Within your Resource Manager templates, an
additional parameter for licenseType can be specified. You can read more about authoring Azure Resource
Manager templates. Once you have your VHD uploaded to Azure, edit you Resource Manager template to include
the license type as part of the compute provider and deploy your template as normal:

"properties": {
"licenseType": "Windows_Client",
"hardwareProfile": {
"vmSize": "[variables('vmSize')]"
}

Deploy via PowerShell When deploying your Windows Server VM via PowerShell, you have an additional
parameter for -LicenseType . Once you have your VHD uploaded to Azure, you create a VM using New-AzVM and
specify the licensing type as follows:

New-AzVM -ResourceGroupName "myResourceGroup" -Location "West US" -VM $vm -LicenseType "Windows_Client"

Verify your VM is utilizing the licensing benefit


Once you have deployed your VM through either the PowerShell or Resource Manager deployment method, verify
the license type with Get-AzVM as follows:

Get-AzVM -ResourceGroup "myResourceGroup" -Name "myVM"

The output is similar to the following example for Windows 10 with correct license type:

Type : Microsoft.Compute/virtualMachines
Location : westus
LicenseType : Windows_Client

This output contrasts with the following VM deployed without Azure Hybrid Use Benefit licensing, such as a VM
deployed straight from the Azure Gallery:
Type : Microsoft.Compute/virtualMachines
Location : westus
LicenseType :

Additional Information about joining Azure AD


NOTE
Azure provisions all Windows VMs with built-in administrator account, which cannot be used to join AAD. For example,
Settings > Account > Access Work or School > +Connect will not work. You must create and log on as a second
administrator account to join Azure AD manually. You can also configure Azure AD using a provisioning package, use the link
is the Next Steps section to learn more.

Next Steps
Learn more about Configuring VDA for Windows 10
Learn more about Multitenant Hosting for Windows 10
Security recommendations for Windows virtual
machines in Azure
11/13/2019 • 3 minutes to read • Edit Online

This article contains security recommendations for Azure Virtual Machines. Follow these recommendations to help
fulfill the security obligations described in our model for shared responsibility. The recommendations will also help
you improve overall security for your web app solutions. For more information about what Microsoft does to fulfill
service-provider responsibilities, see Shared responsibilities for cloud computing.
Some of this article's recommendations can be automatically addressed by Azure Security Center. Azure Security
Center is the first line of defense for your resources in Azure. It periodically analyzes the security state of your
Azure resources to identify potential security vulnerabilities. It then recommends how to address the vulnerabilities.
For more information, see Security recommendations in Azure Security Center.
For general information about Azure Security Center, see What is Azure Security Center?.

General
RECOMMENDATION COMMENTS SECURITY CENTER

When you build custom VM images, Before you create images, install the -
apply the latest updates. latest updates for the operating system
and for all applications that will be part
of your image.

Keep your VMs current. You can use the Update Management Yes
solution in Azure Automation to
manage operating system updates for
your Windows and Linux computers in
Azure.

Back up your VMs. Azure Backup helps protect your -


application data and has minimal
operating costs. Application errors can
corrupt your data, and human errors
can introduce bugs into your
applications. Azure Backup protects
your VMs that run Windows and Linux.

Use multiple VMs for greater resilience If your VM runs applications that must -
and availability. be highly available, use multiple VMs or
availability sets.

Adopt a business continuity and Azure Site Recovery allows you to -


disaster recovery (BCDR) strategy. choose from different options designed
to support business continuity. It
supports different replication and
failover scenarios. For more information,
see About Site Recovery.

Data security
RECOMMENDATION COMMENTS SECURITY CENTER

Encrypt operating system disks. Azure Disk Encryption helps you Yes
encrypt your Windows and Linux IaaS
VM disks. Without the necessary keys,
the contents of encrypted disks are
unreadable. Disk encryption protects
stored data from unauthorized access
that would otherwise be possible if the
disk were copied.

Encrypt data disks. Azure Disk Encryption helps you -


encrypt your Windows and Linux IaaS
VM disks. Without the necessary keys,
the contents of encrypted disks are
unreadable. Disk encryption protects
stored data from unauthorized access
that would otherwise be possible if the
disk were copied.

Limit installed software. Limit installed software to what is -


required to successfully apply your
solution. This guideline helps reduce
your solution's attack surface.

Use antivirus or antimalware. In Azure, you can use antimalware -


software from security vendors such as
Microsoft, Symantec, Trend Micro, and
Kaspersky. This software helps protect
your VMs from malicious files, adware,
and other threats. You can deploy
Microsoft Antimalware based on your
application workloads. Use either basic
secure-by-default or advanced custom
configuration. For more information, see
Microsoft Antimalware for Azure Cloud
Services and Virtual Machines.

Securely store keys and secrets. Simplify the management of your -


secrets and keys by providing your
application owners with a secure,
centrally managed option. This
management reduces the risk of an
accidental compromise or leak. Azure
Key Vault can securely store your keys
in hardware security modules (HSMs)
that are certified to FIPS 140-2 Level 2.
If you need to use FIPs 140.2 Level 3 to
store your keys and secrets, you can
use Azure Dedicated HSM.

Identity and access management


RECOMMENDATION COMMENTS SECURITY CENTER

Centralize VM authentication. You can centralize the authentication of -


your Windows and Linux VMs by using
Azure Active Directory authentication.
Monitoring
RECOMMENDATION COMMENTS SECURITY CENTER

Monitor your VMs. You can use Azure Monitor for VMs to -
monitor the state of your Azure VMs
and virtual machine scale sets.
Performance issues with a VM can lead
to service disruption, which violates the
security principle of availability.

Networking
RECOMMENDATION COMMENTS SECURITY CENTER

Restrict access to management ports. Attackers scan public cloud IP ranges -


for open management ports and
attempt "easy" attacks like common
passwords and known unpatched
vulnerabilities. You can use just-in-time
(JIT) VM access to lock down inbound
traffic to your Azure VMs, reducing
exposure to attacks while providing
easy connections to VMs when they're
needed.

Limit network access. Network security groups allow you to -


restrict network access and control the
number of exposed endpoints. For more
information, see Create, change, or
delete a network security group.

Next steps
Check with your application provider to learn about additional security requirements. For more information about
developing secure applications, see Secure-development documentation.
Secure your management ports with just-in-time access
2/25/2020 • 11 minutes to read • Edit Online

If you're on Security Center's standard pricing tier (see pricing), you can lock down inbound traffic to your Azure VMs with
just-in-time (JIT) virtual machine (VM ) access. This reduces exposure to attacks while providing easy access to connect to
VMs when needed.

NOTE
Security Center just-in-time VM access currently supports only VMs deployed through Azure Resource Manager. To learn more about
the classic and Resource Manager deployment models see Azure Resource Manager vs. classic deployment.

Attack scenario
Brute force attacks commonly target management ports as a means to gain access to a VM. If successful, an attacker can take
control over the VM and establish a foothold into your environment.
One way to reduce exposure to a brute force attack is to limit the amount of time that a port is open. Management ports don't
need to be open at all times. They only need to be open while you're connected to the VM, for example to perform
management or maintenance tasks. When just-in-time is enabled, Security Center uses network security group (NSG ) and
Azure Firewall rules, which restrict access to management ports so they cannot be targeted by attackers.

How does JIT access work?


When just-in-time is enabled, Security Center locks down inbound traffic to your Azure VMs by creating an NSG rule. You
select the ports on the VM to which inbound traffic will be locked down. These ports are controlled by the just-in-time
solution.
When a user requests access to a VM, Security Center checks that the user has Role-Based Access Control (RBAC )
permissions for that VM. If the request is approved, Security Center automatically configures the Network Security Groups
(NSGs) and Azure Firewall to allow inbound traffic to the selected ports and requested source IP addresses or ranges, for the
amount of time that was specified. After the time has expired, Security Center restores the NSGs to their previous states.
Those connections that are already established are not being interrupted, however.

NOTE
If a JIT access request is approved for a VM behind an Azure Firewall, then Security Center automatically changes both the NSG and
firewall policy rules. For the amount of time that was specified, the rules allow inbound traffic to the selected ports and requested source
IP addresses or ranges. After the time is over, Security Center restores the firewall and NSG rules to their previous states.

Permissions needed to configure and use JIT


TO ENABLE A USER TO: PERMISSIONS TO SET

Configure or edit a JIT policy for a VM Assign these actions to the role:
On the scope of a subscription or resource group that is
associated with the VM:
Microsoft.Security/locations/jitNetworkAccessPolicies/write
On the scope of a subscription or resource group of VM:
Microsoft.Compute/virtualMachines/write

Request JIT access to a VM Assign these actions to the user:


On the scope of a subscription or resource group that is
associated with the VM:
Microsoft.Security/locations/jitNetworkAccessPolicies/initiate/action
On the scope of a subscription or resource group that is
associated with the VM:
Microsoft.Security/locations/jitNetworkAccessPolicies/*/read
On the scope of a subscription or resource group or VM:
Microsoft.Compute/virtualMachines/read
On the scope of a subscription or resource group or VM:
Microsoft.Network/networkInterfaces/*/read

Configure JIT on a VM
There are three ways to configure a JIT policy on a VM:
Configure JIT access in Azure Security Center
Configure JIT access in an Azure VM page
Configure a JIT policy on a VM programmatically

Configure JIT in Azure Security Center


From Security Center, you can configure a JIT policy and request access to a VM using a JIT policy
Configure JIT access on a VM in Security Center
1. Open the Security Center dashboard.
2. In the left pane, select Just-in-time VM access.
The Just-in-time VM access window opens and shows information on the state of your VMs:
Configured - VMs that have been configured to support just-in-time VM access. The data presented is for the last
week and includes for each VM the number of approved requests, last access date and time, and last user.
Recommended - VMs that can support just-in-time VM access but haven't been configured to. We recommend
that you enable just-in-time VM access control for these VMs.
No recommendation - Reasons that can cause a VM not to be recommended are:
Missing NSG - The just-in-time solution requires an NSG to be in place.
Classic VM - Security Center just-in-time VM access currently supports only VMs deployed through Azure
Resource Manager. A classic deployment is not supported by the just-in-time solution.
Other - A VM is in this category if the just-in-time solution is turned off in the security policy of the
subscription or the resource group, or if the VM is missing a public IP and doesn't have an NSG in place.
3. Select the Recommended tab.
4. Under VIRTUAL MACHINE, click the VMs that you want to enable. This puts a checkmark next to a VM.
5. Click Enable JIT on VMs. A pane opens displaying the default ports recommended by Azure Security Center:
22 - SSH
3389 - RDP
5985 - WinRM
5986 - WinRM
6. Optionally, you can add custom ports to the list:
a. Click Add. The Add port configuration window opens.
b. For each port you choose to configure, both default and custom, you can customize the following settings:
Protocol type- The protocol that is allowed on this port when a request is approved.
Allowed source IP addresses- The IP ranges that are allowed on this port when a request is approved.
Maximum request time- The maximum time window during which a specific port can be opened.
c. Click OK.
7. Click Save.

NOTE
When JIT VM Access is enabled for a VM, Azure Security Center creates "deny all inbound traffic" rules for the selected ports in the
network security groups associated and Azure Firewall with it. If other rules had been created for the selected ports, then the existing
rules take priority over the new “deny all inbound traffic” rules. If there are no existing rules on the selected ports, then the new “deny all
inbound traffic” rules take top priority in the Network Security Groups and Azure Firewall.

Request JIT access via Security Center


To request access to a VM via Security Center:
1. Under Just-in-time VM access, select the Configured tab.
2. Under Virtual Machine, click the VMs that you want to request access for. This puts a checkmark next to the VM.
The icon in the Connection Details column indicates whether JIT is enabled on the NSG or FW. If it’s enabled
on both, only the Firewall icon appears.
The Connection Details column provides the information required to connect the VM, and its open ports.

3. Click Request access. The Request access window opens.

4. Under Request access, for each VM, configure the ports that you want to open and the source IP addresses that the
port is opened on and the time window for which the port will be open. It will only be possible to request access to the
ports that are configured in the just-in-time policy. Each port has a maximum allowed time derived from the just-in-
time policy.
5. Click Open ports.
NOTE
If a user who is requesting access is behind a proxy, the option My IP may not work. You may need to define the full IP address range of
the organization.

Edit a JIT access policy via Security Center


You can change a VM's existing just-in-time policy by adding and configuring a new port to protect for that VM, or by
changing any other setting related to an already protected port.
To edit an existing just-in-time policy of a VM:
1. In the Configured tab, under VMs, select a VM to which to add a port by clicking on the three dots within the row for
that VM.
2. Select Edit.
3. Under JIT VM access configuration, you can either edit the existing settings of an already protected port or add a
new custom port.

Audit JIT access activity in Security Center


You can gain insights into VM activities using log search. To view logs:
1. Under Just-in-time VM access, select the Configured tab.
2. Under VMs, select a VM to view information about by clicking on the three dots within the row for that VM and select
Activity Log from the menu. The Activity log opens.
Activity log provides a filtered view of previous operations for that VM along with time, date, and subscription.
You can download the log information by selecting Click here to download all the items as CSV.
Modify the filters and click Apply to create a search and log.

Configure JIT access from an Azure VM's page


For your convenience, you can connect to a VM using JIT directly from within the VM's page in Security Center.
Configure JIT access on a VM via the Azure VM page
To make it easy to roll out just-in-time access across your VMs, you can set a VM to allow only just-in-time access directly
from within the VM.
1. From the Azure portal, search for and select Virtual machines.
2. Select the virtual machine you want to limit to just-in-time access.
3. In the menu, select Configuration.
4. Under Just-in-time access, select Enable just-in-time.
This enables just-in-time access for the VM using the following settings:
Windows servers:
RDP port 3389
Three hours of maximum allowed access
Allowed source IP addresses is set to Any
Linux servers:
SSH port 22
Three hours of maximum allowed access
Allowed source IP addresses is set to Any
If a VM already has just-in-time enabled, when you go to its configuration page you will be able to see that just-in-time is
enabled and you can use the link to open the policy in Azure Security Center to view and change the settings.

Request JIT access to a VM via an Azure VM's page


In the Azure portal, when you try to connect to a VM, Azure checks to see if you have a just-in-time access policy configured
on that VM.
If you have a JIT policy configured on the VM, you can click Request access to grant access in accordance with the JIT
policy set for the VM.
Access is requested with the following default parameters:
source IP: ‘Any’ (*) (cannot be changed)
time range: Three hours (cannot be changed)
port number RDP port 3389 for Windows / port 22 for Linux (can be changed)

NOTE
After a request is approved for a VM protected by Azure Firewall, Security Center provides the user with the proper
connection details (the port mapping from the DNAT table) to use to connect to the VM.

If you do not have JIT configured on a VM, you will be prompted to configure a JIT policy on it.
Configure a JIT policy on a VM programmatically
You can set up and use just-in-time via REST APIs and via PowerShell.
JIT VM access via REST APIs
The just-in-time VM access feature can be used via the Azure Security Center API. You can get information about configured
VMs, add new ones, request access to a VM, and more, via this API. See Jit Network Access Policies, to learn more about the
just-in-time REST API.
JIT VM access via PowerShell
To use the just-in-time VM access solution via PowerShell, use the official Azure Security Center PowerShell cmdlets, and
specifically Set-AzJitNetworkAccessPolicy .
The following example sets a just-in-time VM access policy on a specific VM, and sets the following:
1. Close ports 22 and 3389.
2. Set a maximum time window of 3 hours for each so they can be opened per approved request.
3. Allows the user who is requesting access to control the source IP addresses and allows the user to establish a
successful session upon an approved just-in-time access request.
Run the following in PowerShell to accomplish this:
1. Assign a variable that holds the just-in-time VM access policy for a VM:
$JitPolicy = (@{
id="/subscriptions/SUBSCRIPTIONID/resourceGroups/RESOURCEGROUP/providers/Microsoft.Compute/virtualMachines/VMNAME
"
ports=(@{
number=22;
protocol="*";
allowedSourceAddressPrefix=@("*");
maxRequestAccessDuration="PT3H"},
@{
number=3389;
protocol="*";
allowedSourceAddressPrefix=@("*");
maxRequestAccessDuration="PT3H"})})

2. Insert the VM just-in-time VM access policy to an array:

$JitPolicyArr=@($JitPolicy)

3. Configure the just-in-time VM access policy on the selected VM:

Set-AzJitNetworkAccessPolicy -Kind "Basic" -Location "LOCATION" -Name "default" -ResourceGroupName "RESOURCEGROUP"


-VirtualMachine $JitPolicyArr

Request access to a VM via PowerShell


In the following example, you can see a just-in-time VM access request to a specific VM in which port 22 is requested to be
opened for a specific IP address and for a specific amount of time:
Run the following in PowerShell:
1. Configure the VM request access properties

$JitPolicyVm1 = (@{
id="/SUBSCRIPTIONID/resourceGroups/RESOURCEGROUP/providers/Microsoft.Compute/virtualMachines/VMNAME"
ports=(@{
number=22;
endTimeUtc="2018-09-17T17:00:00.3658798Z";
allowedSourceAddressPrefix=@("IPV4ADDRESS")})})

2. Insert the VM access request parameters in an array:

$JitPolicyArr=@($JitPolicyVm1)

3. Send the request access (use the resource ID you got in step 1)

Start-AzJitNetworkAccessPolicy -ResourceId
"/subscriptions/SUBSCRIPTIONID/resourceGroups/RESOURCEGROUP/providers/Microsoft.Security/locations/LOCATION/jitNet
workAccessPolicies/default" -VirtualMachine $JitPolicyArr

For more information, see the PowerShell cmdlet documentation.

Automatic cleanup of redundant JIT rules


Whenever you update a JIT policy, a cleanup tool automatically runs to check the validity of your entire ruleset. The tool looks
for mismatches between rules in your policy and rules in the NSG. If the cleanup tool finds a mismatch, it determines the
cause and, when it's safe to do so, removes built-in rules that aren't needed any more. The cleaner never deletes rules that
you've created.
Examples scenarios when the cleaner might remove a built-in rule:
When two rules with identical definitions exist and one has a higher priority than the other (meaning, the lower priority
rule will never be used)
When a rule description includes the name of a VM which doesn't match the destination IP in the rule

Next steps
In this article, you learned how just-in-time VM access in Security Center helps you control access to your Azure virtual
machines.
To learn more about Security Center, see the following:
Setting security policies — Learn how to configure security policies for your Azure subscriptions and resource groups.
Managing security recommendations — Learn how recommendations help you protect your Azure resources.
Security health monitoring — Learn how to monitor the health of your Azure resources.
Azure Disk Encryption scenarios on Windows VMs
10/29/2019 • 11 minutes to read • Edit Online

Azure Disk Encryption uses the BitLocker external key protector to provide volume encryption for the OS and data
disks of Azure virtual machines (VMs), and is integrated with Azure Key Vault to help you control and manage the
disk encryption keys and secrets. For an overview of the service, see Azure Disk Encryption for Windows VMs.
There are many disk encryption scenarios, and the steps may vary according to the scenario. The following
sections cover the scenarios in greater detail for Windows VMs.
You can only apply disk encryption to virtual machines of supported VM sizes and operating systems. You must
also meet the following prerequisites:
Networking requirements
Group Policy requirements
Encryption key storage requirements

IMPORTANT
If you have previously used Azure Disk Encryption with Azure AD to encrypt a VM, you must continue use this option
to encrypt your VM. See Azure Disk Encryption with Azure AD (previous release) for details.
You should take a snapshot and/or create a backup before disks are encrypted. Backups ensure that a recovery
option is possible if an unexpected failure occurs during encryption. VMs with managed disks require a backup before
encryption occurs. Once a backup is made, you can use the Set-AzVMDiskEncryptionExtension cmdlet to encrypt
managed disks by specifying the -skipVmBackup parameter. For more information about how to back up and restore
encrypted VMs, see Back up and restore encrypted Azure VM.
Encrypting or disabling encryption may cause a VM to reboot.

Install tools and connect to Azure


Azure Disk Encryption can be enabled and managed through the Azure CLI and Azure PowerShell. To do so you
must install the tools locally and connect to your Azure subscription.
Azure CLI
The Azure CLI 2.0 is a command-line tool for managing Azure resources. The CLI is designed to flexibly query
data, support long-running operations as non-blocking processes, and make scripting easy. You can install it locally
by following the steps in Install the Azure CLI.
To Sign in to your Azure account with the Azure CLI, use the az login command.

az login

If you would like to select a tenant to sign in under, use:

az login --tenant <tenant>

If you have multiple subscriptions and want to specify a specific one, get your subscription list with az account list
and specify with az account set.
az account list
az account set --subscription "<subscription name or ID>"

For more information, see Get started with Azure CLI 2.0.
Azure PowerShell
The Azure PowerShell az module provides a set of cmdlets that uses the Azure Resource Manager model for
managing your Azure resources. You can use it in your browser with Azure Cloud Shell, or you can install it on
your local machine using the instructions in Install the Azure PowerShell module.
If you already have it installed locally, make sure you use the latest version of Azure PowerShell SDK version to
configure Azure Disk Encryption. Download the latest version of Azure PowerShell release.
To Sign in to your Azure account with Azure PowerShell, use the Connect-AzAccount cmdlet.

Connect-AzAccount

If you have multiple subscriptions and want to specify one, use the Get-AzSubscription cmdlet to list them,
followed by the Set-AzContext cmdlet:

Set-AzContext -Subscription -Subscription <SubscriptionId>

Running the Get-AzContext cmdlet will verify that the correct subscription has been selected.
To confirm the Azure Disk Encryption cmdlets are installed, use the Get-command cmdlet:

Get-command *diskencryption*

For more information, see Getting started with Azure PowerShell.

Enable encryption on an existing or running Windows VM


In this scenario, you can enable encryption by using the Resource Manager template, PowerShell cmdlets, or CLI
commands. If you need schema information for the virtual machine extension, see the Azure Disk Encryption for
Windows extension article.

Enable encryption on existing or running IaaS Windows VMs


You can enable encryption by using a template, PowerShell cmdlets, or CLI commands. If you need schema
information for the virtual machine extension, see the Azure Disk Encryption for Windows extension article.
Enable encryption on existing or running VMs with Azure PowerShell
Use the Set-AzVMDiskEncryptionExtension cmdlet to enable encryption on a running IaaS virtual machine in
Azure.
Encrypt a running VM: The script below initializes your variables and runs the Set-
AzVMDiskEncryptionExtension cmdlet. The resource group, VM, and key vault should have already been
created as prerequisites. Replace MyKeyVaultResourceGroup, MyVirtualMachineResourceGroup,
MySecureVM, and MySecureVault with your values.
$KVRGname = 'MyKeyVaultResourceGroup';
$VMRGName = 'MyVirtualMachineResourceGroup';
$vmName = 'MySecureVM';
$KeyVaultName = 'MySecureVault';
$KeyVault = Get-AzKeyVault -VaultName $KeyVaultName -ResourceGroupName $KVRGname;
$diskEncryptionKeyVaultUrl = $KeyVault.VaultUri;
$KeyVaultResourceId = $KeyVault.ResourceId;

Set-AzVMDiskEncryptionExtension -ResourceGroupName $VMRGname -VMName $vmName -DiskEncryptionKeyVaultUrl


$diskEncryptionKeyVaultUrl -DiskEncryptionKeyVaultId $KeyVaultResourceId;

Encrypt a running VM using KEK:

$KVRGname = 'MyKeyVaultResourceGroup';
$VMRGName = 'MyVirtualMachineResourceGroup';
$vmName = 'MyExtraSecureVM';
$KeyVaultName = 'MySecureVault';
$keyEncryptionKeyName = 'MyKeyEncryptionKey';
$KeyVault = Get-AzKeyVault -VaultName $KeyVaultName -ResourceGroupName $KVRGname;
$diskEncryptionKeyVaultUrl = $KeyVault.VaultUri;
$KeyVaultResourceId = $KeyVault.ResourceId;
$keyEncryptionKeyUrl = (Get-AzKeyVaultKey -VaultName $KeyVaultName -Name $keyEncryptionKeyName).Key.kid;

Set-AzVMDiskEncryptionExtension -ResourceGroupName $VMRGname -VMName $vmName -DiskEncryptionKeyVaultUrl


$diskEncryptionKeyVaultUrl -DiskEncryptionKeyVaultId $KeyVaultResourceId -KeyEncryptionKeyUrl
$keyEncryptionKeyUrl -KeyEncryptionKeyVaultId $KeyVaultResourceId;

NOTE
The syntax for the value of disk-encryption-keyvault parameter is the full identifier string:
/subscriptions/[subscription-id-guid]/resourceGroups/[resource-group-
name]/providers/Microsoft.KeyVault/vaults/[keyvault-name]
The syntax for the value of the key-encryption-key parameter is the full URI to the KEK as in: https://[keyvault-
name].vault.azure.net/keys/[kekname]/[kek-unique-id]

Verify the disks are encrypted: To check on the encryption status of an IaaS VM, use the Get-
AzVmDiskEncryptionStatus cmdlet.

Get-AzVmDiskEncryptionStatus -ResourceGroupName 'MyVirtualMachineResourceGroup' -VMName 'MySecureVM'

Disable disk encryption: To disable the encryption, use the Disable-AzVMDiskEncryption cmdlet.
Disabling data disk encryption on Windows VM when both OS and data disks have been encrypted doesn't
work as expected. Disable encryption on all disks instead.

Disable-AzVMDiskEncryption -ResourceGroupName 'MyVirtualMachineResourceGroup' -VMName 'MySecureVM'

Enable encryption on existing or running VMs with the Azure CLI


Use the az vm encryption enable command to enable encryption on a running IaaS virtual machine in Azure.
Encrypt a running VM:

az vm encryption enable --resource-group "MyVirtualMachineResourceGroup" --name "MySecureVM" --disk-


encryption-keyvault "MySecureVault" --volume-type [All|OS|Data]
Encrypt a running VM using KEK:

az vm encryption enable --resource-group "MyVirtualMachineResourceGroup" --name "MySecureVM" --disk-


encryption-keyvault "MySecureVault" --key-encryption-key "MyKEK_URI" --key-encryption-keyvault
"MySecureVaultContainingTheKEK" --volume-type [All|OS|Data]

NOTE
The syntax for the value of disk-encryption-keyvault parameter is the full identifier string:
/subscriptions/[subscription-id-guid]/resourceGroups/[resource-group-
name]/providers/Microsoft.KeyVault/vaults/[keyvault-name]
The syntax for the value of the key-encryption-key parameter is the full URI to the KEK as in: https://[keyvault-
name].vault.azure.net/keys/[kekname]/[kek-unique-id]

Verify the disks are encrypted: To check on the encryption status of an IaaS VM, use the az vm
encryption show command.

az vm encryption show --name "MySecureVM" --resource-group "MyVirtualMachineResourceGroup"

Disable encryption: To disable encryption, use the az vm encryption disable command. Disabling data
disk encryption on Windows VM when both OS and data disks have been encrypted doesn't work as
expected. Disable encryption on all disks instead.

az vm encryption disable --name "MySecureVM" --resource-group "MyVirtualMachineResourceGroup" --volume-


type [ALL, DATA, OS]

Using the Resource Manager template


You can enable disk encryption on existing or running IaaS Windows VMs in Azure by using the Resource
Manager template to encrypt a running Windows VM.
1. On the Azure quickstart template, click Deploy to Azure.
2. Select the subscription, resource group, location, settings, legal terms, and agreement. Click Purchase to
enable encryption on the existing or running IaaS VM.
The following table lists the Resource Manager template parameters for existing or running VMs:

PARAMETER DESCRIPTION

vmName Name of the VM to run the encryption operation.

keyVaultName Name of the key vault that the BitLocker key should be
uploaded to. You can get it by using the cmdlet
(Get-AzKeyVault -ResourceGroupName
<MyKeyVaultResourceGroupName>). Vaultname
or the Azure CLI command
az keyvault list --resource-group
"MyKeyVaultResourceGroup"

keyVaultResourceGroup Name of the resource group that contains the key vault

keyEncryptionKeyURL The URL of the key encryption key, in the format


https://<keyvault-name>.vault.azure.net/key/<key-name>. If
you do not wish to use a KEK, leave this field blank.
PARAMETER DESCRIPTION

volumeType Type of volume that the encryption operation is performed


on. Valid values are OS, Data, and All.

forceUpdateTag Pass in a unique value like a GUID every time the operation
needs to be force run.

resizeOSDisk Should the OS partition be resized to occupy full OS VHD


before splitting system volume.

location Location for all resources.

New IaaS VMs created from customer-encrypted VHD and encryption


keys
In this scenario, you can create a new VM from a pre-encrypted VHD and the associated encryption keys using
PowerShell cmdlets or CLI commands.
Use the instructions in Prepare a pre-encrypted Windows VHD. After the image is created, you can use the steps in
the next section to create an encrypted Azure VM.
Encrypt VMs with pre -encrypted VHDs with Azure PowerShell
You can enable disk encryption on your encrypted VHD by using the PowerShell cmdlet Set-AzVMOSDisk. The
example below gives you some common parameters.

$VirtualMachine = New-AzVMConfig -VMName "MySecureVM" -VMSize "Standard_A1"


$VirtualMachine = Set-AzVMOSDisk -VM $VirtualMachine -Name "SecureOSDisk" -VhdUri "os.vhd" Caching ReadWrite -
Windows -CreateOption "Attach" -DiskEncryptionKeyUrl
"https://mytestvault.vault.azure.net/secrets/Test1/514ceb769c984379a7e0230bddaaaaaa" -DiskEncryptionKeyVaultId
"/subscriptions/00000000-0000-0000-0000-
000000000000/resourceGroups/myKVresourcegroup/providers/Microsoft.KeyVault/vaults/mytestvault"
New-AzVM -VM $VirtualMachine -ResourceGroupName "MyVirtualMachineResourceGroup"

Enable encryption on a newly added data disk


You can add a new disk to a Windows VM using PowerShell, or through the Azure portal.
Enable encryption on a newly added disk with Azure PowerShell
When using Powershell to encrypt a new disk for Windows VMs, a new sequence version should be specified. The
sequence version has to be unique. The script below generates a GUID for the sequence version. In some cases, a
newly added data disk might be encrypted automatically by the Azure Disk Encryption extension. Auto encryption
usually occurs when the VM reboots after the new disk comes online. This is typically caused because "All" was
specified for the volume type when disk encryption previously ran on the VM. If auto encryption occurs on a newly
added data disk, we recommend running the Set-AzVmDiskEncryptionExtension cmdlet again with new sequence
version. If your new data disk is auto encrypted and you do not wish to be encrypted, decrypt all drives first then
re-encrypt with a new sequence version specifying OS for the volume type.
Encrypt a running VM: The script below initializes your variables and runs the Set-
AzVMDiskEncryptionExtension cmdlet. The resource group, VM, and key vault should have already been
created as prerequisites. Replace MyKeyVaultResourceGroup, MyVirtualMachineResourceGroup,
MySecureVM, and MySecureVault with your values. This example uses "All" for the -VolumeType
parameter, which includes both OS and Data volumes. If you only want to encrypt the OS volume, use "OS"
for the -VolumeType parameter.
$KVRGname = 'MyKeyVaultResourceGroup';
$VMRGName = 'MyVirtualMachineResourceGroup';
$vmName = 'MySecureVM';
$KeyVaultName = 'MySecureVault';
$KeyVault = Get-AzKeyVault -VaultName $KeyVaultName -ResourceGroupName $KVRGname;
$diskEncryptionKeyVaultUrl = $KeyVault.VaultUri;
$KeyVaultResourceId = $KeyVault.ResourceId;
$sequenceVersion = [Guid]::NewGuid();

Set-AzVMDiskEncryptionExtension -ResourceGroupName $VMRGname -VMName $vmName -DiskEncryptionKeyVaultUrl


$diskEncryptionKeyVaultUrl -DiskEncryptionKeyVaultId $KeyVaultResourceId -VolumeType "All" –
SequenceVersion $sequenceVersion;

Encrypt a running VM using KEK: This example uses "All" for the -VolumeType parameter, which
includes both OS and Data volumes. If you only want to encrypt the OS volume, use "OS" for the -
VolumeType parameter.

$KVRGname = 'MyKeyVaultResourceGroup';
$VMRGName = 'MyVirtualMachineResourceGroup';
$vmName = 'MyExtraSecureVM';
$KeyVaultName = 'MySecureVault';
$keyEncryptionKeyName = 'MyKeyEncryptionKey';
$KeyVault = Get-AzKeyVault -VaultName $KeyVaultName -ResourceGroupName $KVRGname;
$diskEncryptionKeyVaultUrl = $KeyVault.VaultUri;
$KeyVaultResourceId = $KeyVault.ResourceId;
$keyEncryptionKeyUrl = (Get-AzKeyVaultKey -VaultName $KeyVaultName -Name $keyEncryptionKeyName).Key.kid;
$sequenceVersion = [Guid]::NewGuid();

Set-AzVMDiskEncryptionExtension -ResourceGroupName $VMRGname -VMName $vmName -DiskEncryptionKeyVaultUrl


$diskEncryptionKeyVaultUrl -DiskEncryptionKeyVaultId $KeyVaultResourceId -KeyEncryptionKeyUrl
$keyEncryptionKeyUrl -KeyEncryptionKeyVaultId $KeyVaultResourceId -VolumeType "All" –SequenceVersion
$sequenceVersion;

NOTE
The syntax for the value of disk-encryption-keyvault parameter is the full identifier string:
/subscriptions/[subscription-id-guid]/resourceGroups/[resource-group-
name]/providers/Microsoft.KeyVault/vaults/[keyvault-name]
The syntax for the value of the key-encryption-key parameter is the full URI to the KEK as in: https://[keyvault-
name].vault.azure.net/keys/[kekname]/[kek-unique-id]

Enable encryption on a newly added disk with Azure CLI


The Azure CLI command will automatically provide a new sequence version for you when you run the command
to enable encryption. The example uses "All" for the volume-type parameter. You may need to change the volume-
type parameter to OS if you're only encrypting the OS disk. In contrast to Powershell syntax, the CLI does not
require the user to provide a unique sequence version when enabling encryption. The CLI automatically generates
and uses its own unique sequence version value.
Encrypt a running VM:

az vm encryption enable --resource-group "MyVirtualMachineResourceGroup" --name "MySecureVM" --disk-


encryption-keyvault "MySecureVault" --volume-type "All"

Encrypt a running VM using KEK:


az vm encryption enable --resource-group "MyVirtualMachineResourceGroup" --name "MySecureVM" --disk-
encryption-keyvault "MySecureVault" --key-encryption-key "MyKEK_URI" --key-encryption-keyvault
"MySecureVaultContainingTheKEK" --volume-type "All"

Disable encryption
You can disable encryption using Azure PowerShell, the Azure CLI, or with a Resource Manager template.
Disabling data disk encryption on Windows VM when both OS and data disks have been encrypted doesn't work
as expected. Disable encryption on all disks instead.
Disable disk encryption with Azure PowerShell: To disable the encryption, use the Disable-
AzVMDiskEncryption cmdlet.

Disable-AzVMDiskEncryption -ResourceGroupName 'MyVirtualMachineResourceGroup' -VMName 'MySecureVM' -


VolumeType "all"

Disable encryption with the Azure CLI: To disable encryption, use the az vm encryption disable
command.

az vm encryption disable --name "MySecureVM" --resource-group "MyVirtualMachineResourceGroup" --volume-


type "all"

Disable encryption with a Resource Manager template:


1. Click Deploy to Azure from the Disable disk encryption on running Windows VM template.
2. Select the subscription, resource group, location, VM, volume type, legal terms, and agreement.
3. Click Purchase to disable disk encryption on a running Windows VM.

Unsupported scenarios
Azure Disk Encryption does not work for the following scenarios, features, and technology:
Encrypting basic tier VM or VMs created through the classic VM creation method.
Encrypting VMs configured with software-based RAID systems.
Encrypting VMs configured with Storage Spaces Direct (S2D ), or Windows Server versions before 2016
configured with Windows Storage Spaces.
Integration with an on-premises key management system.
Azure Files (shared file system).
Network File System (NFS ).
Dynamic volumes.
Windows Server containers, which create dynamic volumes for each container.
Ephemeral OS disks.
Encryption of shared/distributed file systems like (but not limited to) DFS, GFS, DRDB, and CephFS.

Next steps
Azure Disk Encryption overview
Azure Disk Encryption sample scripts
Azure Disk Encryption troubleshooting
Quickstart: Create and encrypt a Windows VM with
the Azure CLI
10/9/2019 • 3 minutes to read • Edit Online

The Azure CLI is used to create and manage Azure resources from the command line or in scripts. This quickstart
shows you how to use the Azure CLI to create and encrypt a Windows Server 2016 virtual machine (VM ).
If you don't have an Azure subscription, create a free account before you begin.

Use Azure Cloud Shell


Azure hosts Azure Cloud Shell, an interactive shell environment that you can use through your browser. You can
use either Bash or PowerShell with Cloud Shell to work with Azure services. You can use the Cloud Shell
preinstalled commands to run the code in this article without having to install anything on your local environment.
To start Azure Cloud Shell:

OPTION EXAMPLE/LINK

Select Try It in the upper-right corner of a code block.


Selecting Try It doesn't automatically copy the code to Cloud
Shell.

Go to https://shell.azure.com, or select the Launch Cloud


Shell button to open Cloud Shell in your browser.

Select the Cloud Shell button on the menu bar at the upper
right in the Azure portal.

To run the code in this article in Azure Cloud Shell:


1. Start Cloud Shell.
2. Select the Copy button on a code block to copy the code.
3. Paste the code into the Cloud Shell session by selecting Ctrl+Shift+V on Windows and Linux or by
selecting Cmd+Shift+V on macOS.
4. Select Enter to run the code.
If you choose to install and use the CLI locally, this quickstart requires that you are running the Azure CLI version
2.0.30 or later. Run az --version to find the version. If you need to install or upgrade, see Install Azure CLI.

Create a resource group


Create a resource group with the az group create command. An Azure resource group is a logical container into
which Azure resources are deployed and managed. The following example creates a resource group named
myResourceGroup in the eastus location:

az group create --name myResourceGroup --location eastus


Create a virtual machine
Create a VM with az vm create. The following example creates a VM named myVM. This example uses azureuser
for an administrative user name and myPassword12 as the password.

az vm create \
--resource-group myResourceGroup \
--name myVM \
--image win2016datacenter \
--admin-username azureuser \
--admin-password myPassword12

It takes a few minutes to create the VM and supporting resources. The following example output shows the VM
create operation was successful.

{
"fqdns": "",
"id":
"/subscriptions/<guid>/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM",
"location": "eastus",
"macAddress": "00-0D-3A-23-9A-49",
"powerState": "VM running",
"privateIpAddress": "10.0.0.4",
"publicIpAddress": "52.174.34.95",
"resourceGroup": "myResourceGroup"
}

Create a Key Vault configured for encryption keys


Azure disk encryption stores its encryption key in an Azure Key Vault. Create a Key Vault with az keyvault create. To
enable the Key Vault to store encryption keys, use the --enabled-for-disk-encryption parameter.

IMPORTANT
Each Key Vault must have a unique name. The following example creates a Key Vault named myKV, but you must name yours
something different.

az keyvault create --name "myKV" --resource-group "myResourceGroup" --location eastus --enabled-for-disk-


encryption

Encrypt the virtual machine


Encrypt your VM with az vm encryption, providing your unique Key Vault name to the --disk-encryption-keyvault
parameter.

az vm encryption enable -g MyResourceGroup --name MyVM --disk-encryption-keyvault myKV

You can verify that encryption is enabled on your VM with az vm show

az vm show --name MyVM -g MyResourceGroup

You will see the following in the returned output:


"EncryptionOperation": "EnableEncryption"

Clean up resources
When no longer needed, you can use the az group delete command to remove the resource group, VM, and Key
Vault.

az group delete --name myResourceGroup

Next steps
In this quickstart, you created a virtual machine, created a Key Vault that was enable for encryption keys, and
encrypted the VM. Advance to the next article to learn more about Azure Disk Encryption prerequisites for IaaS
VMs.
Azure Disk Encryption overview
Quickstart: Create and encrypt a Windows virtual
machine in Azure with PowerShell
10/9/2019 • 2 minutes to read • Edit Online

The Azure PowerShell module is used to create and manage Azure resources from the PowerShell command line
or in scripts. This quickstart shows you how to use the Azure PowerShell module to create a Windows virtual
machine (VM ), create a Key Vault for the storage of encryption keys, and encrypt the VM.
If you don't have an Azure subscription, create a free account before you begin.

Create a resource group


Create an Azure resource group with New -AzResourceGroup. A resource group is a logical container into which
Azure resources are deployed and managed:

New-AzResourceGroup -Name "myResourceGroup" -Location "EastUS"

Create a virtual machine


Create an Azure virtual machine with New -AzVM. You must supply credentials to the cmdlet.

$cred = Get-Credential

New-AzVM -Name MyVm -Credential $cred -ResourceGroupName MyResourceGroup -Image win2016datacenter -Size
Standard_D2S_V3

It will take a few minutes for your VM to be deployed.

Create a Key Vault configured for encryption keys


Azure disk encryption stores its encryption key in an Azure Key Vault. Create a Key Vault with New -AzKeyvault. To
enable the Key Vault to store encryption keys, use the -EnabledForDiskEncryption parameter.

IMPORTANT
Each Key Vault must have a unique name. The following example creates a Key Vault named myKV, but you must name yours
something different.

New-AzKeyvault -name MyKV -ResourceGroupName myResourceGroup -Location EastUS -EnabledForDiskEncryption

Encrypt the virtual machine


Encrypt your VM with Set-AzVmDiskEncryptionExtension.
Set-AzVmDiskEncryptionExtension requires some values from your Key Vault object. You can obtain these values
by passing the unique name of your key vault to Get-AzKeyvault.
$KeyVault = Get-AzKeyVault -VaultName MyKV -ResourceGroupName MyResourceGroup

Set-AzVMDiskEncryptionExtension -ResourceGroupName MyResourceGroup -VMName MyVM -DiskEncryptionKeyVaultUrl


$KeyVault.VaultUri -DiskEncryptionKeyVaultId $KeyVault.ResourceId

After a few minutes the process will return the following:

RequestId IsSuccessStatusCode StatusCode ReasonPhrase


--------- ------------------- ---------- ------------
True OK OK

You can verify the encryption process by running Get-AzVmDiskEncryptionStatus.

Get-AzVmDiskEncryptionStatus -VMName MyVM -ResourceGroupName MyResourceGroup

When encryption is enabled, you will see the following in the returned output:

OsVolumeEncrypted : Encrypted
DataVolumesEncrypted : NoDiskFound
OsVolumeEncryptionSettings : Microsoft.Azure.Management.Compute.Models.DiskEncryptionSettings
ProgressMessage : Provisioning succeeded

Clean up resources
When no longer needed, you can use the Remove-AzResourceGroup cmdlet to remove the resource group, VM,
and all related resources:

Remove-AzResourceGroup -Name "myResourceGroup"

Next steps
In this quickstart, you created a virtual machine, created a Key Vault that was enable for encryption keys, and
encrypted the VM. Advance to the next article to learn more about Azure Disk Encryption prerequisites for IaaS
VMs.
Azure Disk Encryption overview
Quickstart: Create and encrypt a Windows virtual
machine with the Azure portal
11/17/2019 • 2 minutes to read • Edit Online

Azure virtual machines (VMs) can be created through the Azure portal. The Azure portal is a browser-based user
interface to create VMs and their associated resources. In this quickstart you will use the Azure portal to deploy a
Windows virtual machine (VM ) running Ubuntu 18.04 LTS, create a key vault for the storage of encryption keys,
and encrypt the VM.
If you don't have an Azure subscription, create a free account before you begin.

Sign in to Azure
Sign in to the Azure portal.

Create a virtual machine


1. Choose Create a resource in the upper left corner of the Azure portal.
2. In the New page, under Popular, select Windows Server 2016 Datacenter.
3. In the Basics tab, under Project details, make sure the correct subscription is selected and then choose to Create
new resource group. Enter myResourceGroup as the name.
4. For Virtual machine name, enter MyVM.
5. For Region, select the same region you used when making your key vault above (e.g., East US ).
6. Make sure the Size is Standard D2s v3.
7. Under Administrator account, select Password. Enter a user name and a password.
8. Select the "Management" tab and verify that you have a Diagnostics Storage Account. If you have no storage
accounts, select "Create New", give your new account a name, and select "Ok"

9. Click "Review + Create".


10. On the Create a virtual machine page, you can see the details about the VM you are about to create. When
you are ready, select Create.
It will take a few minutes for your VM to be deployed. When the deployment is finished, move on to the next
section.

Encrypt the virtual machine


1. When the VM deployment is complete, select Go to resource.
2. On the left-hand sidebar, select Disks.
3. On the Disks screen, select Encryption.

4. On the encryption screen, under Disks to encrypt, choose OS and data disks.
5. Under Encryption settings, choose Select a key vault and key for encryption.
6. On the Select key from Azure Key Vault screen, select Create New.

7. On the Create key vault screen, ensure that the Resource Group is the same as the one you used to create
the VM.
8. Give your key vault a name. Every key vault across Azure must have an unique name.
9. On the Access Policies tab, check the Azure Disk Encryption for volume encryption box.

10. Select Review + create.


11. After the key vault has passed validation, select Create. This will return you to the Select key from Azure
Key Vault screen.
12. Leave the Key field blank and choose Select.
13. At the top of the encryption screen, click Save. A popup will warn you that the VM will reboot. Click Yes.

Clean up resources
When no longer needed, you can delete the resource group, virtual machine, and all related resources. To do so,
select the resource group for the virtual machine, select Delete, then confirm the name of the resource group to
delete.

Next steps
In this quickstart, you created a Key Vault that was enable for encryption keys, created a virtual machine, and
enabled the virtual machine for encryption.
Azure Disk Encryption overview
Creating and configuring a key vault for Azure Disk
Encryption
10/9/2019 • 6 minutes to read • Edit Online

Azure Disk Encryption uses Azure Key Vault to control and manage disk encryption keys and secrets. For more
information about key vaults, see Get started with Azure Key Vault and Secure your key vault.

WARNING
If you have previously used Azure Disk Encryption with Azure AD to encrypt a VM, you must continue use this option to
encrypt your VM. See Creating and configuring a key vault for Azure Disk Encryption with Azure AD (previous release) for
details.

Creating and configuring a key vault for use with Azure Disk Encryption involves three steps:
1. Creating a resource group, if needed.
2. Creating a key vault.
3. Setting key vault advanced access policies.
These steps are illustrated in the following quickstarts:
Create and encrypt a Windows VM with Azure CLI
Create and encrypt a Windows VM with Azure PowerShell
You may also, if you wish, generate or import a key encryption key (KEK).

NOTE
The steps in this article are automated in the Azure Disk Encryption prerequisites CLI script and Azure Disk Encryption
prerequisites PowerShell script.

Install tools and connect to Azure


The steps in this article can be completed with the Azure CLI, the Azure PowerShell Az module, or the Azure
portal.
While the portal is accessible through your browser, Azure CLI and Azure PowerShell require local installation; see
Azure Disk Encryption for Windows: Install tools for details.
Connect to your Azure account
Before using the Azure CLI or Azure PowerShell, you must first connect to your Azure subscription. You do so by
Signing in with Azure CLI, Signing in with Azure Powershell, or supplying your credentials to the Azure portal
when prompted.

az login

Connect-AzAccount
Create a resource group
If you already have a resource group, you can skip to Create a key vault.
A resource group is a logical container into which Azure resources are deployed and managed.
Create a resource group using the az group create Azure CLI command, the New -AzResourceGroup Azure
PowerShell command, or from the Azure portal.
Azure CLI

az group create --name "myResourceGroup" --location eastus

Azure PowerShell

New-AzResourceGroup -Name "myResourceGroup" -Location "EastUS"

Create a key vault


If you already have a key vault, you can skip to Set key vault advanced access policies.
Create a key vault using the az keyvault create Azure CLI command, the New -AzKeyvault Azure Powershell
command, the Azure portal, or a Resource Manager template.

WARNING
To ensure that encryption secrets don't cross regional boundaries, Azure Disk Encryption requires the Key Vault and the VMs
to be co-located in the same region. Create and use a Key Vault that is in the same region as the VMs to be encrypted.

Each Key Vault must have a unique name. Replace with the name of your key vault in the following examples.
Azure CLI
When creating a key vault using Azure CLI, add the "--enabled-for-disk-encryption" flag.

az keyvault create --name "<your-unique-keyvault-name>" --resource-group "myResourceGroup" --location "eastus"


--enabled-for-disk-encryption

Azure PowerShell
When creating a key vault using Azure PowerShell, add the "-EnabledForDiskEncryption" flag.

New-AzKeyvault -name "<your-unique-keyvault-name>" -ResourceGroupName "myResourceGroup" -Location "eastus" -


EnabledForDiskEncryption

Resource Manager template


You can also create a key vault by using the Resource Manager template.
1. On the Azure quickstart template, click Deploy to Azure.
2. Select the subscription, resource group, resource group location, Key Vault name, Object ID, legal terms, and
agreement, and then click Purchase.

Set key vault advanced access policies


The Azure platform needs access to the encryption keys or secrets in your key vault to make them available to the
VM for booting and decrypting the volumes.
If you did not enable your key vault for disk encryption, deployment, or template deployment at the time of
creation (as demonstrated in the previous step), you must update its advanced access policies.
Azure CLI
Use az keyvault update to enable disk encryption for the key vault.
Enable Key Vault for disk encryption: Enabled-for-disk-encryption is required.

az keyvault update --name "<your-unique-keyvault-name>" --resource-group "MyResourceGroup" --enabled-


for-disk-encryption "true"

Enable Key Vault for deployment, if needed: Enables the Microsoft.Compute resource provider to
retrieve secrets from this key vault when this key vault is referenced in resource creation, for example when
creating a virtual machine.

az keyvault update --name "<your-unique-keyvault-name>" --resource-group "MyResourceGroup" --enabled-


for-deployment "true"

Enable Key Vault for template deployment, if needed: Allow Resource Manager to retrieve secrets
from the vault.

az keyvault update --name "<your-unique-keyvault-name>" --resource-group "MyResourceGroup" --enabled-


for-template-deployment "true"

Azure PowerShell
Use the key vault PowerShell cmdlet Set-AzKeyVaultAccessPolicy to enable disk encryption for the key vault.
Enable Key Vault for disk encryption: EnabledForDiskEncryption is required for Azure Disk encryption.

Set-AzKeyVaultAccessPolicy -VaultName "<your-unique-keyvault-name>" -ResourceGroupName "MyResourceGroup"


-EnabledForDiskEncryption

Enable Key Vault for deployment, if needed: Enables the Microsoft.Compute resource provider to
retrieve secrets from this key vault when this key vault is referenced in resource creation, for example when
creating a virtual machine.

Set-AzKeyVaultAccessPolicy -VaultName "<your-unique-keyvault-name>" -ResourceGroupName


"MyResourceGroup" -EnabledForDeployment

Enable Key Vault for template deployment, if needed: Enables Azure Resource Manager to get secrets
from this key vault when this key vault is referenced in a template deployment.

Set-AzKeyVaultAccessPolicy -VaultName "<your-unique-keyvault-name>" -ResourceGroupName "MyResourceGroup"


-EnabledForTemplateDeployment

Azure portal
1. Select your key vault, go to Access Policies, and Click to show advanced access policies.
2. Select the box labeled Enable access to Azure Disk Encryption for volume encryption.
3. Select Enable access to Azure Virtual Machines for deployment and/or Enable Access to Azure
Resource Manager for template deployment, if needed.
4. Click Save.

Set up a key encryption key (KEK)


If you want to use a key encryption key (KEK) for an additional layer of security for encryption keys, add a KEK to
your key vault. When a key encryption key is specified, Azure Disk Encryption uses that key to wrap the encryption
secrets before writing to Key Vault.
You can generate a new KEK using the Azure CLI az keyvault key create command, the Azure PowerShell Add-
AzKeyVaultKey cmdlet, or the Azure portal. You must generate an RSA key type; Azure Disk Encryption does not
yet support using Elliptic Curve keys.
You can instead import a KEK from your on-premises key management HSM. For more information, see Key Vault
Documentation.
Your key vault KEK URLs must be versioned. Azure enforces this restriction of versioning. For valid secret and KEK
URLs, see the following examples:
Example of a valid secret URL:
https://contosovault.vault.azure.net/secrets/EncryptionSecretWithKek/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Example of a valid KEK URL:
https://contosovault.vault.azure.net/keys/diskencryptionkek/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Azure Disk Encryption doesn't support specifying port numbers as part of key vault secrets and KEK URLs. For
examples of non-supported and supported key vault URLs, see the following examples:
Acceptable key vault URL:
https://contosovault.vault.azure.net/secrets/contososecret/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Unacceptable key vault URL:
https://contosovault.vault.azure.net:443/secrets/contososecret/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Azure CLI
Use the Azure CLI az keyvault key create command to generate a new KEK and store it in your key vault.
az keyvault key create --name "myKEK" --vault-name "<your-unique-keyvault-name>" --kty RSA-HSM

You may instead import a private key using the Azure CLI az keyvault key import command:
In either case, you will supply the name of your KEK to the Azure CLI az vm encryption enable --key-encryption-
key parameter.

az vm encryption enable -g "MyResourceGroup" --name "myVM" --disk-encryption-keyvault "<your-unique-keyvault-


name>" --key-encryption-key "myKEK"

Azure PowerShell
Use the Azure PowerShell Add-AzKeyVaultKey cmdlet to generate a new KEK and store it in your key vault.

Add-AzKeyVaultKey -Name "myKEK" -VaultName "<your-unique-keyvault-name>" -Destination "HSM"

You may instead import a private key using the Azure PowerShell az keyvault key import command.
In either case, you will supply the ID of your KEK key Vault and the URL of your KEK to the Azure PowerShell Set-
AzVMDiskEncryptionExtension -KeyEncryptionKeyVaultId and -KeyEncryptionKeyUrl parameters. Note that this
example assumes that you are using the same key vault for both the disk encryption key and the KEK.

$KeyVault = Get-AzKeyVault -VaultName "<your-unique-keyvault-name>" -ResourceGroupName "myResourceGroup"


$KEK = Get-AzKeyVaultKey -VaultName "<your-unique-keyvault-name>" -Name "myKEK"

Set-AzVMDiskEncryptionExtension -ResourceGroupName MyResourceGroup -VMName "MyVM" -DiskEncryptionKeyVaultUrl


$KeyVault.VaultUri -DiskEncryptionKeyVaultId $KeyVault.ResourceId -KeyEncryptionKeyVaultId $KeyVault.ResourceId
-KeyEncryptionKeyUrl $KEK.Id -SkipVmBackup -VolumeType All

Next steps
Azure Disk Encryption prerequisites CLI script
Azure Disk Encryption prerequisites PowerShell script
Learn Azure Disk Encryption scenarios on Windows VMs
Learn how to troubleshoot Azure Disk Encryption
Read the Azure Disk Encryption sample scripts
Azure Disk Encryption sample scripts
11/7/2019 • 7 minutes to read • Edit Online

This article provides sample scripts for preparing pre-encrypted VHDs and other tasks.

List VMs and secrets


List all encrypted VMs in your subscription:

$osVolEncrypted = {(Get-AzVMDiskEncryptionStatus -ResourceGroupName $_.ResourceGroupName -VMName


$_.Name).OsVolumeEncrypted}
$dataVolEncrypted= {(Get-AzVMDiskEncryptionStatus -ResourceGroupName $_.ResourceGroupName -VMName
$_.Name).DataVolumesEncrypted}
Get-AzVm | Format-Table @{Label="MachineName"; Expression={$_.Name}}, @{Label="OsVolumeEncrypted";
Expression=$osVolEncrypted}, @{Label="DataVolumesEncrypted"; Expression=$dataVolEncrypted}

List all disk encryption secrets used for encrypting VMs in a key vault:

Get-AzKeyVaultSecret -VaultName $KeyVaultName | where {$_.Tags.ContainsKey('DiskEncryptionKeyFileName')} |


format-table @{Label="MachineName"; Expression={$_.Tags['MachineName']}}, @{Label="VolumeLetter"; Expression=
{$_.Tags['VolumeLetter']}}, @{Label="EncryptionKeyURL"; Expression={$_.Id}}

The Azure Disk Encryption prerequisites scripts


If you're already familiar with the prerequisites for Azure Disk Encryption, you can use the Azure Disk Encryption
prerequisites PowerShell script. For an example of using this PowerShell script, see the Encrypt a VM Quickstart.
You can remove the comments from a section of the script, starting at line 211, to encrypt all disks for existing
VMs in an existing resource group.
The following table shows which parameters can be used in the PowerShell script:

PARAMETER DESCRIPTION MANDATORY?

$resourceGroupName Name of the resource group to which True


the KeyVault belongs to. A new
resource group with this name will be
created if one doesn't exist.

$keyVaultName Name of the KeyVault in which True


encryption keys are to be placed. A new
vault with this name will be created if
one doesn't exist.

$location Location of the KeyVault. Make sure the True


KeyVault and VMs to be encrypted are
in the same location. Get a location list
with Get-AzLocation .

$subscriptionId Identifier of the Azure subscription to True


be used. You can get your Subscription
ID with Get-AzSubscription .
PARAMETER DESCRIPTION MANDATORY?

$aadAppName Name of the Azure AD application that False


will be used to write secrets to KeyVault.
A new application with this name will be
created if one doesn't exist. If this app
already exists, pass aadClientSecret
parameter to the script.

$aadClientSecret Client secret of the Azure AD False


application that was created earlier.

$keyEncryptionKeyName Name of optional key encryption key in False


KeyVault. A new key with this name will
be created if one doesn't exist.

Resource Manager templates


Encrypt or decrypt VMs without an Azure AD app
Enable disk encryption on an existing or running Windows VM
Disable encryption on a running Windows VM
Encrypt or decrypt VMs with an Azure AD app (previous release )
Enable disk encryption on an existing or running Windows VM
Disable encryption on a running Windows VM
Create a new encrypted managed disk from a pre-encrypted VHD/storage blob
Creates a new encrypted managed disk provided a pre-encrypted VHD and its corresponding
encryption settings

Prepare a pre-encrypted Windows VHD


The sections that follow are necessary to prepare a pre-encrypted Windows VHD for deployment as an encrypted
VHD in Azure IaaS. Use the information to prepare and boot a fresh Windows VM (VHD ) on Azure Site Recovery
or Azure. For more information on how to prepare and upload a VHD, see Upload a generalized VHD and use it to
create new VMs in Azure.
Update group policy to allow non-TPM for OS protection
Configure the BitLocker Group Policy setting BitLocker Drive Encryption, which you'll find under Local
Computer Policy > Computer Configuration > Administrative Templates > Windows Components.
Change this setting to Operating System Drives > Require additional authentication at startup > Allow
BitLocker without a compatible TPM, as shown in the following figure:
Install BitLocker feature components
For Windows Server 2012 and later, use the following command:

dism /online /Enable-Feature /all /FeatureName:BitLocker /quiet /norestart

For Windows Server 2008 R2, use the following command:

ServerManagerCmd -install BitLockers

Prepare the OS volume for BitLocker by using bdehdcfg

To compress the OS partition and prepare the machine for BitLocker, execute the bdehdcfg if needed:

bdehdcfg -target c: shrink -quiet

Protect the OS volume by using BitLocker


Use the manage-bde command to enable encryption on the boot volume using an external key protector. Also
place the external key (.bek file) on the external drive or volume. Encryption is enabled on the system/boot volume
after the next reboot.

manage-bde -on %systemdrive% -sk [ExternalDriveOrVolume]


reboot

NOTE
Prepare the VM with a separate data/resource VHD for getting the external key by using BitLocker.
Upload encrypted VHD to an Azure storage account
After DM -Crypt encryption is enabled, the local encrypted VHD needs to be uploaded to your storage account.

Add-AzVhd [-Destination] <Uri> [-LocalFilePath] <FileInfo> [[-NumberOfUploaderThreads] <Int32> ] [[-


BaseImageUriToPatch] <Uri> ] [[-OverWrite]] [ <CommonParameters>]

Upload the secret for the pre-encrypted VM to your key vault


The disk encryption secret that you obtained previously must be uploaded as a secret in your key vault. This
requires granting the set secret permission and the wrapkey permission to the account that will upload the secrets.

# Typically, account Id is the user principal name (in [email protected] format)


$upn = (Get-AzureRmContext).Account.Id
Set-AzKeyVaultAccessPolicy -VaultName $kvname -UserPrincipalName $acctid -PermissionsToKeys wrapKey -
PermissionsToSecrets set

# In cloud shell, the account ID is a managed service identity, so specify the username directly
# $upn = "[email protected]"
# Set-AzKeyVaultAccessPolicy -VaultName $kvname -UserPrincipalName $acctid -PermissionsToKeys wrapKey -
PermissionsToSecrets set

# When running as a service principal, retrieve the service principal ID from the account ID, and set access
policy to that
# $acctid = (Get-AzureRmContext).Account.Id
# $spoid = (Get-AzureRmADServicePrincipal -ServicePrincipalName $acctid).Id
# Set-AzKeyVaultAccessPolicy -VaultName $kvname -ObjectId $spoid -BypassObjectIdValidation -PermissionsToKeys
wrapKey -PermissionsToSecrets set

Disk encryption secret not encrypted with a KEK


To set up the secret in your key vault, use Set-AzKeyVaultSecret. The passphrase is encoded as a base64 string and
then uploaded to the key vault. In addition, make sure that the following tags are set when you create the secret in
the key vault.

# This is the passphrase that was provided for encryption during the distribution installation
$passphrase = "contoso-password"

$tags = @{"DiskEncryptionKeyEncryptionAlgorithm" = "RSA-OAEP"; "DiskEncryptionKeyFileName" =


"LinuxPassPhraseFileName"}
$secretName = [guid]::NewGuid().ToString()
$secretValue = [Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes($passphrase))
$secureSecretValue = ConvertTo-SecureString $secretValue -AsPlainText -Force

$secret = Set-AzKeyVaultSecret -VaultName $KeyVaultName -Name $secretName -SecretValue $secureSecretValue -


tags $tags
$secretUrl = $secret.Id

Use the $secretUrl in the next step for attaching the OS disk without using KEK.
Disk encryption secret encrypted with a KEK
Before you upload the secret to the key vault, you can optionally encrypt it by using a key encryption key. Use the
wrap API to first encrypt the secret using the key encryption key. The output of this wrap operation is a base64
URL encoded string, which you can then upload as a secret by using the Set-AzKeyVaultSecret cmdlet.

# This is the passphrase that was provided for encryption during the distribution installation
$passphrase = "contoso-password"
Add-AzKeyVaultKey -VaultName $KeyVaultName -Name "keyencryptionkey" -Destination Software
$KeyEncryptionKey = Get-AzKeyVaultKey -VaultName $KeyVault.OriginalVault.Name -Name "keyencryptionkey"

$apiversion = "2015-06-01"

##############################
# Get Auth URI
##############################

$uri = $KeyVault.VaultUri + "/keys"


$headers = @{}

$response = try { Invoke-RestMethod -Method GET -Uri $uri -Headers $headers } catch {
$_.Exception.Response }

$authHeader = $response.Headers["www-authenticate"]
$authUri = [regex]::match($authHeader, 'authorization="(.*?)"').Groups[1].Value

Write-Host "Got Auth URI successfully"

##############################
# Get Auth Token
##############################

$uri = $authUri + "/oauth2/token"


$body = "grant_type=client_credentials"
$body += "&client_id=" + $AadClientId
$body += "&client_secret=" + [Uri]::EscapeDataString($AadClientSecret)
$body += "&resource=" + [Uri]::EscapeDataString("https://vault.azure.net")
$headers = @{}

$response = Invoke-RestMethod -Method POST -Uri $uri -Headers $headers -Body $body

$access_token = $response.access_token

Write-Host "Got Auth Token successfully"

##############################
# Get KEK info
##############################

$uri = $KeyEncryptionKey.Id + "?api-version=" + $apiversion


$headers = @{"Authorization" = "Bearer " + $access_token}

$response = Invoke-RestMethod -Method GET -Uri $uri -Headers $headers

$keyid = $response.key.kid

Write-Host "Got KEK info successfully"

##############################
# Encrypt passphrase using KEK
##############################

$passphraseB64 = [Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes($Passphrase))
$uri = $keyid + "/encrypt?api-version=" + $apiversion
$headers = @{"Authorization" = "Bearer " + $access_token; "Content-Type" = "application/json"}
$bodyObj = @{"alg" = "RSA-OAEP"; "value" = $passphraseB64}
$body = $bodyObj | ConvertTo-Json

$response = Invoke-RestMethod -Method POST -Uri $uri -Headers $headers -Body $body

$wrappedSecret = $response.value

Write-Host "Encrypted passphrase successfully"

##############################
# Store secret
# Store secret
##############################

$secretName = [guid]::NewGuid().ToString()
$uri = $KeyVault.VaultUri + "/secrets/" + $secretName + "?api-version=" + $apiversion
$secretAttributes = @{"enabled" = $true}
$secretTags = @{"DiskEncryptionKeyEncryptionAlgorithm" = "RSA-OAEP"; "DiskEncryptionKeyFileName" =
"LinuxPassPhraseFileName"}
$headers = @{"Authorization" = "Bearer " + $access_token; "Content-Type" = "application/json"}
$bodyObj = @{"value" = $wrappedSecret; "attributes" = $secretAttributes; "tags" = $secretTags}
$body = $bodyObj | ConvertTo-Json

$response = Invoke-RestMethod -Method PUT -Uri $uri -Headers $headers -Body $body

Write-Host "Stored secret successfully"

$secretUrl = $response.id

Use $KeyEncryptionKey and $secretUrl in the next step for attaching the OS disk using KEK.

Specify a secret URL when you attach an OS disk


Without using a KEK
While you're attaching the OS disk, you need to pass $secretUrl . The URL was generated in the "Disk-encryption
secret not encrypted with a KEK" section.

Set-AzVMOSDisk `
-VM $VirtualMachine `
-Name $OSDiskName `
-SourceImageUri $VhdUri `
-VhdUri $OSDiskUri `
-Windows `
-CreateOption FromImage `
-DiskEncryptionKeyVaultId $KeyVault.ResourceId `
-DiskEncryptionKeyUrl $SecretUrl

Using a KEK
When you attach the OS disk, pass $KeyEncryptionKey and $secretUrl . The URL was generated in the "Disk
encryption secret encrypted with a KEK" section.

Set-AzVMOSDisk `
-VM $VirtualMachine `
-Name $OSDiskName `
-SourceImageUri $CopiedTemplateBlobUri `
-VhdUri $OSDiskUri `
-Windows `
-CreateOption FromImage `
-DiskEncryptionKeyVaultId $KeyVault.ResourceId `
-DiskEncryptionKeyUrl $SecretUrl `
-KeyEncryptionKeyVaultId $KeyVault.ResourceId `
-KeyEncryptionKeyURL $KeyEncryptionKey.Id
Azure Disk Encryption troubleshooting guide
11/7/2019 • 3 minutes to read • Edit Online

This guide is for IT professionals, information security analysts, and cloud administrators whose organizations use
Azure Disk Encryption. This article is to help with troubleshooting disk-encryption-related problems.
Before taking any of the steps below, first ensure that the VMs you are attempting to encrypt are among the
supported VM sizes and operating systems, and that you have met all the prerequisites:
Networking requirements
Group policy requirements
Encryption key storage requirements

Troubleshooting Azure Disk Encryption behind a firewall


When connectivity is restricted by a firewall, proxy requirement, or network security group (NSG ) settings, the
ability of the extension to perform needed tasks might be disrupted. This disruption can result in status messages
such as "Extension status not available on the VM." In expected scenarios, the encryption fails to finish. The
sections that follow have some common firewall problems that you might investigate.
Network security groups
Any network security group settings that are applied must still allow the endpoint to meet the documented
network configuration prerequisites for disk encryption.
Azure Key Vault behind a firewall
When encryption is being enabled with Azure AD credentials, the target VM must allow connectivity to both Azure
Active Directory endpoints and Key Vault endpoints. Current Azure Active Directory authentication endpoints are
maintained in sections 56 and 59 of the Office 365 URLs and IP address ranges documentation. Key Vault
instructions are provided in the documentation on how to Access Azure Key Vault behind a firewall.
Azure Instance Metadata Service
The VM must be able to access the Azure Instance Metadata service endpoint which uses a well-known non-
routable IP address ( 169.254.169.254 ) that can be accessed only from within the VM. Proxy configurations that
alter local HTTP traffic to this address (for example, adding an X-Forwarded-For header) are not supported.

Troubleshooting Windows Server 2016 Server Core


On Windows Server 2016 Server Core, the bdehdcfg component isn't available by default. This component is
required by Azure Disk Encryption. It's used to split the system volume from OS volume, which is done only once
for the life time of the VM. These binaries aren't required during later encryption operations.
To work around this issue, copy the following four files from a Windows Server 2016 Data Center VM to the same
location on Server Core:

\windows\system32\bdehdcfg.exe
\windows\system32\bdehdcfglib.dll
\windows\system32\en-US\bdehdcfglib.dll.mui
\windows\system32\en-US\bdehdcfg.exe.mui

1. Enter the following command:


bdehdcfg.exe -target default

2. This command creates a 550-MB system partition. Reboot the system.


3. Use DiskPart to check the volumes, and then proceed.
For example:

DISKPART> list vol

Volume ### Ltr Label Fs Type Size Status Info


---------- --- ----------- ----- ---------- ------- --------- --------
Volume 0 C NTFS Partition 126 GB Healthy Boot
Volume 1 NTFS Partition 550 MB Healthy System
Volume 2 D Temporary S NTFS Partition 13 GB Healthy Pagefile

Troubleshooting encryption status


The portal may display a disk as encrypted even after it has been unencrypted within the VM. This can occur when
low -level commands are used to directly unencrypt the disk from within the VM, instead of using the higher level
Azure Disk Encryption management commands. The higher level commands not only unencrypt the disk from
within the VM, but outside of the VM they also update important platform level encryption settings and extension
settings associated with the VM. If these are not kept in alignment, the platform will not be able to report
encryption status or provision the VM properly.
To disable Azure Disk Encryption with PowerShell, use Disable-AzVMDiskEncryption followed by Remove-
AzVMDiskEncryptionExtension. Running Remove-AzVMDiskEncryptionExtension before the encryption is
disabled will fail.
To disable Azure Disk Encryption with CLI, use az vm encryption disable.

Next steps
In this document, you learned more about some common problems in Azure Disk Encryption and how to
troubleshoot those problems. For more information about this service and its capabilities, see the following
articles:
Apply disk encryption in Azure Security Center
Azure data encryption at rest
Azure Disk Encryption for Windows VMs FAQ
11/22/2019 • 6 minutes to read • Edit Online

This article provides answers to frequently asked questions (FAQ ) about Azure Disk Encryption for Windows VMs.
For more information about this service, see Azure Disk Encryption overview.

Where is Azure Disk Encryption in general availability (GA)?


Azure Disk Encryption is in general availability in all Azure public regions.

What user experiences are available with Azure Disk Encryption?


Azure Disk Encryption GA supports Azure Resource Manager templates, Azure PowerShell, and Azure CLI. The
different user experiences give you flexibility. You have three different options for enabling disk encryption for your
VMs. For more information on the user experience and step-by-step guidance available in Azure Disk Encryption,
see Azure Disk Encryption scenarios for Windows.

How much does Azure Disk Encryption cost?


There's no charge for encrypting VM disks with Azure Disk Encryption, but there are charges associated with the
use of Azure Key Vault. For more information on Azure Key Vault costs, see the Key Vault pricing page.

How can I start using Azure Disk Encryption?


To get started, read the Azure Disk Encryption overview.

What VM sizes and operating systems support Azure Disk Encryption?


The Azure Disk Encryption overview article lists the VM sizes and VM operating systems that support Azure Disk
Encryption.

Can I encrypt both boot and data volumes with Azure Disk Encryption?
You can encrypt both boot and data volumes, but you can't encrypt the data without first encrypting the OS
volume.
After you've encrypted the OS volume, disabling encryption on the OS volume isn't supported.

Can I encrypt an unmounted volume with Azure Disk Encryption?


No, Azure Disk Encryption only encrypts mounted volumes.

How do I rotate secrets or encryption keys?


To rotate secrets, just call the same command you used originally to enable disk encryption, specifying a different
Key Vault. To rotate the key encryption key, call the same command you used originally to enable disk encryption,
specifying the new key encryption.
WARNING
If you have previously used Azure Disk Encryption with Azure AD app by specifying Azure AD credentials to encrypt this
VM, you will have to continue use this option to encrypt your VM. You can’t use Azure Disk Encryption on this encrypted
VM as this isn’t a supported scenario, meaning switching away from AAD application for this encrypted VM isn’t
supported yet.

How do I add or remove a key encryption key if I didn't originally use


one?
To add a key encryption key, call the enable command again passing the key encryption key parameter. To remove
a key encryption key, call the enable command again without the key encryption key parameter.

Does Azure Disk Encryption allow you to bring your own key (BYOK)?
Yes, you can supply your own key encryption keys. These keys are safeguarded in Azure Key Vault, which is the key
store for Azure Disk Encryption. For more information on the key encryption keys support scenarios, see Creating
and configuring a key vault for Azure Disk Encryption.

Can I use an Azure-created key encryption key?


Yes, you can use Azure Key Vault to generate a key encryption key for Azure disk encryption use. These keys are
safeguarded in Azure Key Vault, which is the key store for Azure Disk Encryption. For more information on the key
encryption key, see Creating and configuring a key vault for Azure Disk Encryption.

Can I use an on-premises key management service or HSM to


safeguard the encryption keys?
You can't use the on-premises key management service or HSM to safeguard the encryption keys with Azure Disk
Encryption. You can only use the Azure Key Vault service to safeguard the encryption keys. For more information
on the key encryption key support scenarios, see Creating and configuring a key vault for Azure Disk Encryption.

What are the prerequisites to configure Azure Disk Encryption?


There are prerequisites for Azure Disk Encryption. See the Creating and configuring a key vault for Azure Disk
Encryption article to create a new key vault, or set up an existing key vault for disk encryption access to enable
encryption, and safeguard secrets and keys. For more information on the key encryption key support scenarios, see
Creating and configuring a key vault for Azure Disk Encryption.

What are the prerequisites to configure Azure Disk Encryption with an


Azure AD app (previous release)?
There are prerequisites for Azure Disk Encryption. See the Azure Disk Encryption with Azure AD content to create
an Azure Active Directory application, create a new key vault, or set up an existing key vault for disk encryption
access to enable encryption, and safeguard secrets and keys. For more information on the key encryption key
support scenarios, see Creating and configuring a key vault for Azure Disk Encryption with Azure AD.

Is Azure Disk Encryption using an Azure AD app (previous release) still


supported?
Yes. Disk encryption using an Azure AD app is still supported. However, when encrypting new VMs it's
recommended that you use the new method rather than encrypting with an Azure AD app.

Can I migrate VMs that were encrypted with an Azure AD app to


encryption without an Azure AD app?
Currently, there isn't a direct migration path for machines that were encrypted with an Azure AD app to encryption
without an Azure AD app. Additionally, there isn't a direct path from encryption without an Azure AD app to
encryption with an AD app.

What version of Azure PowerShell does Azure Disk Encryption support?


Use the latest version of the Azure PowerShell SDK to configure Azure Disk Encryption. Download the latest
version of Azure PowerShell. Azure Disk Encryption is not supported by Azure SDK version 1.1.0.

What is the disk "Bek Volume" or "/mnt/azure_bek_disk"?


The "Bek volume" is a local data volume that securely stores the encryption keys for Encrypted Azure VMs.

NOTE
Do not delete or edit any contents in this disk. Do not unmount the disk since the encryption key presence is needed for any
encryption operations on the IaaS VM.

What encryption method does Azure Disk Encryption use?


Azure Disk Encryption selects the encryption method in BitLocker based on the version of Windows as follows:

WINDOWS VERSIONS VERSION ENCRYPTION METHOD

Windows Server 2012, Windows 10, or >=1511 XTS-AES 256 bit


greater

Windows Server 2012, Windows 8, 8.1, < 1511 AES 256 bit *
10

Windows Server 2008R2 AES 256 bit with Diffuser

* AES 256 bit with Diffuser isn't supported in Windows 2012 and later.
To determine Windows OS version, run the 'winver' tool in your virtual machine.

If I use EncryptFormatAll and specify all volume types, will it erase the
data on the data drives that we already encrypted?
No, data won't be erased from data drives that are already encrypted using Azure Disk Encryption. Similar to how
EncryptFormatAll didn't re-encrypt the OS drive, it won't re-encrypt the already encrypted data drive.

Can I backup and restore an encrypted VM?


Azure Backup provides a mechanism to backup and restore encrypted VM's within the same subscription and
region. For instructions, please see Back up and restore encrypted virtual machines with Azure Backup. Restoring
an encrypted VM to a different region is not currently supported.
Where can I go to ask questions or provide feedback?
You can ask questions or provide feedback on the Azure Disk Encryption forum.

Next steps
In this document, you learned more about the most frequent questions related to Azure Disk Encryption. For more
information about this service, see the following articles:
Azure Disk Encryption Overview
Apply disk encryption in Azure Security Center
Azure data encryption at rest
Azure Disk Encryption with Azure AD (previous
release)
10/9/2019 • 2 minutes to read • Edit Online

The new release of Azure Disk Encryption eliminates the requirement for providing an Azure AD
application parameter to enable VM disk encryption. With the new release, you are no longer required
to provide Azure AD credentials during the enable encryption step. All new VMs must be encrypted
without the Azure AD application parameters using the new release. To view instructions to enable VM
disk encryption using the new release, see Azure Disk Encryption for Windows VMs. VMs that were
already encrypted with Azure AD application parameters are still supported and should continue to be
maintained with the AAD syntax.
This article supplements Azure Disk Encryption for Windows VMs with additional requirements and prerequisites
for Azure Disk Encryption with Azure AD (previous release). The Supported VMs and operating systems section
remains the same.

Networking and Group Policy


To enable the Azure Disk Encryption feature using the older AAD parameter syntax, the IaaS VMs must
meet the following network endpoint configuration requirements:
To get a token to connect to your key vault, the IaaS VM must be able to connect to an Azure Active
Directory endpoint, [login.microsoftonline.com].
To write the encryption keys to your key vault, the IaaS VM must be able to connect to the key vault
endpoint.
The IaaS VM must be able to connect to an Azure storage endpoint that hosts the Azure extension
repository and an Azure storage account that hosts the VHD files.
If your security policy limits access from Azure VMs to the Internet, you can resolve the preceding URI and
configure a specific rule to allow outbound connectivity to the IPs. For more information, see Azure Key
Vault behind a firewall.
On Windows, if TLS 1.0 has been explicitly disabled and the .NET version has not been updated to 4.6 or
higher, the following registry change will enable ADE to select the more recent TLS version:

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\v4.0.30319]
"SystemDefaultTlsVersions"=dword:00000001
"SchUseStrongCrypto"=dword:00000001

[HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\.NETFramework\v4.0.30319]
"SystemDefaultTlsVersions"=dword:00000001
"SchUseStrongCrypto"=dword:00000001`

Group Policy:
The Azure Disk Encryption solution uses the BitLocker external key protector for Windows IaaS VMs. For
domain joined VMs, don't push any group policies that enforce TPM protectors. For information about the
group policy for “Allow BitLocker without a compatible TPM,” see BitLocker Group Policy Reference.
BitLocker policy on domain joined virtual machines with custom group policy must include the following
setting: Configure user storage of BitLocker recovery information -> Allow 256-bit recovery key . Azure
Disk Encryption will fail when custom group policy settings for BitLocker are incompatible. On machines
that didn't have the correct policy setting, apply the new policy, force the new policy to update (gpupdate.exe
/force), and then restarting may be required.

Encryption key storage requirements


Azure Disk Encryption requires an Azure Key Vault to control and manage disk encryption keys and secrets. Your
key vault and VMs must reside in the same Azure region and subscription.
For details, see Creating and configuring a key vault for Azure Disk Encryption with Azure AD (previous release).

Next steps
Creating and configuring a key vault for Azure Disk Encryption with Azure AD (previous release)
Enable Azure Disk Encryption with Azure AD on Windows VMs (previous release)
Azure Disk Encryption prerequisites CLI script
Azure Disk Encryption prerequisites PowerShell script
Creating and configuring a key vault for Azure Disk
Encryption with Azure AD (previous release)
10/9/2019 • 15 minutes to read • Edit Online

The new release of Azure Disk Encryption eliminates the requirement for providing an Azure AD
application parameter to enable VM disk encryption. With the new release, you are no longer required
to provide Azure AD credentials during the enable encryption step. All new VMs must be encrypted
without the Azure AD application parameters using the new release. To view instructions to enable VM
disk encryption using the new release, see Azure Disk Encryption. VMs that were already encrypted
with Azure AD application parameters are still supported and should continue to be maintained with
the AAD syntax.
Azure Disk Encryption uses Azure Key Vault to control and manage disk encryption keys and secrets. For more
information about key vaults, see Get started with Azure Key Vault and Secure your key vault.
Creating and configuring a key vault for use with Azure Disk Encryption with Azure AD (previous release) involves
three steps:
1. Create a key vault.
2. Set up an Azure AD application and service principal.
3. Set the key vault access policy for the Azure AD app.
4. Set key vault advanced access policies.
You may also, if you wish, generate or import a key encryption key (KEK).
See the main Creating and configuring a key vault for Azure Disk Encryption article for steps on how to Install
tools and connect to Azure.

NOTE
The steps in this article are automated in the Azure Disk Encryption prerequisites CLI script and Azure Disk Encryption
prerequisites PowerShell script.

Create a key vault


Azure Disk Encryption is integrated with Azure Key Vault to help you control and manage the disk-encryption keys
and secrets in your key vault subscription. You can create a key vault or use an existing one for Azure Disk
Encryption. For more information about key vaults, see Get started with Azure Key Vault and Secure your key
vault. You can use a Resource Manager template, Azure PowerShell, or the Azure CLI to create a key vault.

WARNING
In order to make sure the encryption secrets don’t cross regional boundaries, Azure Disk Encryption needs the Key Vault
and the VMs to be co-located in the same region. Create and use a Key Vault that is in the same region as the VM to be
encrypted.

Create a key vault with PowerShell


You can create a key vault with Azure PowerShell using the New -AzKeyVault cmdlet. For additional cmdlets for
Key Vault, see Az.KeyVault.
1. Create a new resource group, if needed, with New -AzResourceGroup. To list data center locations, use Get-
AzLocation.

# Get-AzLocation
New-AzResourceGroup –Name 'MyKeyVaultResourceGroup' –Location 'East US'

2. Create a new key vault using New -AzKeyVault

New-AzKeyVault -VaultName 'MySecureVault' -ResourceGroupName 'MyKeyVaultResourceGroup' -Location 'East


US'

3. Note the Vault Name, Resource Group Name, Resource ID, Vault URI, and the Object ID that are
returned for later use when you encrypt the disks.
Create a key vault with Azure CLI
You can manage your key vault with Azure CLI using the az keyvault commands. To create a key vault, use az
keyvault create.
1. Create a new resource group, if needed, with az group create. To list locations, use az account list-locations

# To list locations: az account list-locations --output table


az group create -n "MyKeyVaultResourceGroup" -l "East US"

2. Create a new key vault using az keyvault create.

az keyvault create --name "MySecureVault" --resource-group "MyKeyVaultResourceGroup" --location "East


US"

3. Note the Vault Name (name), Resource Group Name, Resource ID (ID ), Vault URI, and the Object ID
that are returned for use later.
Create a key vault with a Resource Manager template
You can create a key vault by using the Resource Manager template.
1. On the Azure quickstart template, click Deploy to Azure.
2. Select the subscription, resource group, resource group location, Key Vault name, Object ID, legal terms, and
agreement, and then click Purchase.

Set up an Azure AD app and service principal


When you need encryption to be enabled on a running VM in Azure, Azure Disk Encryption generates and writes
the encryption keys to your key vault. Managing encryption keys in your key vault requires Azure AD
authentication. Create an Azure AD application for this purpose. For authentication purposes, you can use either
client secret-based authentication or client certificate-based Azure AD authentication.
Set up an Azure AD app and service principal with Azure PowerShell
To execute the following commands, get and use the Azure AD PowerShell module.
1. Use the New -AzADApplication PowerShell cmdlet to create an Azure AD application.
MyApplicationHomePage and the MyApplicationUri can be any values you wish.
$aadClientSecret = "My AAD client secret"
$aadClientSecretSec = ConvertTo-SecureString -String $aadClientSecret -AsPlainText -Force
$azureAdApplication = New-AzADApplication -DisplayName "My Application Display Name" -HomePage
"https://MyApplicationHomePage" -IdentifierUris "https://MyApplicationUri" -Password
$aadClientSecretSec
$servicePrincipal = New-AzADServicePrincipal –ApplicationId $azureAdApplication.ApplicationId

2. The $azureAdApplication.ApplicationId is the Azure AD ClientID and the $aadClientSecret is the client
secret that you will use later to enable Azure Disk Encryption. Safeguard the Azure AD client secret
appropriately. Running $azureAdApplication.ApplicationId will show you the ApplicationID.
Set up an Azure AD app and service principal with Azure CLI
You can manage your service principals with Azure CLI using the az ad sp commands. For more information, see
Create an Azure service principal.
1. Create a new service principal.

az ad sp create-for-rbac --name "ServicePrincipalName" --password "My-AAD-client-secret" --skip-


assignment

2. The appId returned is the Azure AD ClientID used in other commands. It's also the SPN you'll use for az
keyvault set-policy. The password is the client secret that you should use later to enable Azure Disk
Encryption. Safeguard the Azure AD client secret appropriately.
Set up an Azure AD app and service principal though the Azure portal
Use the steps from the Use portal to create an Azure Active Directory application and service principal that can
access resources article to create an Azure AD application. Each step listed below will take you directly to the
article section to complete.
1. Verify required permissions
2. Create an Azure Active Directory application
You can use any name and sign-on URL you would like when creating the application.
3. Get the application ID and the authentication key.
The authentication key is the client secret and is used as the AadClientSecret for Set-
AzVMDiskEncryptionExtension.
The authentication key is used by the application as a credential to sign in to Azure AD. In the
Azure portal, this secret is called keys, but has no relation to key vaults. Secure this secret
appropriately.
The application ID will be used later as the AadClientId for Set-AzVMDiskEncryptionExtension and as
the ServicePrincipalName for Set-AzKeyVaultAccessPolicy.

Set the key vault access policy for the Azure AD app
To write encryption secrets to a specified Key Vault, Azure Disk Encryption needs the Client ID and the Client
Secret of the Azure Active Directory application that has permissions to write secrets to the Key Vault.

NOTE
Azure Disk Encryption requires you to configure the following access policies to your Azure AD client application: WrapKey
and Set permissions.

Set the key vault access policy for the Azure AD app with Azure PowerShell
Your Azure AD application needs rights to access the keys or secrets in the vault. Use the Set-
AzKeyVaultAccessPolicy cmdlet to grant permissions to the application, using the client ID (which was generated
when the application was registered) as the –ServicePrincipalName parameter value. To learn more, see the blog
post Azure Key Vault - Step by Step.
1. Set the key vault access policy for the AD application with PowerShell.

$keyVaultName = 'MySecureVault'
$aadClientID = 'MyAadAppClientID'
$KVRGname = 'MyKeyVaultResourceGroup'
Set-AzKeyVaultAccessPolicy -VaultName $keyVaultName -ServicePrincipalName $aadClientID -
PermissionsToKeys 'WrapKey' -PermissionsToSecrets 'Set' -ResourceGroupName $KVRGname

Set the key vault access policy for the Azure AD app with Azure CLI
Use az keyvault set-policy to set the access policy. For more information, see Manage Key Vault using CLI 2.0.
Give the service principal you created via the Azure CLI access to get secrets and wrap keys with the following
command:

```azurecli-interactive
az keyvault set-policy --name "MySecureVault" --spn "<spn created with CLI/the Azure AD ClientID>" --key-
permissions wrapKey --secret-permissions set
```

Set the key vault access policy for the Azure AD app with the portal
1. Open the resource group with your key vault.
2. Select your key vault, go to Access Policies, then click Add new.
3. Under Select principal, search for the Azure AD application you created and select it.
4. For Key permissions, check Wrap Key under Cryptographic Operations.
5. For Secret permissions, check Set under Secret Management Operations.
6. Click OK to save the access policy.
Set key vault advanced access policies
The Azure platform needs access to the encryption keys or secrets in your key vault to make them available to the
VM for booting and decrypting the volumes. Enable disk encryption on the key vault or deployments will fail.
Set key vault advanced access policies with Azure PowerShell
Use the key vault PowerShell cmdlet Set-AzKeyVaultAccessPolicy to enable disk encryption for the key vault.
Enable Key Vault for disk encryption: EnabledForDiskEncryption is required for Azure Disk encryption.

Set-AzKeyVaultAccessPolicy -VaultName 'MySecureVault' -ResourceGroupName 'MyKeyVaultResourceGroup' -


EnabledForDiskEncryption

Enable Key Vault for deployment, if needed: Enables the Microsoft.Compute resource provider to
retrieve secrets from this key vault when this key vault is referenced in resource creation, for example when
creating a virtual machine.

Set-AzKeyVaultAccessPolicy -VaultName 'MySecureVault' -ResourceGroupName 'MyKeyVaultResourceGroup' -


EnabledForDeployment

Enable Key Vault for template deployment, if needed: Enables Azure Resource Manager to get secrets
from this key vault when this key vault is referenced in a template deployment.

Set-AzKeyVaultAccessPolicy -VaultName 'MySecureVault' -ResourceGroupName 'MyKeyVaultResourceGroup' -


EnabledForTemplateDeployment

Set key vault advanced access policies using the Azure CLI
Use az keyvault update to enable disk encryption for the key vault.
Enable Key Vault for disk encryption: Enabled-for-disk-encryption is required.

az keyvault update --name "MySecureVault" --resource-group "MyKeyVaultResourceGroup" --enabled-for-


disk-encryption "true"

Enable Key Vault for deployment, if needed: Allow Virtual Machines to retrieve certificates stored as
secrets from the vault.

az keyvault update --name "MySecureVault" --resource-group "MyKeyVaultResourceGroup" --enabled-for-


deployment "true"

Enable Key Vault for template deployment, if needed: Allow Resource Manager to retrieve secrets
from the vault.

az keyvault update --name "MySecureVault" --resource-group "MyKeyVaultResourceGroup" --enabled-for-


template-deployment "true"

Set key vault advanced access policies through the Azure portal
1. Select your keyvault, go to Access Policies, and Click to show advanced access policies.
2. Select the box labeled Enable access to Azure Disk Encryption for volume encryption.
3. Select Enable access to Azure Virtual Machines for deployment and/or Enable Access to Azure
Resource Manager for template deployment, if needed.
4. Click Save.

Set up a key encryption key (optional)


If you want to use a key encryption key (KEK) for an additional layer of security for encryption keys, add a KEK to
your key vault. Use the Add-AzKeyVaultKey cmdlet to create a key encryption key in the key vault. You can also
import a KEK from your on-premises key management HSM. For more information, see Key Vault
Documentation. When a key encryption key is specified, Azure Disk Encryption uses that key to wrap the
encryption secrets before writing to Key Vault.
When generating keys, use an RSA key type. Azure Disk Encryption does not yet support using Elliptic
Curve keys.
Your key vault secret and KEK URLs must be versioned. Azure enforces this restriction of versioning. For
valid secret and KEK URLs, see the following examples:
Example of a valid secret URL:
https://contosovault.vault.azure.net/secrets/EncryptionSecretWithKek/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Example of a valid KEK URL:
https://contosovault.vault.azure.net/keys/diskencryptionkek/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Azure Disk Encryption doesn't support specifying port numbers as part of key vault secrets and KEK URLs.
For examples of non-supported and supported key vault URLs, see the following examples:
Unacceptable key vault URL
https://contosovault.vault.azure.net:443/secrets/contososecret/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Acceptable key vault URL:
https://contosovault.vault.azure.net/secrets/contososecret/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Set up a key encryption key with Azure PowerShell
Before using the PowerShell script, you should be familiar with the Azure Disk Encryption prerequisites to
understand the steps in the script. The sample script might need changes for your environment. This script creates
all Azure Disk Encryption prerequisites and encrypts an existing IaaS VM, wrapping the disk encryption key by
using a key encryption key.
# Step 1: Create a new resource group and key vault in the same location.
# Fill in 'MyLocation', 'MyKeyVaultResourceGroup', and 'MySecureVault' with your values.
# Use Get-AzLocation to get available locations and use the DisplayName.
# To use an existing resource group, comment out the line for New-AzResourceGroup

$Loc = 'MyLocation';
$KVRGname = 'MyKeyVaultResourceGroup';
$KeyVaultName = 'MySecureVault';
New-AzResourceGroup –Name $KVRGname –Location $Loc;
New-AzKeyVault -VaultName $KeyVaultName -ResourceGroupName $KVRGname -Location $Loc;
$KeyVault = Get-AzKeyVault -VaultName $KeyVaultName -ResourceGroupName $KVRGname;
$KeyVaultResourceId = (Get-AzKeyVault -VaultName $KeyVaultName -ResourceGroupName $KVRGname).ResourceId;
$diskEncryptionKeyVaultUrl = (Get-AzKeyVault -VaultName $KeyVaultName -ResourceGroupName
$KVRGname).VaultUri;

# Step 2: Create the AD application and service principal.


# Fill in 'MyAADClientSecret', "<My Application Display Name>", "<https://MyApplicationHomePage>", and "
<https://MyApplicationUri>" with your values.
# MyApplicationHomePage and the MyApplicationUri can be any values you wish.

$aadClientSecret = 'MyAADClientSecret';
$aadClientSecretSec = ConvertTo-SecureString -String $aadClientSecret -AsPlainText -Force;
$azureAdApplication = New-AzADApplication -DisplayName "<My Application Display Name>" -HomePage "
<https://MyApplicationHomePage>" -IdentifierUris "<https://MyApplicationUri>" -Password $aadClientSecretSec
$servicePrincipal = New-AzADServicePrincipal –ApplicationId $azureAdApplication.ApplicationId;
$aadClientID = $azureAdApplication.ApplicationId;

#Step 3: Enable the vault for disk encryption and set the access policy for the Azure AD application.

Set-AzKeyVaultAccessPolicy -VaultName $KeyVaultName -ResourceGroupName $KVRGname -EnabledForDiskEncryption;


Set-AzKeyVaultAccessPolicy -VaultName $keyVaultName -ServicePrincipalName $aadClientID -PermissionsToKeys
'WrapKey' -PermissionsToSecrets 'Set' -ResourceGroupName $KVRGname;

#Step 4: Create a new key in the key vault with the Add-AzKeyVaultKey cmdlet.
# Fill in 'MyKeyEncryptionKey' with your value.

$keyEncryptionKeyName = 'MyKeyEncryptionKey';
Add-AzKeyVaultKey -VaultName $KeyVaultName -Name $keyEncryptionKeyName -Destination 'Software';
$keyEncryptionKeyUrl = (Get-AzKeyVaultKey -VaultName $KeyVaultName -Name $keyEncryptionKeyName).Key.kid;

#Step 5: Encrypt the disks of an existing IaaS VM


# Fill in 'MySecureVM' and 'MyVirtualMachineResourceGroup' with your values.

$VMName = 'MySecureVM';
$VMRGName = 'MyVirtualMachineResourceGroup';
Set-AzVMDiskEncryptionExtension -ResourceGroupName $VMRGName -VMName $vmName -AadClientID $aadClientID -
AadClientSecret $aadClientSecret -DiskEncryptionKeyVaultUrl $diskEncryptionKeyVaultUrl -
DiskEncryptionKeyVaultId $KeyVaultResourceId -KeyEncryptionKeyUrl $keyEncryptionKeyUrl -
KeyEncryptionKeyVaultId $KeyVaultResourceId;

Certificate-based authentication (optional)


If you would like to use certificate authentication, you can upload one to your key vault and deploy it to the client.
Before using the PowerShell script, you should be familiar with the Azure Disk Encryption prerequisites to
understand the steps in the script. The sample script might need changes for your environment.

# Fill in "MyKeyVaultResourceGroup", "MySecureVault", and 'MyLocation' ('My location' only if needed)

$KVRGname = 'MyKeyVaultResourceGroup'
$KeyVaultName= 'MySecureVault'

# Create a key vault and set enabledForDiskEncryption property on it.


# Comment out the next three lines if you already have an existing key vault enabled for encryption. No need
to set 'My location' in this case.
to set 'My location' in this case.

$Loc = 'MyLocation'
New-AzKeyVault -VaultName $KeyVaultName -ResourceGroupName $KVRGname -Location $Loc
Set-AzKeyVaultAccessPolicy -VaultName $KeyVaultName -ResourceGroupName $KVRGname -EnabledForDiskEncryption

#Setting some variables with the key vault information


$KeyVault = Get-AzKeyVault -VaultName $KeyVaultName -ResourceGroupName $KVRGname
$DiskEncryptionKeyVaultUrl = $KeyVault.VaultUri
$KeyVaultResourceId = $KeyVault.ResourceId

# Create the Azure AD application and associate the certificate with it.
# Fill in "C:\certificates\mycert.pfx", "Password", "<My Application Display Name>", "
<https://MyApplicationHomePage>", and "<https://MyApplicationUri>" with your values.
# MyApplicationHomePage and the MyApplicationUri can be any values you wish

$CertPath = "C:\certificates\mycert.pfx"
$CertPassword = "Password"
$Cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2($CertPath, $CertPassword)
$CertValue = [System.Convert]::ToBase64String($cert.GetRawCertData())

$AzureAdApplication = New-AzADApplication -DisplayName "<My Application Display Name>" -HomePage "


<https://MyApplicationHomePage>" -IdentifierUris "<https://MyApplicationUri>" -CertValue $CertValue
$ServicePrincipal = New-AzADServicePrincipal -ApplicationId $AzureAdApplication.ApplicationId

$AADClientID = $AzureAdApplication.ApplicationId
$aadClientCertThumbprint= $cert.Thumbprint

Set-AzKeyVaultAccessPolicy -VaultName $keyVaultName -ServicePrincipalName $aadClientID -PermissionsToKeys


'WrapKey' -PermissionsToSecrets 'Set' -ResourceGroupName $KVRGname

# Upload the pfx file to the key vault.


# Fill in "MyAADCert".

$KeyVaultSecretName = "MyAADCert"
$FileContentBytes = get-content $CertPath -Encoding Byte
$FileContentEncoded = [System.Convert]::ToBase64String($fileContentBytes)
$JSONObject = @"
{
"data" : "$filecontentencoded",
"dataType" : "pfx",
"password" : "$CertPassword"
}
"@

$JSONObjectBytes = [System.Text.Encoding]::UTF8.GetBytes($jsonObject)
$JSONEncoded = [System.Convert]::ToBase64String($jsonObjectBytes)

#Set the secret and set the key vault policy for -EnabledForDeployment

$Secret = ConvertTo-SecureString -String $JSONEncoded -AsPlainText -Force


Set-AzKeyVaultSecret -VaultName $KeyVaultName -Name $KeyVaultSecretName -SecretValue $Secret
Set-AzKeyVaultAccessPolicy -VaultName $KeyVaultName -ResourceGroupName $KVRGname -EnabledForDeployment

# Deploy the certificate to the VM


# Fill in 'MySecureVM' and 'MyVirtualMachineResourceGroup' with your values.

$VMName = 'MySecureVM'
$VMRGName = 'MyVirtualMachineResourceGroup'
$CertUrl = (Get-AzKeyVaultSecret -VaultName $KeyVaultName -Name $KeyVaultSecretName).Id
$SourceVaultId = (Get-AzKeyVault -VaultName $KeyVaultName -ResourceGroupName $KVRGName).ResourceId
$VM = Get-AzVM -ResourceGroupName $VMRGName -Name $VMName
$VM = Add-AzVMSecret -VM $VM -SourceVaultId $SourceVaultId -CertificateStore "My" -CertificateUrl $CertUrl
Update-AzVM -VM $VM -ResourceGroupName $VMRGName

#Enable encryption on the VM using Azure AD client ID and the client certificate thumbprint

Set-AzVMDiskEncryptionExtension -ResourceGroupName $VMRGName -VMName $VMName -AadClientID $AADClientID -


AadClientCertThumbprint $AADClientCertThumbprint -DiskEncryptionKeyVaultUrl $DiskEncryptionKeyVaultUrl -
DiskEncryptionKeyVaultId $KeyVaultResourceId
DiskEncryptionKeyVaultId $KeyVaultResourceId

Certificate-based authentication and a KEK (optional)


If you would like to use certificate authentication and wrap the encryption key with a KEK, you can use the below
script as an example. Before using the PowerShell script, you should be familiar with all of the previous Azure Disk
Encryption prerequisites to understand the steps in the script. The sample script might need changes for your
environment.

# Fill in 'MyKeyVaultResourceGroup', 'MySecureVault', and 'MyLocation' (if needed)

$KVRGname = 'MyKeyVaultResourceGroup'
$KeyVaultName= 'MySecureVault'

# Create a key vault and set enabledForDiskEncryption property on it.


# Comment out the next three lines if you already have an existing key vault enabled for encryption.

$Loc = 'MyLocation'
New-AzKeyVault -VaultName $KeyVaultName -ResourceGroupName $KVRGname -Location $Loc
Set-AzKeyVaultAccessPolicy -VaultName $KeyVaultName -ResourceGroupName $KVRGname -EnabledForDiskEncryption

# Create the Azure AD application and associate the certificate with it.
# Fill in "C:\certificates\mycert.pfx", "Password", "<My Application Display Name>", "
<https://MyApplicationHomePage>", and "<https://MyApplicationUri>" with your values.
# MyApplicationHomePage and the MyApplicationUri can be any values you wish

$CertPath = "C:\certificates\mycert.pfx"
$CertPassword = "Password"
$Cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2($CertPath, $CertPassword)
$CertValue = [System.Convert]::ToBase64String($cert.GetRawCertData())

$AzureAdApplication = New-AzADApplication -DisplayName "<My Application Display Name>" -HomePage "


<https://MyApplicationHomePage>" -IdentifierUris "<https://MyApplicationUri>" -CertValue $CertValue
$ServicePrincipal = New-AzADServicePrincipal -ApplicationId $AzureAdApplication.ApplicationId

$AADClientID = $AzureAdApplication.ApplicationId
$aadClientCertThumbprint= $cert.Thumbprint

## Give access for setting secrets and wraping keys


Set-AzKeyVaultAccessPolicy -VaultName $keyVaultName -ServicePrincipalName $aadClientID -PermissionsToKeys
'WrapKey' -PermissionsToSecrets 'Set' -ResourceGroupName $KVRGname

# Upload the pfx file to the key vault.


# Fill in "MyAADCert".

$KeyVaultSecretName = "MyAADCert"
$FileContentBytes = get-content $CertPath -Encoding Byte
$FileContentEncoded = [System.Convert]::ToBase64String($fileContentBytes)
$JSONObject = @"
{
"data" : "$filecontentencoded",
"dataType" : "pfx",
"password" : "$CertPassword"
}
"@

$JSONObjectBytes = [System.Text.Encoding]::UTF8.GetBytes($jsonObject)
$JSONEncoded = [System.Convert]::ToBase64String($jsonObjectBytes)

#Set the secret and set the key vault policy for deployment

$Secret = ConvertTo-SecureString -String $JSONEncoded -AsPlainText -Force


Set-AzKeyVaultSecret -VaultName $KeyVaultName -Name $KeyVaultSecretName -SecretValue $Secret
Set-AzKeyVaultAccessPolicy -VaultName $KeyVaultName -ResourceGroupName $KVRGname -EnabledForDeployment

#Setting some variables with the key vault information and generating a KEK
#Setting some variables with the key vault information and generating a KEK
# FIll in 'KEKName'

$KEKName ='KEKName'
$KeyVault = Get-AzKeyVault -VaultName $KeyVaultName -ResourceGroupName $KVRGname
$DiskEncryptionKeyVaultUrl = $KeyVault.VaultUri
$KeyVaultResourceId = $KeyVault.ResourceId
$KEK = Add-AzKeyVaultKey -VaultName $KeyVaultName -Name $KEKName -Destination "Software"
$KeyEncryptionKeyUrl = $KEK.Key.kid

# Deploy the certificate to the VM


# Fill in 'MySecureVM' and 'MyVirtualMachineResourceGroup' with your values.

$VMName = 'MySecureVM';
$VMRGName = 'MyVirtualMachineResourceGroup';
$CertUrl = (Get-AzKeyVaultSecret -VaultName $KeyVaultName -Name $KeyVaultSecretName).Id
$SourceVaultId = (Get-AzKeyVault -VaultName $KeyVaultName -ResourceGroupName $KVRGName).ResourceId
$VM = Get-AzVM -ResourceGroupName $VMRGName -Name $VMName
$VM = Add-AzVMSecret -VM $VM -SourceVaultId $SourceVaultId -CertificateStore "My" -CertificateUrl $CertUrl
Update-AzVM -VM $VM -ResourceGroupName $VMRGName

#Enable encryption on the VM using Azure AD client ID and the client certificate thumbprint

Set-AzVMDiskEncryptionExtension -ResourceGroupName $VMRGName -VMName $VMName -AadClientID $AADClientID -


AadClientCertThumbprint $AADClientCertThumbprint -DiskEncryptionKeyVaultUrl $DiskEncryptionKeyVaultUrl -
DiskEncryptionKeyVaultId $KeyVaultResourceId -KeyEncryptionKeyUrl $keyEncryptionKeyUrl -
KeyEncryptionKeyVaultId $KeyVaultResourceId

Next steps
Enable Azure Disk Encryption with Azure AD on Windows VMs (previous release)
Azure Disk Encryption with Azure AD for Windows
VMs (previous release)
10/9/2019 • 13 minutes to read • Edit Online

The new release of Azure Disk Encryption eliminates the requirement for providing an Azure AD
application parameter to enable VM disk encryption. With the new release, you are no longer required
to provide Azure AD credentials during the enable encryption step. All new VMs must be encrypted
without the Azure AD application parameters using the new release. To view instructions to enable VM
disk encryption using the new release, see Azure Disk Encryption for Windows VMS. VMs that were
already encrypted with Azure AD application parameters are still supported and should continue to be
maintained with the AAD syntax.
You can enable many disk-encryption scenarios, and the steps may vary according to the scenario. The following
sections cover the scenarios in greater detail for Windows IaaS VMs. Before you can use disk encryption, the
Azure Disk Encryption prerequisites need to be completed.

IMPORTANT
You should take a snapshot and/or create a backup before disks are encrypted. Backups ensure that a recovery
option is possible if an unexpected failure occurs during encryption. VMs with managed disks require a backup before
encryption occurs. Once a backup is made, you can use the Set-AzVMDiskEncryptionExtension cmdlet to encrypt
managed disks by specifying the -skipVmBackup parameter. For more information about how to back up and restore
encrypted VMs, see Back up and restore encrypted Azure VM.
Encrypting or disabling encryption may cause a VM to reboot.

Enable encryption on new IaaS VMs created from the Marketplace


You can enable disk encryption on new IaaS Windows VM from the Marketplace in Azure using a Resource
Manager template. The template creates a new encrypted Windows VM using the Windows Server 2012 gallery
image.
1. On the Resource Manager template, click Deploy to Azure.
2. Select the subscription, resource group, resource group location, parameters, legal terms, and agreement.
Click Purchase to deploy a new IaaS VM where encryption is enabled.
3. After you deploy the template, verify the VM encryption status using your preferred method:
Verify with the Azure CLI by using the az vm encryption show command.

az vm encryption show --name "MySecureVM" --resource-group "MyVirtualMachineResourceGroup"

Verify with Azure PowerShell by using the Get-AzVmDiskEncryptionStatus cmdlet.

Get-AzVmDiskEncryptionStatus -ResourceGroupName 'MyVirtualMachineResourceGroup' -VMName


'MySecureVM'

Select the VM, then click on Disks under the Settings heading to verify encryption status in the
portal. In the chart under Encryption, you'll see if it's enabled.
The following table lists the Resource Manager template parameters for new VMs from the Marketplace scenario
using Azure AD client ID:

PARAMETER DESCRIPTION

adminUserName Admin user name for the virtual machine.

adminPassword Admin user password for the virtual machine.

newStorageAccountName Name of the storage account to store OS and data VHDs.

vmSize Size of the VM. Currently, only Standard A, D, and G series are
supported.

virtualNetworkName Name of the VNet that the VM NIC should belong to.

subnetName Name of the subnet in the VNet that the VM NIC should
belong to.

AADClientID Client ID of the Azure AD application that has permissions to


write secrets to your key vault.

AADClientSecret Client secret of the Azure AD application that has permissions


to write secrets to your key vault.

keyVaultURL URL of the key vault that the BitLocker key should be
uploaded to. You can get it by using the cmdlet
(Get-AzKeyVault -VaultName "MyKeyVault" -
ResourceGroupName
"MyKeyVaultResourceGroupName").VaultURI
or the Azure CLI
az keyvault show --name "MySecureVault" --query
properties.vaultUri

keyEncryptionKeyURL URL of the key encryption key that's used to encrypt the
generated BitLocker key (optional).

KeyEncryptionKeyURL is an optional parameter. You can bring


your own KEK to further safeguard the data encryption key
(Passphrase secret) in your key vault.

keyVaultResourceGroup Resource group of the key vault.


PARAMETER DESCRIPTION

vmName Name of the VM that the encryption operation is to be


performed on.

Enable encryption on existing or running IaaS Windows VMs


In this scenario, you can enable encryption by using a template, PowerShell cmdlets, or CLI commands. The
following sections explain in greater detail how to enable Azure Disk Encryption.
Enable encryption on existing or running VMs with Azure PowerShell
Use the Set-AzVMDiskEncryptionExtension cmdlet to enable encryption on a running IaaS virtual machine in
Azure. For information about enabling encryption with Azure Disk Encryption by using PowerShell cmdlets, see
the blog posts Explore Azure Disk Encryption with Azure PowerShell - Part 1 and Explore Azure Disk Encryption
with Azure PowerShell - Part 2.
Encrypt a running VM using a client secret: The script below initializes your variables and runs the Set-
AzVMDiskEncryptionExtension cmdlet. The resource group, VM, key vault, AAD app, and client secret
should have already been created as prerequisites. Replace MyKeyVaultResourceGroup,
MyVirtualMachineResourceGroup, MySecureVM, MySecureVault, My-AAD -client-ID, and My-AAD -client-
secret with your values.

$KVRGname = 'MyKeyVaultResourceGroup';
$VMRGName = 'MyVirtualMachineResourceGroup';
$vmName = 'MySecureVM';
$aadClientID = 'My-AAD-client-ID';
$aadClientSecret = 'My-AAD-client-secret';
$KeyVaultName = 'MySecureVault';
$KeyVault = Get-AzKeyVault -VaultName $KeyVaultName -ResourceGroupName $KVRGname;
$diskEncryptionKeyVaultUrl = $KeyVault.VaultUri;
$KeyVaultResourceId = $KeyVault.ResourceId;

Set-AzVMDiskEncryptionExtension -ResourceGroupName $VMRGName -VMName $vmName -AadClientID $aadClientID


-AadClientSecret $aadClientSecret -DiskEncryptionKeyVaultUrl $diskEncryptionKeyVaultUrl -
DiskEncryptionKeyVaultId $KeyVaultResourceId;

Encrypt a running VM using KEK to wrap the client secret: Azure Disk Encryption lets you specify an
existing key in your key vault to wrap disk encryption secrets that were generated while enabling
encryption. When a key encryption key is specified, Azure Disk Encryption uses that key to wrap the
encryption secrets before writing to Key Vault.
$KVRGname = 'MyKeyVaultResourceGroup';
$VMRGName = 'MyVirtualMachineResourceGroup';
$vmName = ‘MyExtraSecureVM’;
$aadClientID = 'My-AAD-client-ID';
$aadClientSecret = 'My-AAD-client-secret';
$KeyVaultName = 'MySecureVault';
$keyEncryptionKeyName = 'MyKeyEncryptionKey';
$KeyVault = Get-AzKeyVault -VaultName $KeyVaultName -ResourceGroupName $KVRGname;
$diskEncryptionKeyVaultUrl = $KeyVault.VaultUri;
$KeyVaultResourceId = $KeyVault.ResourceId;
$keyEncryptionKeyUrl = (Get-AzKeyVaultKey -VaultName $KeyVaultName -Name
$keyEncryptionKeyName).Key.kid;

Set-AzVMDiskEncryptionExtension -ResourceGroupName $VMRGname -VMName $vmName -AadClientID $aadClientID


-AadClientSecret $aadClientSecret -DiskEncryptionKeyVaultUrl $diskEncryptionKeyVaultUrl -
DiskEncryptionKeyVaultId $KeyVaultResourceId -KeyEncryptionKeyUrl $keyEncryptionKeyUrl -
KeyEncryptionKeyVaultId $KeyVaultResourceId;

NOTE
The syntax for the value of disk-encryption-keyvault parameter is the full identifier string:
/subscriptions/[subscription-id-guid]/resourceGroups/[resource-group-
name]/providers/Microsoft.KeyVault/vaults/[keyvault-name]
The syntax for the value of the key-encryption-key parameter is the full URI to the KEK as in: https://[keyvault-
name].vault.azure.net/keys/[kekname]/[kek-unique-id]

Verify the disks are encrypted: To check on the encryption status of an IaaS VM, use the Get-
AzVmDiskEncryptionStatus cmdlet.

Get-AzVmDiskEncryptionStatus -ResourceGroupName 'MyVirtualMachineResourceGroup' -VMName 'MySecureVM'

Disable disk encryption: To disable the encryption, use the Disable-AzureRmVMDiskEncryption cmdlet.

Disable-AzVMDiskEncryption -ResourceGroupName 'MyVirtualMachineResourceGroup' -VMName 'MySecureVM'

Enable encryption on existing or running VMs with Azure CLI


Use the az vm encryption enable command to enable encryption on a running IaaS virtual machine in Azure.
Encrypt a running VM using a client secret:

az vm encryption enable --resource-group "MyVirtualMachineResourceGroup" --name "MySecureVM" --aad-


client-id "<my spn created with CLI/my Azure AD ClientID>" --aad-client-secret "My-AAD-client-secret"
--disk-encryption-keyvault "MySecureVault" --volume-type [All|OS|Data]

Encrypt a running VM using KEK to wrap the client secret:

az vm encryption enable --resource-group "MyVirtualMachineResourceGroup" --name "MySecureVM" --aad-


client-id "<my spn created with CLI which is the Azure AD ClientID>" --aad-client-secret "My-AAD-
client-secret" --disk-encryption-keyvault "MySecureVault" --key-encryption-key "MyKEK_URI" --key-
encryption-keyvault "MySecureVaultContainingTheKEK" --volume-type [All|OS|Data]
NOTE
The syntax for the value of disk-encryption-keyvault parameter is the full identifier string:
/subscriptions/[subscription-id-guid]/resourceGroups/[resource-group-
name]/providers/Microsoft.KeyVault/vaults/[keyvault-name]
The syntax for the value of the key-encryption-key parameter is the full URI to the KEK as in: https://[keyvault-
name].vault.azure.net/keys/[kekname]/[kek-unique-id]

Verify the disks are encrypted: To check on the encryption status of an IaaS VM, use the az vm
encryption show command.

az vm encryption show --name "MySecureVM" --resource-group "MyVirtualMachineResourceGroup"

Disable encryption: To disable encryption, use the az vm encryption disable command.

az vm encryption disable --name "MySecureVM" --resource-group "MyVirtualMachineResourceGroup" --volume-


type [ALL, DATA, OS]

Using the Resource Manager template


You can enable disk encryption on existing or running IaaS Windows VMs in Azure by using the Resource
Manager template to encrypt a running Windows VM.
1. On the Azure quickstart template, click Deploy to Azure.
2. Select the subscription, resource group, resource group location, parameters, legal terms, and agreement.
Click Purchase to enable encryption on the existing or running IaaS VM.
The following table lists the Resource Manager template parameters for existing or running VMs that use an
Azure AD client ID:

PARAMETER DESCRIPTION

AADClientID Client ID of the Azure AD application that has permissions to


write secrets to the key vault.

AADClientSecret Client secret of the Azure AD application that has permissions


to write secrets to the key vault.

keyVaultName Name of the key vault that the BitLocker key should be
uploaded to. You can get it by using the cmdlet
(Get-AzKeyVault -ResourceGroupName
<MyKeyVaultResourceGroupName>). Vaultname
or the Azure CLI command
az keyvault list --resource-group "MySecureGroup"

keyEncryptionKeyURL URL of the key encryption key that's used to encrypt the
generated BitLocker key. This parameter is optional if you
select nokek in the UseExistingKek drop-down list. If you
select kek in the UseExistingKek drop-down list, you must
enter the keyEncryptionKeyURL value.

volumeType Type of volume that the encryption operation is performed


on. Valid values are OS, Data, and All.
PARAMETER DESCRIPTION

sequenceVersion Sequence version of the BitLocker operation. Increment this


version number every time a disk-encryption operation is
performed on the same VM.

vmName Name of the VM that the encryption operation is to be


performed on.

New IaaS VMs created from customer-encrypted VHD and encryption


keys
In this scenario, you can enable encrypting by using the Resource Manager template, PowerShell cmdlets, or CLI
commands. The following sections explain in greater detail the Resource Manager template and CLI commands.
Use the instructions in the appendix for preparing pre-encrypted images that can be used in Azure. After the
image is created, you can use the steps in the next section to create an encrypted Azure VM.
Prepare a pre-encrypted Windows VHD
Encrypt VMs with pre -encrypted VHDs with Azure PowerShell
You can enable disk encryption on your encrypted VHD by using the PowerShell cmdlet Set-AzVMOSDisk. The
example below gives you some common parameters.

$VirtualMachine = New-AzVMConfig -VMName "MySecureVM" -VMSize "Standard_A1"


$VirtualMachine = Set-AzVMOSDisk -VM $VirtualMachine -Name "SecureOSDisk" -VhdUri "os.vhd" Caching ReadWrite -
Windows -CreateOption "Attach" -DiskEncryptionKeyUrl
"https://mytestvault.vault.azure.net/secrets/Test1/514ceb769c984379a7e0230bddaaaaaa" -DiskEncryptionKeyVaultId
"/subscriptions/00000000-0000-0000-0000-
000000000000/resourceGroups/myKVresourcegroup/providers/Microsoft.KeyVault/vaults/mytestvault"
New-AzVM -VM $VirtualMachine -ResourceGroupName "MyVirtualMachineResourceGroup"

Enable encryption on a newly added data disk


You can add a new disk to a Windows VM using PowerShell, or through the Azure portal.
Enable encryption on a newly added disk with Azure PowerShell
When using Powershell to encrypt a new disk for Windows VMs, a new sequence version should be specified. The
sequence version has to be unique. The script below generates a GUID for the sequence version. In some cases, a
newly added data disk might be encrypted automatically by the Azure Disk Encryption extension. Auto encryption
usually occurs when the VM reboots after the new disk comes online. This is typically caused because "All" was
specified for the volume type when disk encryption previously ran on the VM. If auto encryption occurs on a
newly added data disk, we recommend running the Set-AzVmDiskEncryptionExtension cmdlet again with new
sequence version. If your new data disk is auto encrypted and you do not wish to be encrypted, decrypt all drives
first then re-encrypt with a new sequence version specifying OS for the volume type.
Encrypt a running VM using a client secret: The script below initializes your variables and runs the Set-
AzVMDiskEncryptionExtension cmdlet. The resource group, VM, key vault, AAD app, and client secret
should have already been created as prerequisites. Replace MyKeyVaultResourceGroup,
MyVirtualMachineResourceGroup, MySecureVM, MySecureVault, My-AAD -client-ID, and My-AAD -client-
secret with your values. This example uses "All" for the -VolumeType parameter, which includes both OS
and Data volumes. If you only want to encrypt the OS volume, use "OS" for the -VolumeType parameter.
$sequenceVersion = [Guid]::NewGuid();
$KVRGname = 'MyKeyVaultResourceGroup';
$VMRGName = 'MyVirtualMachineResourceGroup';
$vmName = 'MySecureVM';
$aadClientID = 'My-AAD-client-ID';
$aadClientSecret = 'My-AAD-client-secret';
$KeyVaultName = 'MySecureVault';
$KeyVault = Get-AzKeyVault -VaultName $KeyVaultName -ResourceGroupName $KVRGname;
$diskEncryptionKeyVaultUrl = $KeyVault.VaultUri;
$KeyVaultResourceId = $KeyVault.ResourceId;

Set-AzVMDiskEncryptionExtension -ResourceGroupName $VMRGname -VMName $vmName -AadClientID $aadClientID


-AadClientSecret $aadClientSecret -DiskEncryptionKeyVaultUrl $diskEncryptionKeyVaultUrl -
DiskEncryptionKeyVaultId $KeyVaultResourceId -VolumeType 'all' –SequenceVersion $sequenceVersion;

Encrypt a running VM using KEK to wrap the client secret: Azure Disk Encryption lets you specify an
existing key in your key vault to wrap disk encryption secrets that were generated while enabling
encryption. When a key encryption key is specified, Azure Disk Encryption uses that key to wrap the
encryption secrets before writing to Key Vault. This example uses "All" for the -VolumeType parameter,
which includes both OS and Data volumes. If you only want to encrypt the OS volume, use "OS" for the -
VolumeType parameter.

$sequenceVersion = [Guid]::NewGuid();
$KVRGname = 'MyKeyVaultResourceGroup';
$VMRGName = 'MyVirtualMachineResourceGroup';
$vmName = 'MyExtraSecureVM';
$aadClientID = 'My-AAD-client-ID';
$aadClientSecret = 'My-AAD-client-secret';
$KeyVaultName = 'MySecureVault';
$keyEncryptionKeyName = 'MyKeyEncryptionKey';
$KeyVault = Get-AzKeyVault -VaultName $KeyVaultName -ResourceGroupName $KVRGname;
$diskEncryptionKeyVaultUrl = $KeyVault.VaultUri;
$KeyVaultResourceId = $KeyVault.ResourceId;
$keyEncryptionKeyUrl = (Get-AzKeyVaultKey -VaultName $KeyVaultName -Name
$keyEncryptionKeyName).Key.kid;

Set-AzVMDiskEncryptionExtension -ResourceGroupName $VMRGname -VMName $vmName -AadClientID $aadClientID


-AadClientSecret $aadClientSecret -DiskEncryptionKeyVaultUrl $diskEncryptionKeyVaultUrl -
DiskEncryptionKeyVaultId $KeyVaultResourceId -KeyEncryptionKeyUrl $keyEncryptionKeyUrl -
KeyEncryptionKeyVaultId $KeyVaultResourceId -VolumeType 'all' –SequenceVersion $sequenceVersion;

NOTE
The syntax for the value of disk-encryption-keyvault parameter is the full identifier string:
/subscriptions/[subscription-id-guid]/resourceGroups/[resource-group-
name]/providers/Microsoft.KeyVault/vaults/[keyvault-name]
The syntax for the value of the key-encryption-key parameter is the full URI to the KEK as in: https://[keyvault-
name].vault.azure.net/keys/[kekname]/[kek-unique-id]

Enable encryption on a newly added disk with Azure CLI


The Azure CLI command will automatically provide a new sequence version for you when you run the command
to enable encryption. Acceptable values for the volume-yype parameter are All, OS, and Data. You may need to
change the volume-type parameter to OS or Data if you're only encrypting one type of disk for the VM. The
examples use "All" for the volume-type parameter.
Encrypt a running VM using a client secret:
az vm encryption enable --resource-group "MyVirtualMachineResourceGroup" --name "MySecureVM" --aad-
client-id "<my spn created with CLI/my Azure AD ClientID>" --aad-client-secret "My-AAD-client-secret"
--disk-encryption-keyvault "MySecureVault" --volume-type "All"

Encrypt a running VM using KEK to wrap the client secret:

az vm encryption enable --resource-group "MyVirtualMachineResourceGroup" --name "MySecureVM" --aad-


client-id "<my spn created with CLI which is the Azure AD ClientID>" --aad-client-secret "My-AAD-
client-secret" --disk-encryption-keyvault "MySecureVault" --key-encryption-key "MyKEK_URI" --key-
encryption-keyvault "MySecureVaultContainingTheKEK" --volume-type "all"

Enable encryption using Azure AD client certificate-based


authentication.
You can use client certificate authentication with or without KEK. Before using the PowerShell scripts, you should
already have the certificate uploaded to the key vault and deployed to the VM. If you're using KEK too, the KEK
should already exist. For more information, see the Certificate-based authentication for Azure AD section of the
prerequisites article.
Enable encryption using certificate -based authentication with Azure PowerShell

## Fill in 'MyVirtualMachineResourceGroup', 'MyKeyVaultResourceGroup', 'My-AAD-client-ID', 'MySecureVault, and


‘MySecureVM’.

$VMRGName = 'MyVirtualMachineResourceGroup'
$KVRGname = 'MyKeyVaultResourceGroup';
$AADClientID ='My-AAD-client-ID';
$KeyVaultName = 'MySecureVault';
$VMName = 'MySecureVM';
$KeyVault = Get-AzKeyVault -VaultName $KeyVaultName -ResourceGroupName $KVRGname;
$diskEncryptionKeyVaultUrl = $KeyVault.VaultUri;
$KeyVaultResourceId = $KeyVault.ResourceId;

# Fill in the certificate path and the password so the thumbprint can be set as a variable.

$certPath = '$CertPath = "C:\certificates\mycert.pfx';


$CertPassword ='Password'
$Cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2($CertPath, $CertPassword)
$aadClientCertThumbprint = $cert.Thumbprint;

# Enable disk encryption using the client certificate thumbprint

Set-AzVMDiskEncryptionExtension -ResourceGroupName $VMRGName -VMName $VMName -AadClientID $AADClientID -


AadClientCertThumbprint $AADClientCertThumbprint -DiskEncryptionKeyVaultUrl $DiskEncryptionKeyVaultUrl -
DiskEncryptionKeyVaultId $KeyVaultResourceId

Enable encryption using certificate -based authentication and a KEK with Azure PowerShell
# Fill in 'MyVirtualMachineResourceGroup', 'MyKeyVaultResourceGroup', 'My-AAD-client-ID', 'MySecureVault,,
'MySecureVM’, and "KEKName.

$VMRGName = 'MyVirtualMachineResourceGroup';
$KVRGname = 'MyKeyVaultResourceGroup';
$AADClientID ='My-AAD-client-ID';
$KeyVaultName = 'MySecureVault';
$VMName = 'MySecureVM';
$keyEncryptionKeyName ='KEKName';
$KeyVault = Get-AzKeyVault -VaultName $KeyVaultName -ResourceGroupName $KVRGname;
$diskEncryptionKeyVaultUrl = $KeyVault.VaultUri;
$KeyVaultResourceId = $KeyVault.ResourceId;
$keyEncryptionKeyUrl = (Get-AzKeyVaultKey -VaultName $KeyVaultName -Name $keyEncryptionKeyName).Key.kid;

## Fill in the certificate path and the password so the thumbprint can be read and set as a variable.

$certPath = '$CertPath = "C:\certificates\mycert.pfx';


$CertPassword ='Password'
$Cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2($CertPath, $CertPassword)
$aadClientCertThumbprint = $cert.Thumbprint;

# Enable disk encryption using the client certificate thumbprint and a KEK

Set-AzVMDiskEncryptionExtension -ResourceGroupName $VMRGName -VMName $VMName -AadClientID $AADClientID -


AadClientCertThumbprint $AADClientCertThumbprint -DiskEncryptionKeyVaultUrl $DiskEncryptionKeyVaultUrl -
DiskEncryptionKeyVaultId $KeyVaultResourceId -KeyEncryptionKeyUrl $keyEncryptionKeyUrl -
KeyEncryptionKeyVaultId $KeyVaultResourceId

Disable encryption
You can disable encryption using Azure PowerShell, the Azure CLI, or with a Resource Manager template.
Disable disk encryption with Azure PowerShell: To disable the encryption, use the Disable-Azure
RmVMDiskEncryption cmdlet.

Disable-AzVMDiskEncryption -ResourceGroupName 'MyVirtualMachineResourceGroup' -VMName 'MySecureVM'

Disable encryption with the Azure CLI: To disable encryption, use the az vm encryption disable
command.

az vm encryption disable --name "MySecureVM" --resource-group "MyVirtualMachineResourceGroup" --volume-


type [ALL, DATA, OS]

Disable encryption with a Resource Manager Template:


1. Click Deploy to Azure from the Disable disk encryption on running Windows VM template.
2. Select the subscription, resource group, location, VM, legal terms, and agreement.
3. Click Purchase to disable disk encryption on a running Windows VM.

Next steps
Azure Disk Encryption overview
Setting up WinRM access for Virtual Machines in
Azure Resource Manager
11/13/2019 • 3 minutes to read • Edit Online

Here are the steps you need to take to set up a VM with WinRM connectivity
1. Create a Key Vault
2. Create a self-signed certificate
3. Upload your self-signed certificate to Key Vault
4. Get the URL for your self-signed certificate in the Key Vault
5. Reference your self-signed certificates URL while creating a VM

Step 1: Create a Key Vault


You can use the below command to create the Key Vault

New-AzKeyVault -VaultName "<vault-name>" -ResourceGroupName "<rg-name>" -Location "<vault-location>" -


EnabledForDeployment -EnabledForTemplateDeployment

Step 2: Create a self-signed certificate


You can create a self-signed certificate using this PowerShell script

$certificateName = "somename"

$thumbprint = (New-SelfSignedCertificate -DnsName $certificateName -CertStoreLocation Cert:\CurrentUser\My -


KeySpec KeyExchange).Thumbprint

$cert = (Get-ChildItem -Path cert:\CurrentUser\My\$thumbprint)

$password = Read-Host -Prompt "Please enter the certificate password." -AsSecureString

Export-PfxCertificate -Cert $cert -FilePath ".\$certificateName.pfx" -Password $password

Step 3: Upload your self-signed certificate to the Key Vault


Before uploading the certificate to the Key Vault created in step 1, it needs to converted into a format the
Microsoft.Compute resource provider will understand. The below PowerShell script will allow you do that
$fileName = "<Path to the .pfx file>"
$fileContentBytes = Get-Content $fileName -Encoding Byte
$fileContentEncoded = [System.Convert]::ToBase64String($fileContentBytes)

$jsonObject = @"
{
"data": "$filecontentencoded",
"dataType" :"pfx",
"password": "<password>"
}
"@

$jsonObjectBytes = [System.Text.Encoding]::UTF8.GetBytes($jsonObject)
$jsonEncoded = [System.Convert]::ToBase64String($jsonObjectBytes)

$secret = ConvertTo-SecureString -String $jsonEncoded -AsPlainText –Force


Set-AzKeyVaultSecret -VaultName "<vault name>" -Name "<secret name>" -SecretValue $secret

Step 4: Get the URL for your self-signed certificate in the Key Vault
The Microsoft.Compute resource provider needs a URL to the secret inside the Key Vault while provisioning the
VM. This enables the Microsoft.Compute resource provider to download the secret and create the equivalent
certificate on the VM.

NOTE
The URL of the secret needs to include the version as well. An example URL looks like below
https://contosovault.vault.azure.net:443/secrets/contososecret/01h9db0df2cd4300a20ence585a6s7ve

Templates
You can get the link to the URL in the template using the below code

"certificateUrl": "[reference(resourceId(resourceGroup().name, 'Microsoft.KeyVault/vaults/secrets', '<vault-


name>', '<secret-name>'), '2015-06-01').secretUriWithVersion]"

PowerShell
You can get this URL using the below PowerShell command

$secretURL = (Get-AzKeyVaultSecret -VaultName "<vault name>" -Name "<secret name>").Id

Step 5: Reference your self-signed certificates URL while creating a VM


Azure Resource Manager Templates
While creating a VM through templates, the certificate gets referenced in the secrets section and the winRM
section as below:
"osProfile": {
...
"secrets": [
{
"sourceVault": {
"id": "<resource id of the Key Vault containing the secret>"
},
"vaultCertificates": [
{
"certificateUrl": "<URL for the certificate you got in Step 4>",
"certificateStore": "<Name of the certificate store on the VM>"
}
]
}
],
"windowsConfiguration": {
...
"winRM": {
"listeners": [
{
"protocol": "http"
},
{
"protocol": "https",
"certificateUrl": "<URL for the certificate you got in Step 4>"
}
]
},
...
}
},

A sample template for the above can be found here at 201-vm-winrm-keyvault-windows


Source code for this template can be found on GitHub
PowerShell

$vm = New-AzVMConfig -VMName "<VM name>" -VMSize "<VM Size>"


$credential = Get-Credential
$secretURL = (Get-AzKeyVaultSecret -VaultName "<vault name>" -Name "<secret name>").Id
$vm = Set-AzVMOperatingSystem -VM $vm -Windows -ComputerName "<Computer Name>" -Credential $credential -
WinRMHttp -WinRMHttps -WinRMCertificateUrl $secretURL
$sourceVaultId = (Get-AzKeyVault -ResourceGroupName "<Resource Group name>" -VaultName "<Vault
Name>").ResourceId
$CertificateStore = "My"
$vm = Add-AzVMSecret -VM $vm -SourceVaultId $sourceVaultId -CertificateStore $CertificateStore -CertificateUrl
$secretURL

Step 6: Connecting to the VM


Before you can connect to the VM you'll need to make sure your machine is configured for WinRM remote
management. Start PowerShell as an administrator and execute the below command to make sure you're set up.

Enable-PSRemoting -Force

NOTE
You might need to make sure the WinRM service is running if the above does not work. You can do that using
Get-Service WinRM
Once the setup is done, you can connect to the VM using the below command

Enter-PSSession -ConnectionUri https://<public-ip-dns-of-the-vm>:5986 -Credential $cred -SessionOption (New-


PSSessionOption -SkipCACheck -SkipCNCheck -SkipRevocationCheck) -Authentication Negotiate
What is role-based access control (RBAC) for Azure
resources?
12/23/2019 • 7 minutes to read • Edit Online

Access management for cloud resources is a critical function for any organization that is using the cloud. Role-
based access control (RBAC ) helps you manage who has access to Azure resources, what they can do with those
resources, and what areas they have access to.
RBAC is an authorization system built on Azure Resource Manager that provides fine-grained access management
of Azure resources.

What can I do with RBAC?


Here are some examples of what you can do with RBAC:
Allow one user to manage virtual machines in a subscription and another user to manage virtual networks
Allow a DBA group to manage SQL databases in a subscription
Allow a user to manage all resources in a resource group, such as virtual machines, websites, and subnets
Allow an application to access all resources in a resource group

Best practice for using RBAC


Using RBAC, you can segregate duties within your team and grant only the amount of access to users that they
need to perform their jobs. Instead of giving everybody unrestricted permissions in your Azure subscription or
resources, you can allow only certain actions at a particular scope.
When planning your access control strategy, it's a best practice to grant users the least privilege to get their work
done. The following diagram shows a suggested pattern for using RBAC.

How RBAC works


The way you control access to resources using RBAC is to create role assignments. This is a key concept to
understand – it’s how permissions are enforced. A role assignment consists of three elements: security principal,
role definition, and scope.
Security principal
A security principal is an object that represents a user, group, service principal, or managed identity that is
requesting access to Azure resources.

User - An individual who has a profile in Azure Active Directory. You can also assign roles to users in other
tenants. For information about users in other organizations, see Azure Active Directory B2B.
Group - A set of users created in Azure Active Directory. When you assign a role to a group, all users within
that group have that role.
Service principal - A security identity used by applications or services to access specific Azure resources. You
can think of it as a user identity (username and password or certificate) for an application.
Managed identity - An identity in Azure Active Directory that is automatically managed by Azure. You typically
use managed identities when developing cloud applications to manage the credentials for authenticating to
Azure services.
Role definition
A role definition is a collection of permissions. It's typically just called a role. A role definition lists the operations
that can be performed, such as read, write, and delete. Roles can be high-level, like owner, or specific, like virtual
machine reader.

Azure includes several built-in roles that you can use. The following lists four fundamental built-in roles. The first
three apply to all resource types.
Owner - Has full access to all resources including the right to delegate access to others.
Contributor - Can create and manage all types of Azure resources but can’t grant access to others.
Reader - Can view existing Azure resources.
User Access Administrator - Lets you manage user access to Azure resources.
The rest of the built-in roles allow management of specific Azure resources. For example, the Virtual Machine
Contributor role allows a user to create and manage virtual machines. If the built-in roles don't meet the specific
needs of your organization, you can create your own custom roles for Azure resources.
Azure has data operations that enable you to grant access to data within an object. For example, if a user has read
data access to a storage account, then they can read the blobs or messages within that storage account. For more
information, see Understand role definitions for Azure resources.
Scope
Scope is the set of resources that the access applies to. When you assign a role, you can further limit the actions
allowed by defining a scope. This is helpful if you want to make someone a Website Contributor, but only for one
resource group.
In Azure, you can specify a scope at multiple levels: management group, subscription, resource group, or resource.
Scopes are structured in a parent-child relationship.

When you grant access at a parent scope, those permissions are inherited to the child scopes. For example:
If you assign the Owner role to a user at the management group scope, that user can manage everything in all
subscriptions in the management group.
If you assign the Reader role to a group at the subscription scope, the members of that group can view every