简体   繁体   中英

How to Know if Virtual Machine is stopped in Azure

I am using the Azure Rest API. How can I check if a virtual machine is running or stopped? for first I thought to use the provisioning State, but it gives no useful info

Try the code below. PowerState is what you need to check.

       using (ComputeManagementClient computeClient = new ComputeManagementClient(credentials))
        {
            HostedServiceListResponse services  = await computeClient.HostedServices.ListAsync();
            foreach(HostedServiceListResponse.HostedService service in services.HostedServices)
            {
                DeploymentGetResponse deployment = await computeClient.Deployments.GetBySlotAsync(service.ServiceName, DeploymentSlot.Production);

                var powerState = deployment.RoleInstances[0].PowerState;

            }
        }

You can using the Virtual Machine REST API Get information about a virtual machine for Azure Resource Management, please refer to https://msdn.microsoft.com/en-us/Library/azure/mt163682.aspx .

In the response of the REST API for Get information about the instance view of a virtual machine , you can find an attribute displayStatus of the second element in the json property "statuses" array the the bottom of the reference page, see the picture below:

在此处输入图片说明

You can see the status of VM on the portal itself. If you want to use powershell- Get-azurevm -servicename "svcname" -vmname "vmname"

will give you status of vm as well.

using Nodejs:

var msRestAzure = require('ms-rest-azure');
var azArmCompute = require('azure-arm-compute');
const clientId = "xxxx";
const appSecret = "xxxx"; 
const tenantId = "xxxx";
const subscriptionId = "xxxx";

let credential = await msRestAzure.loginWithServicePrincipalSecret(clientId, appSecret, tenantId);
computeClient = new azArmCompute.ComputeManagementClient(credential, subscriptionId);
var getVMStatus = async function(resourceGroup, vmName){
    try {
        await computeClient.virtualMachines.get(resourceGroup, vmName, {expand: 'instanceView'},function(err, result){
            context.log("VM Status:" + result.instanceView.statuses[1].displayStatus);
        });
    } catch (error) {
        context.log("Error has occurred while trying to get VM info");
        throw error;
    }
}

getVMStatus("Rg_xxxx","Vm_xxxx");

Status will be: "VM deallocating","VM deallocated","VM stopping","VM stopped","VM starting" or "VM running" Virtual machines lifecycle and states

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM