Search code examples
azureazure-sdk-.net

How to check if any backup policy applied on virtual machine via azure fluent API?


I want check if any backup policy enable for virtual machine currently I am using Azure Management ResourceManager Fluent API.


Solution

  • Regarding the issue, please refer to the following code

    1. Create a service principal and assign Contributor role to the sp

    2. SDk

     <PackageReference Include="Microsoft.Azure.Management.Compute" Version="46.0.0" />
        <PackageReference Include="Microsoft.Azure.Management.RecoveryServices.Backup" Version="4.1.5-preview" />
        <PackageReference Include="Microsoft.Identity.Client" Version="4.30.1" />
    
    1. Code
     var app = ConfidentialClientApplicationBuilder.Create(clientId)
                    .WithClientSecret(clientSecret)
                    .WithAuthority(String.Format(CultureInfo.InvariantCulture, "https://login.microsoftonline.com/{0}", tenantDomain))
                    .Build();
                string[] scopes = new string[] { "https://management.azure.com/.default" };
                var result = await app.AcquireTokenForClient(scopes)
                         .ExecuteAsync();
    
                var cred = new TokenCredentials(result.AccessToken);
    
                ComputeManagementClient computeClient = new ComputeManagementClient(cred);
                computeClient.SubscriptionId = subscription;
                RecoveryServicesBackupClient backupClient = new RecoveryServicesBackupClient(cred);
                backupClient.SubscriptionId = subscription;
                 foreach (var vm in await computeClient.VirtualMachines.ListAllAsync()) {
                    BackupStatusResponse res = await backupClient.BackupStatus.GetAsync(vm.Location, new BackupStatusRequest()
                    {
                        ResourceId = vm.Id,
                        ResourceType = "VM"
                    });
    
                    Console.WriteLine($"the vm {vm.Name} has been assiocated with backup policy {res.PolicyName}");
    
    
                }
    

    enter image description here