Saturday, July 26, 2014

Azure Virtual Machine using Powershell – common operations


This is very common scenario I have observed, many times the IT guys need to perform day to day tasks of Azure with the help of Powershell command and he finds dozens of ways to do it. In this post I am providing the list of all common and basic operation of Azure Virtual Machine using Powershell. If I have missed any operation on Azure virtual machine with powershell, then feel free to comment.
To perform any task in powershell there are numerous ways, I will be showing the easiest way to achieve it. As expected this post is also going to be big one!!!
Setting up Azure Account on Powershell window
This is mandatory step. Without this setup you cannot perform a single operation using Azure powershell. There are two ways to set up your credentials in Azure Powershell. One is to use Azure publish settings files and importing in powershell or you can directly login credentials by using Add-AzureAccount. Here I am depicting the second way –
#add azure account to powershell current session
Set-ExecutionPolicy RemoteSigned
Add-AzureAccount
Select-AzureSubscription -SubscriptionName  "Your Subscription name" 

Setting up Storage Account
Azure Virtual machine disks and images are stored in Azure Storage therefore we need to have storage account. If you have an existing storage account then definitely you can use that or create new. Following commands specify how you can create a new storage account and also depicts how can you turn ON or OFF the geo replication for account. I don’t wanted to have geo replication therefore to save on cost I am making locally redundant by specifying
-GeoReplicationEnabled  $false
Here are the complete commands –
#this section is required only if you don't have storage account available, if you have one ready then use that.
#set storage account details
$location = "West Europe"
#this can be any location of your choice
$storageAccountName = "YourStorageAccountName"
#set geo replication to locally redundant. If you wish to setup to Geo redundant then set below parameter to $true
Set-AzureStorageAccount  -StorageAccountName  $storageAccountName -GeoReplicationEnabled  $false

#set newly created storage account for current subscription
Set-Azuresubscription -SubscriptionName "YourSubscriptionName" -CurrentStorageAccountname $storageAccountName

Setting up Azure cloud Service (Optional)
Following command actually create a cloud service in your subscription, if you any cloud service existing then you can use the same to deploy your vm –
#create cloud service, if already present then you can use that
$cloudServiceName = "YourCloudServiceName"
New-AzureService -ServiceName $cloudServiceName -Location $locations


Selecting latest published Azure Virtual Machine Image using powershell
First run the command –
Get-AzureVMImage
This lists down all the VM images available. I will be taking the entire article with respect to Azure virtual Machine SQL Server with powershell therefore I searched for SQL Server family as shown below –
 
I used following command to list images based on published date in descending order so that I can select the latest image available in the location and here is the result screenshot.
#retrieve the latest image of your choice based on published date
$images = Get-AzureVMImage | where { $_.ImageFamily -eq "SQL Server 2012 SP1 Enterprise on Windows Server 2012" } | where { $_.Location.Split(";") -contains $location } | Sort-Object -Descending -Property PublishedDate 

$latestImage = $images[0]
$latestImage

 
Highlighted area shows the latest version available for SQL Server as on today in West Europe region and it got selected correctly.

Set up Credentials for Azure Virtual Machine using Powershell
In this step let’s setup the credentials for Azure virtual machine. Firs declare the variables with appropriate values –
#set virtual machine variables
$vmName = "YourVMName"
$adminLogin = "YourUserName"
$adminPasswd = "YourPassword"
Create Azure virtual Machine using Powershell
Let’s first define the VM specific variables as follows –
#set virtual machine variables
$vmName = "powershellvm"#should not be more that 13 characters as of now
$instanceSize = "Basic_A1"
#Possible values - #ExtraSmall,Small,Medium,Large,ExtraLarge,A5,A6,A7,A8,A9,Basic_A0,Basic_A1,Basic_A2,Basic_A3, Basic_A4
Below this point all commands uses variables declared above. So in case you are not able to understand from where the particular variable values come, do not hesitate to look above this point. J


Caution – When you are creating azure virtual machine using New-AzureQuickVM command and you are providing already created cloud service name along with location then you will receive an error as -
Service already exists, Location cannot be specified.
To avoid this error there are two resolutions –

 


1.     If you are specifying already created cloud service name then do not specify the location parameter in the command. Command will be as follows –

New-AzureQuickVM -ImageName $latestImage.ImageName -Windows -Name $vmName -ServiceName "ExistingcloudServiceName" -AdminUsername $adminLogin -Password $adminPasswd -InstanceSize $instanceSize
2.     If you are specifying cloud service name which is not created in subscription then specify location parameter as well –
      New-AzureQuickVM -ImageName $latestImage.ImageName -Windows -Name $vmName -ServiceName "yourNonexistingcloudServiceName" -AdminUsername $adminLogin -Password $adminPasswd -Location $location -InstanceSize $instanceSize

Download Azure VM RDP using Powershell
Following command can be used to download he Azure VM RDP file to your desktop using powershell –
#download rdp file for Azure VM to your desktop
$localPath =  "$ENV:userprofile\Desktop\" + $vmName +".rdp"
Get-AzureRemoteDesktopFile -ServiceName $cloudServiceName -Name $vmName -LocalPath $localPaths
Change the size of azure virtual machine using powershell
#change the size of azure vm
$vmObject = Get-AzureVM -ServiceName $cloudServiceName -Name $vmName
Set-AzureVMSize -VM $vmObject -InstanceSize "NewSize" | Update-AzureVM

NewSize in above command can be specified any of the following -
#ExtraSmall,Small,Medium,Large,ExtraLarge,A5,A6,A7,A8,A9,Basic_A0,Basic_A1,Basic_A2,Basic_A3, Basic_A4
Add an Endpoint to Azure virtual Machine
Get-AzureVM -ServiceName $cloudServiceName -Name $vmName | Add-AzureEndpoint -Name "Http" -Protocol "tcp" -PublicPort 80 -LocalPort 80 | Update-AzureVM

 In above code you can change the port number and name as per your choice.
Attach disk to Azure virtual machine using powershell
Attach new disk to azure vm –
#add newdisk to azure vm
Get-AzureVM -ServiceName $cloudServiceName -Name $vmName | Add-AzureDataDisk -CreateNew -DiskSizeInGB 8 -LUN 1 -DiskLabel "YourDiskLabel" | Update-AzureVM
The above command creates a data disk and attaches to azure virtual machine. In above command you can change the size, label as per your choice.
In Above command LUN stands for Logical Unit Number, and it can vary from 1 to 15 only which means any virtual machine in azure can have maximum 15 data disks attached. Also LUN for each disk has to be unique.
Attach existing data disk from library to azure virtual machine using powershell –
Get-AzureVM -ServiceName $cloudServiceName -Name $vmName | Add-AzureDataDisk -Import -DiskName "YoudiskName" -LUN 2 | Update-AzureVM
You can get the name of data disk to be attached from azure portal. Here as I had attached a disk on LUN 1 therefore I attached another disk on LUN 2.
Attaching data disk to azure virtual machine from blob storage using powershell-
Get-AzureVM -ServiceName $cloudServiceName -Name $vmName | Add-AzureDataDisk -ImportFrom -MediaLocation "https://StorageAccountName.blob.core.windows.net/vhds/yourVhd.vhd" -disklabel "mydatadisk" -LUN 1 |Update-AzureVM

Caution – If you try to use the disk that was already attached to any running VM then you need to first detach the disk.  You can use below powershell option to detach the disk – section - Detach data disk from Azure virtual machine. After this, on management portal you may observe that disk is not attached to any of the VM and “Attached To” column is empty.
After this if you run above command to attach the disk from blob storage then you may receive error as  - The VHD is already registered with image repository as the resource with ID.
To resolve this error you will need to delete the disk but retain the associated vhd. For this you can use below powershell command to delete the disk but to retain the associated vhd –
#attach vhd from blob storage to azure VM as disk
Get-AzureVM -ServiceName $cloudServiceName -Name $vmName | Add-AzureDataDisk -ImportFrom -MediaLocation "https://YourStorageAccount.blob.core.windows.net/vhds/YourVhdName.vhd" -disklabel "YourDiskLabel" -LUN 3 | Update-AzureVM

Detach data disk from Azure virtual machine using powershell
First let’s retrieve the list of attached disks to azure VM then based on returned list you can choose which data disk to remove  from azure virtual machine –
Get-AzureVM -ServiceName $cloudServiceName -name $vmName | Get-AzureDataDisk
Following screenshot show the number of disks attached to azure virtual machine. In my case I have only 1 disk attached therefore I am removing the disk having LUN as 1.
 

Remove command is as follows –
#remove the data disk
Get-AzureVM -ServiceName $cloudServiceName -name $vmName | Remove-AzureDataDisk -LUN 1 | Update-AzureVM
When you invoke above command, the attached disk is only detached from the azure virtual machine and it is not deleted from storage. Therefore it will be your responsibility to get it removed from azure storage location. Following screenshot shows the same –


Start, Stop, Restart and Delete Azure Virtual machine using powershell
1.     Using below command your virtual machine will stop however it will not go in Deallocated state. The state of virtual machine will be “Stopped” and hence you will be charged. However, your provisioned IP will not be lost.
Stop-AzureVM -Name $vmName -ServiceName $cloudServiceName –StayProvisioned
2.     Using below command your virtual machine will be in Stopped(Deallocated) state and hence you will not be charged, however your public IP will be lost.
 
Stop-AzureVM -Name $vmName -ServiceName $cloudServiceName –Force 

3.     Restart Azure VM –
 
Restart-AzureVM -Name $vmName -ServiceName $cloudServiceName 

4.     Remove/ delete azure VM along with associated vhd

Remove-AzureVM -ServiceName $cloudServiceName -Name $vmName –DeleteVHD 


Important – Please suggest your Feedback/ Changes / Comments to the article to improve it.
To download full source code refer to the link - http://code.msdn.microsoft.com/Azure-Virtual-Machine-cac3b231
Hope this helps.
Cheers!!

3 comments:

  1. Great Script for beginners. I'm working first time with powershell and I like it.

    But there is an error in this snippet:
    $localPath = "$ENV:userprofile\Desktop\" + $vmName +".rdp"

    Get-AzureRemoteDesktopFile -ServiceName $cloudServiceName -Name $vmName -LocalPath $localPaths

    the last s is too much :)

    correct is $localPath = "$ENV:userprofile\Desktop\" + $vmName +".rdp"

    Get-AzureRemoteDesktopFile -ServiceName $cloudServiceName -Name $vmName -LocalPath $localPath (without s in localPaths)

    ReplyDelete
  2. Your blog provided us with valuable information to work with. Thanks a lot for sharing.
    Discount coupon

    ReplyDelete