Reputation: 925
I am trying to use Microsoft.Azure.Management.Fluent and related set of packages,
I need following details about ALL azure VM in my subscription:
Who created VM, Region of VM, VmSize, Current Status of VM ( Like Stopped/ Running/ Deallocated etc),
I also need
History of VM in terms of duration this VM was up and running for last x months/ weeks.
Is this possible using Microsoft.Azure.Management.Fluent packages?
Upvotes: 0
Views: 319
Reputation: 23111
If you want to know the VM starting and stopping time, we can get it from Azure activity log. Regarding how to retrieve the activity log, we can use Microsoft.Azure.Management.Monitor.Fluent package.
For example
az login
#it will create a service principal and assign contributor role to the sp
az ad sp create-for-rbac -n "jonsp2"
// for more details about the package, please refer to https://www.nuget.org/packages/Microsoft.Azure.Management.Fluent/
Install-Package Microsoft.Azure.Management.Fluent -Version 1.34.0
AzureCredentials credentials = SdkContext.AzureCredentialsFactory.FromServicePrincipal(
clientId, // the sp appId
clientSecret, // the sp password
tenantId, // the sp tenant
AzureEnvironment.AzureGlobalCloud);
var azure = Microsoft.Azure.Management.Fluent.Azure.Configure()
.Authenticate(credentials)
.WithSubscription(subscriptionId);
var vms = await azure.VirtualMachines.ListAsync();
foreach (var vm in vms)
{
var staus = vm.PowerState.Value; // vm power state
var region = vm.RegionName; // vm region
var size = vm.Size.Value; // vm size
var logs = await azure.ActivityLogs.DefineQuery()
.StartingFrom(DateTime.Now.AddDays(-1))
.EndsBefore(DateTime.Now)
.WithAllPropertiesInResponse()
.FilterByResource("/subscriptions/e5b0fcfa-e859-43f3-8d84-5e5fe29f4c68/resourceGroups/jimtest/providers/Microsoft.Compute/virtualMachines/testvm")
.ExecuteAsync();
List<DateTime?> stopTime = new List<DateTime?>();
List<DateTime?> startTime = new List<DateTime?>();
foreach (var log in logs)
{
// get stop time
if ((log.OperationName.LocalizedValue == "Deallocate Virtual Machine") & (log.Status.LocalizedValue == "Succeeded"))
{
stopTime.Add(log.EventTimestamp);
}
// get start tim
if ((log.OperationName.LocalizedValue == "Strat Virtual Machine") & (log.Status.LocalizedValue == "Succeeded"))
{
startTime.Add(log.EventTimestamp);
}
}
}
Upvotes: 1