Azure alert reboot vm on status busy - azure

I am trying to monitor VM status.
I have activated logs, and trying to query the status of the VM.
I can not find the status or health status.

In order to query the status of Azure VMs, make use of below PowerShell commands:
Use the - Status parameter to check whether the VMs are running, deallocated, or stopped using PowerShell like below:
Get-AzVM -Status | Select name, powerstate, provisioningState
If you want to get Status of particular VM then use the below PowerShell command:
Get-AzVM -Name "YourVmName" -ResourceGroup "YourResourceGroupName" -status
If you want to query the status of Azure VMs from Azure Resource Graph Explorer make use of below:
Resources
| project name, location,
PowerState=tostring(properties.extended.instanceView.powerState.code), type
| where type =~ 'Microsoft.Compute/virtualMachines'
| order by name desc
Please note that there is no such state called "Busy", check this MS Doc.
For more information, please find below references:
powershell - Determine Virtual Machine status and activity in Microsoft Azure - Stack Overflow
How to check Azure VM Power state using PowerShell? (tutorialspoint.com)

Related

Finding the last date of the vm using azure cli command

I have an account with Azure with different Resource Group and different virtual machine. I would like to know how I can determine which ones are unused. For example check the last date where the virtual machine was started or used by the user using azure cli command.
Please help me out with this...
Easiest would probably to look at the powerstate of a vm.
First list all the vm's and then run a query where you filter out those that are deallocated and belong to a specific resource group:
az vm list -d --query '[?powerState == `VM deallocated` && resourceGroup==`resource_group`]'
For more information on the queries look up 'JMESPath-query' on the Microsoft docs page. Hopefully this helps.
I would like to know how I can determine which ones are unused
Currently, there is no way to do that using cli.
check the last date where the virtual machine was started or used
We can get this information using PowerShell. which follows.
Get data information of deallocated VM using Get-AzVM -VMName xxxx - RgName xxx -Status
# To retrieve the date of VM was Deallocated.
$vmDeallocatedDate = Get-AzVM -VMName <Your VM name> -ResourceGroupName <Your ResourceGroup Name> -Status
$vmDeallocatedDate.Statuses[0].Time
List all the VM's and the timestamp of the action that triggered the Deallocation
Get-AzLog -Status Accepted -DetailedOutput | ?{$_.Authorization.Action -eq "Microsoft.Compute/virtualMachines/deallocate/action"} | fl ResourceId,EventTimestamp
References
Get-AzLog to get VM Deallocate status
Get-AzVM -status to get VM Deallocate status

Query whether Azure App Services has backup setup

Can anyone suggestion a way to query App Services backup status?
For example, Let say I have a lot of App Services in Azure, different resource groups, instead of clicking through each one and check if backup is setup or not. I want to have a query so I can execute it and return the result?
Thanks in advance.
Based on the above shared requirement , we have written the below PowerShell script to pull the backup details of a webapp. the below script will check whether if there is backup enabled or not for a particular web under resource group.
if backup not enabled scrip will through an error -->
Get-AzWebAppBackupConfiguration : Operation returned an invalid status code 'NotFound'
if backup is enabled scrip will return -->
webappName,storageaccounturi of the backup where it is stored
$RGName='<ResourceGroupName>' ##Pass your ResourceGroupName
$list= Get-AzWebApp -ResourceGroupName $RGName
$listarray=$list
foreach($list in $listarray){
$config=Get-AzWebAppBackupConfiguration -ResourceGroupName $RGName -Name $list.name
Write-Host $config.Name,$config.StorageAccountUrl| Format-Table -AutoSize
}
Here is the sample output for reference:

Get Azure VM creation date

Is there a possible way to get the VM creation date ?
I've tried the following by now
AzureActivity
| where TimeGenerated > ago(90d)
| where ResourceProvider == "Microsoft.Compute" and OperationName == "Create or Update Virtual Machine"
| project Resource ,Datum = format_datetime(EventSubmissionTimestamp, 'MM') ,Caller
| distinct Datum , Resource , Caller
| order by Datum
This kusto query will read the logs from the VM's connected to it. and get all the Create or update virtual machine operations from a vm and its caller ID.
But this is create and update So it gives me double values every time an VM is being updated.
I tried also in PowerShell
$GetVM = Get-AzureRMVM
Foreach ($vms in $GetVM)
{
$vm = get-azurermvm -name $vms.Name -ResourceGroupName $vms.ResourceGroupName
$log = Get-AzureRmLog -ResourceId $vm.Id -StartTime (Get-Date).AddDays(-90) -WarningAction silentlyContinue
Write-Output "- Found VM creation at $($log.EventTimestamp) for VM $($log.Id.split("/")[8]) in Resource Group $($log.ResourceGroupName) found in Azure logs"
}
But Can't seem to find the creation date inside the log files either. Does anyone have a clue if it is possible to find the creation date of a Virtual Machine inside a scripting language , Kusto , Powershell , ...
The easiest way that worked for me to get the Azure VM creation date was to look at the creation date of the OS Disk
Browse to your VM on Azure Portal
On Left Hand side, click on the blade "Disks"
Under OS Disk section, click on your OS Disk.
In the Overview blade of your OS Disk, you can see Time Created field.
Note: All my Azure VMs were created with the OS Disk and were never changed.
Hope it helps. Cheers.
There is no direct way to find out the creation date if it's later than 90 days. But here is a nice workaround solution: https://savilltech.com/2018/02/13/checking-the-creation-time-of-an-azure-iaas-vm/
You can use azure cli
use below command
az vm list
This will list json data with fields and you can filter
date = vm['timeCreated']
//"timeCreated": "2022-06-24T14:13:00.326985+00:00",
The portal does show Created for a cloud service in the Dashboard of a Cloud Service, but that is not shown for a specific VM (which you can see with Azure PowerShell with Get-AzureService <cloud service name> | select DateCreated).
When you do a Quick Create of a VM, that will always create a new cloud service, so the time created would be the same for VM and cloud service. But since you can add multiple VMs to a cloud service, you can't always rely on that.
On the VM's Dashboard in the portal, at the bottom if you look at the VHD column, the VHD name includes the date the disk was created as part of the name, though this is only true for VMs created from an image. If the VM was created from a disk, the name could be anything. You can get that OS disk name in Azure PowerShell with Get-AzureVM <cloud service name> <VM name> | Get-AzureOSDisk | select medialink.
Operation Logs under Management Services in the portal lets you search the last 30 days for operations, so if the VM was created in the last month, you can find evidence of the operation there (for example CreateHostedService and CreateDeployment operations).
For Windows VMs created from an image, the timestamp on WaSetup.log and WaSetup.xml in C:\Windows\panther\ reflect when the VM was provisioned.
Hope it helps.
If you check Deployments in the respective resource group, you will see Last Modified date for each of the deployment in that RG.
I found another way to get it working for me by tweaking your ActivityLog query instead of Powershell. Using the HTTPRequest property seemed to give me what I needed.
AzureActivity
| where TimeGenerated > ago(7d)
| where ResourceProvider contains "Microsoft.Compute" and OperationName == "Create or Update Virtual Machine"
| where HTTPRequest contains "PUT"
| project VMName = Resource, Created_On = format_datetime(EventSubmissionTimestamp,'dd-MM-yyyy-HHtt'), User = Caller
| distinct Created_On, VMName, User
| order by Created_On
In my case, I was trying to get the VMs deleted in the last 7 days. For some reason the time wasn't displaying properly for the query below, hence I had to convert it to my timezone.
AzureActivity
| where TimeGenerated > ago(7d)
| where ResourceProvider == "Microsoft.Compute" and OperationName == "Delete Virtual Machine"
| where HTTPRequest contains "DELETE"
| extend MyTimeZone = EventSubmissionTimestamp + 8h
| project VM_Name = Resource, Deleted_On = format_datetime(MyTimeZone, 'dd-MM-yyyy-HHtt'), User = Caller
| distinct Deleted_On , VM_Name , User
| order by Deleted_On

Azure resource to check orphan resource

I am looking solution to find out Stopped | Deallocated resources Orphan Resources in Azure. I grab the VM data. But if someone spins the VM and VM showing running, How to check owner not used that VM since 30 Days.
az vm list -d --output table
Any automation suggestion will be welcome.
az vm list -d --output table
TESTSXG VM running
I see multiple queries here.
To identify if someone created any resource (say VM) and has forgot to deallocate it.
To check last login in VM if it is older than 30 days.
To check owner not used the VM(s) in the last 30 days.
If we don’t login to VM since a while and if some services (like Jenkins, etc.) are running and untouched.
To audit actions on resources and to determine the operations that were taken on resources, you may use Activity Logs. For more information refer this (https://learn.microsoft.com/en-us/azure/azure-resource-manager/resource-group-audit) link.
For #1, You may execute the below command.
Get-AzureRmVM -Status|select Name, PowerState
For #2 and #3, below is the command which you can run manually in the VM.
Get-WmiObject -Class Win32_NetworkLoginProfile |
Sort-Object -Property LastLogon -Descending |
Select-Object -Property * -First 1 |
Where-Object {$_.LastLogon -match "(\d{14})"} |
Foreach-Object { New-Object PSObject -Property #{ Name=$_.Name;LastLogon=[datetime]::ParseExact($matches[0], "yyyyMMddHHmmss", $null)}}
But I know that we are looking for an automated way to validate all the VM’s under your subscription. So here the requirement is to automatically (i.e., remotely) connect to all the ‘running’ VM’s from Azure portal and then get the required output. If i am not wrong, most probably we can achieve this requirement in multiple ways i.e.,
i. Log Analytics
ii. DSC
iii. Functions
iv. Runbook
v. Logic App
i. Create a Log Analytics OMS workspace and install OMS agent on the VM(s) as instructed here (https://learn.microsoft.com/en-us/azure/azure-monitor/learn/quick-collect-azurevm). Then add Azure Security Center (Security and Audit) solution in OMS so that the security events will be pushed to OMS repository. Then goto Log Analytics -> OMSworkspaceName -> Logs and run the below Kusto query to get the required output.
SecurityEvent
| where EventID == 4624
| sort by TimeGenerated desc
Note that the Event ID 4624 is the ID for the event log of any account logged on to a machine.
ii. Onboard Azure DSC on the VM(s) as instructed here (https://learn.microsoft.com/en-us/azure/automation/automation-dsc-onboarding) and write a DSC configuration script using ‘script’ DSC resource which will run the above mentioned Get-WmiObject…. command remotely on the DSC nodes (i.e., VM’s) and fetch us the required output.
iii. Write a HTTP trigger PowerShell function which will run the above mentioned Get-WmiObject…. command remotely (i.e., may be try a new ps session and invoke command) on the VM’s and fetch us the required output. You may refer this (https://learn.microsoft.com/en-us/azure/azure-functions/functions-create-first-azure-function) link to learn about Functions.
iv. Write a PowerShell runbook which will run the above mentioned Get-WmiObject…. command remotely (i.e., may be try new ps session and invoke command) on the VM’s and fetch us the required output.
v. Currently Azure Logic Apps seems not support to run PowerShell and CLI script. However, we may try to use available Logic Apps Functions connector or any similar connector and internally try to call PowerShell to execute above mentioned Get-WmiObject…. command remotely. Just FYI here (https://feedback.azure.com/forums/287593-logic-apps/suggestions/33913552-run-a-powershell-code-within-a-logic-app-action) is a voice in Azure feedback regarding running PowerShell code within a Logic App, you could vote if you are interested in this option.
For #4, Install OMS agent on the VM’s so that the events details get stored in OMS repository. For example, if no one is logging in to a VM but Jenkins service is running on that VM then in that case you may want to not disturb that VM. So, to validate if Jenkins service is running on a VM or not you may have to run a Kusto query something like this.
Event
| where (EventLog == "System")
| where (RenderedDescription has "jenkins" and RenderedDescription has "stopped")
Hope this helps!!

How do I get the deployment id of an Azure VM?

I created a VM in Windows Azure and some networking people are asking me for the deployment id. I cannot see this property anywhere on the portal. How can I get the deployment id of a Windows Azure VM? I just created the VM through the portal.
One way is to:
Go to https://resources.azure.com and log in
Search for the name of your VM and click to open details. It should return JSON information about the VM.
In the JSON data, search for deploymentId (it should be under the hardwareProfile section in the JSON)
You can see the deployment ID in the virtual machine's Dashboard tab. Refer to the screenshot-
Here's how you can do it via Powershell:
First log in to azure:
login-AzureRmAccount
Then get a reference to the virtual machine. In my case, I have a virtual machine called malcolms-dad in the resource group breaking-bad:
$vm = (Get-AzureRmResource -ResourceGroupName breaking-bad -ResourceName malcolms-dad -ResourceType MicrosoftClassicComputer/virtualMachines)
Now you have the reference, you can query for the deployment id property:
$vm.Properties.HardwareProfile.DeploymentId
Note that we had to pass in the -ResourceType parameter into the Get-AzureRmResource query. This might seem superfluous, but if you omit the parameter the command returns an object without the Properties field.

Resources