Access Azure VM with PowerShell and MS Live credentials - powershell

I want to change the size an Azure VM with powershell. The reason is: I use machine for development. I need A2 size for 4 hours a day. The owner of the VM asked to switch the size of the machine to A0 when I do not develop. I have access to the Azure subscription with my MS Live account. Now I change the size manually through Azure Portal. I want to automate this task with PowerShell. The script should set the size to A2, wait for 4 hours and set it back to A0. I just want to doubleclick the script before starting my development and just forget about the question.
I have the following understanding of the general procedure:
Run Import-AzurePublishSettings
Run Select-AzureSubscription
Get VM object with Get-AzureVM
Run Set-AzureVMSize
Update-AzureVM
I can not get publish profile, because I do not own the machine. Is there a way to authenticate with MS Live account?

Skip the Import-Azurepublish and do a Add-AzureAccount instead. That will popup UI for authenticating with your MS Live account.
Once that is done you can use Select-AzureSubscription
For Classic Deployment you need this:
# authenticate if no account is already added to the powershell session
if (!(Get-AzureAccount)){ Add-AzureAccount }
# Get the vm object out of azure
$vm = get-azurevm | where name -eq "name of the vm"
# Now all you need is to is update the VM with its new size:
$vm | Set-AzureVMSize -InstanceSize Medium | Update-AzureVM
If the VM is deployed via the Resource Manager (RM Model)
if (!(Get-AzureRMContext)){ Add-AzureRmAccount }
Select-AzureRmSubscription -SubscriptionId "{subscriptionId}"
$vm = Get-AzureRmVm | where name -eq "{vmName}"
$vm.HardwareProfile.vmSize = "Medium"
Update-AzureRmVM -VM $vm
btw. Medium is what A2 is called in the API.

Related

Configure Windows Defender for VMs in Scaleset

I have an Azure Scaleset with 5 VMs in it. When I deploy my app (service fabric app) to the scaleset, Windows Defender Real Time Protection is causing the CPU/Memory to max out. I think this is because there are no appropriate exclusions set up in the Windows Defender software.
Can anyone tell me if I can configure the exclusions on each VM without having to RDP on to all of the VMs?
Generally this is VM level config and so is usually managed via a custom VM image that already has things set up or via a VM extension that configures Defender as a part of the machine coming up (this is similar to #jason-ye-msft 's answer). There's some similar guidance around setting up antimalware in a cluster here.
# Script to add Microsoft Antimalware extension to VM Scale Set(VMSS) and Service Fabric Cluster(in turn it used VMSS)
# Login to your Azure Resource Manager Account and select the Subscription to use
Login-AzureRmAccount
# Specify your subscription ID
#$subscriptionId="SUBSCRIPTION ID HERE"
Select-AzureRmSubscription -SubscriptionId $subscriptionId
# Specify location, resource group, and VM Scaleset for the extension
#$location = "LOCATION HERE" # eg., “West US or Southeast Asia” or “Central US”
#$resourceGroupName = "RESOURCE GROUP NAME HERE"
#$vmScaleSetName = "YOUR VM SCALE SET NAME"
# Configuration.JSON configuration file can be customized as per MSDN documentation: https://msdn.microsoft.com/en-us/library/dn771716.aspx
#$settingString = ‘{"AntimalwareEnabled": true}’;
# retrieve the most recent version number of the extension
$allVersions= (Get-AzureRmVMExtensionImage -Location $location -PublisherName “Microsoft.Azure.Security” -Type “IaaSAntimalware”).Version
$versionString = $allVersions[($allVersions.count)-1].Split(“.”)[0] + “.” + $allVersions[($allVersions.count)-1].Split(“.”)[1]
$VMSS = Get-AzureRmVmss -ResourceGroupName $resourceGroupName -VMScaleSetName $vmScaleSetName
Add-AzureRmVmssExtension -VirtualMachineScaleSet $VMSS -Name “IaaSAntimalware” -Publisher “Microsoft.Azure.Security” -Type “IaaSAntimalware” -TypeHandlerVersion $versionString
Update-AzureRmVmss -ResourceGroupName $resourceGroupName -Name $vmScaleSetName -VirtualMachineScaleSet $VMSS
The Service Fabric team does have guidance on how to configure your environment that includes the information about the exclusions you'd want to add. Those include:
Antivirus Excluded directories
Program Files\Microsoft Service Fabric
FabricDataRoot (from cluster configuration)
FabricLogRoot (from cluster configuration)
Antivirus Excluded processes
Fabric.exe
FabricHost.exe
FabricInstallerService.exe
FabricSetup.exe
FabricDeployer.exe
ImageBuilder.exe
FabricGateway.exe
FabricDCA.exe
FabricFAS.exe
FabricUOS.exe
FabricRM.exe
FileStoreService.exe
It's not clear if there's a good way to set up those exclusions at the same time that you're enabling antimalware scanning.
Can anyone tell me if I can configure the exclusions on each VM
without having to RDP on to all of the VMs?
Based on my knowledge, you should configure the exclusion for your image, then upload this image to Azure, then use this image to create new VMSS, in this way, after your increase your VMSS instance, newly created vmss instances will not be affected by Windows Defender software.

Powershell Azure : The term 'Get-AutomationConnection' is not recognized as the name of a cmdlet, function, script file, or operable program

I am trying to connect to an Azure Run As connection, as part of a Powershell script that does a backup of a database.
This script attempts to call Get-AutomationConnection
As seen in the screenshot, Get-Module does return that Azure / Azure.Storage and AzureRM shows.
What module should I import in addition for this to work?
If you want to connect to an Azure Run As connection from Windows PowerShell, you should use New-AzureRmAutomationConnection.
$ConnectionAssetName = "AzureRunAsConnection"
$ConnectionFieldValues = #{"ApplicationId" = $Application.ApplicationId; "TenantId" = $TenantID.TenantId; "CertificateThumbprint" = $Cert.Thumbprint; "SubscriptionId" = $SubscriptionId}
New-AzureRmAutomationConnection -ResourceGroupName $ResourceGroup -AutomationAccountName $AutomationAccountName -Name $ConnectionAssetName -ConnectionTypeName AzureServicePrincipal -ConnectionFieldValues $ConnectionFieldValues
You are able to use the script to create the connection asset because when you create your Automation account, it automatically includes several global modules by default along with the connection type AzurServicePrincipal to create the AzureRunAsConnection connection asset.
Get-AutomationConnection runs in Azure runbook internally.
Please refer to connection assets in Azure Automation.
If you want similar functionality to runbooks on-premise, you can install AzureAutomationAuthoringToolkit. It will give you very similar functionality. I have one script that logs in using the service principal, whether it is running on-premise or in an Azure runbook. It uses the resources provided by AAATK when running on-premise, that simulate a runbook.
I did try using the version of Get-AutomationConnection that comes with the "Microsoft Monitoring agent" (Hybrid worker), but I have since read that it is different to the one that comes with AzureAutomationAuthoringToolkit, detailed in the "Known Issues" in the GitHub readme. I couldn't get it to work, so I reverted to AAATK's version.

How do I authenticate Azure Powershell on Azure VM

I'm wanting to execute a Powershell script from an Azure VM to get its current public IP address (and to write this address to an evironment variable for an application to use).
My question is what the best way to authenticate the Azure Powershell environment is? On AWS credentials get 'baked' into an instance when it gets created. Does the equivalent happen with Azure Virtual Machines?
You can use a Management Certificate contained in your Publish Settings file and 'bake' it yourself
Import-AzurePublishSettingsFile –PublishSettingsFile C:\Store\my.publishsettings
If you already have a certificate for management, you can store it in your vm and use it in PS
# Get management certificate from personal store
$certificate = Get-Item cert:\\CurrentUser\My\$CertificateThumbprint
if ($certificate -eq $null) {
throw “Management certificate for $SubscriptionName was not found in the users personal certificate store. Check thumbprint or install certificate”
}
# Set subscription profile
Set-AzureSubscription -SubscriptionName $SubscriptionName -SubscriptionId $SubscriptionId -Certificate $certificate
# Select subscription as the current context
Select-AzureSubscription -SubscriptionName $SubscriptionName

Stop-AzureVM: No deployment found in service

I want to stop and de-allocate a Windows VM in Azure.
In PowerShell, I use the command:
Stop-AzureVM - ServiceName [servicename] - Name [machinename] - Force
However, I get the following error message in PowerShell:
WARNING: "No deployment found in service [servicename]
What could be wrong?
Troubleshooting steps:
Is the VM already in Shutdown or Deallocated state.
Do you have more than one subscriptions. If yes then select correct subscription using below cmdlet and then try to stop the VM:
Select-AzureSubscription -SubscriptionName "<<Your SubscriptionName here>>"
or
Select-AzureSubscription -Id "<<Your Subscription ID>>"
If you have only one Azure Subscription then check if you created the VM using ASM i.e. old portal (https://manage.windowsazure.com) or ARM i.e. new portal (https://portal.azure.com). If you used new portal then you need to use ARM related PowerShell cmdlets like below:
Stop-AzureRmVM -ResourceGroupName "resource group name" -Name "VM name"
Reference for ARM PowerShell cmdlets: Azure Resource Manager and PowerShell

Remove-AzureDisk throws error, not sure why

I have an Azure VM and I'm trying to delete it using Powershell. I also want to remove the disk that that VM OS was on (there are no data disks).
I assume I'm going to need the following two cmdlets:
Remove-AzureVM
Remove-AzureDisk
Here's my code:
$VMs = Get-AzureVM $svcName
foreach ($VM in $VMs)
{
$OSDisk = ($VM | Get-AzureOSDisk)
if ($VM.InstanceStatus -eq "ReadyRole") {
Stop-AzureVM -Name $VM.Name -ServiceName $svcName
}
remove-azurevm -ServiceName $svcName -Name $VM.Name
Remove-AzureDisk -DiskName $OSDisk.DiskName
}
When I execute this the call to Remove-AzureVM returns successfully but the call to Remove-AzureDisk returns an error:
Remove-AzureDisk : BadRequest: A disk with name
XXX is currently in use
by virtual machine YYY running within hosted service
ZZZ, deployment XYZ.
Strange thing is, I can issue the same call to Remove-AzureDisk just a few moments later and it returns successfully.
Its as if the call to Remove-AzureVM is returning too quickly. i.e. Its reporting success before the VM has been fully removed, or before the link to the disk has been removed at any rate.
Can anyone explain why this might be and also how I might work around this problem?
thanks in advance
Jamie
What's happening here is that the Disk that is stored in BLOB storage is locked when in use by a VM. You are removing the VM, but it takes a few moments for the Lease on the BLOB to release. That's why you can remove it a few moments later.
There are a few folks who have written PowerShell to break the lease, or you could use PowerShell to use the SDK (or make direct REST API calls) to check lease status.
I ended up writing a script that creates a VM, clones it, then deletes the clones. As part of that I needed to wait until the lease was released hence if you're experiencing this same problem you might want to check my blog post at http://sqlblog.com/blogs/jamie_thomson/archive/2013/11/04/clone-an-azure-vm-using-powershell.aspx as it'll have some code that might help you.
Regards
Jamie
I puzzled at this for quite a while. Ultimately, I found a different command to do what I thought I was doing with this command. I would recommend the remove-azuredatadisk command to delete a disk, as it automatically breaks the lease.
Get-AzureVM -ServiceName <servicename> -name <vmname> |Remove-AzureDataDisk -lun <lun#> -deletevhd | Update-AzureVM
It will spin for a couple of minutes, but it will give you a success/failure output at the end.
This command just does it, and doesn't give you any feedback about which drive was removed. I would recommend tossing in a get-azuredatadisk first just to be sure of what you deleted.
Get-AzureVM -ServiceName <servicename> -name <vmname> | Get-AzureDataDisk
This is related to Windows Azure: Delete disk attached to non-existent VM. Cross-posting my answer here:
I was unable to use the (2016) web portal to delete orphaned disks in my (classic) storage account. Here is a detailed walk-through for deleteing these orphaned disks with PowerShell.
PowerShell
Download and install PowerShell if you haven't already. (Install and configure Azure PowerShell.) Initial steps from this doclink:
Check that the Azure PowerShell module is available after installing:
Get-Module –ListAvailable
If the Azure PowerShell module is not listed, you may need to import it:
Import-Module Azure
Login to Azure Resource Manager:
Login-AzureRmAccount
AzurePublishSettingsFile
Retreive your PublishSettingsFile.
Get-AzurePublishSettingsFile
Get-AzurePublishSettingsFile launches manage.windowsazure.com and prompts you to download an XML file that you can be saved anywhere.
Reference: Get-AzurePublishSettingsFile Documentation
Import-AzurePublishSettingsFile and specify the path to the file just saved.
Import-AzurePublishSettingsFile -PublishSettingsFile '<your file path>'
Show and Remove Disks
Show current disks. (Reference: Azure Storage Cmdlets)
Get-AzureDisk
Quickly remove all disks. (Credit to Mike's answer)
get-azuredisk | Remove-AzureDisk
Or remove disks by name. (Credit to Remove-AzureDisk Documentation)
Remove-AzureDisk -DiskName disk-name-000000000000000000 -DeleteVHD