Ok
I have used the following code to connect to an Azure VM using AAD credentials and successfully executed a powershell script on it... and the requirement is resolved.
Sharing the code if anybody need this kind of solution π
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.Management.Compute;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using Microsoft.Rest;
ConnectVM()
{
string TenantId = "";
string ApplicationId = "";
string SubscriptionId = "";
string ResourceGroup = "";
string VirtualMachineName = "";
string ClientSecret = "";
var context = new AuthenticationContext($"https://login.microsoftonline.com/{TenantId}");
var credentials = new ClientCredential(ApplicationId, ClientSecret);
var result = context.AcquireTokenAsync("https://management.azure.com/", credentials).Result;
var token = result.AccessToken;
var tokencredentials = new TokenCredentials(token);
var computeClient = new ComputeManagementClient(tokencredentials)
{
SubscriptionId = SubscriptionId
};
var c = SdkContext.AzureCredentialsFactory.FromServicePrincipal(ApplicationId, ClientSecret, TenantId, AzureEnvironment.AzureGlobalCloud);
var azure = Azure.Configure()
.WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
.Authenticate(c)
.WithSubscription(SubscriptionId);
// Get the VM reference
var virtualMachine = azure.VirtualMachines.GetByResourceGroup(ResourceGroup, VirtualMachineName);
if(virtualMachine != null)
{
// Define the script to execute
var scriptPath = "mypath/to/powershell/script.ps1";
var runCommandInput = new RunCommandInput()
{
CommandId = "RunPowerShellScript",
Script = new List<string> { System.IO.File.ReadAllText(scriptPath) },
Parameters = new List<RunCommandInputParameter>()
}
var runCommandResult = virtualMachine.RunCommand(runCommandInput);
//Retrieve the script execution output
var scriptOutput = runCommandResult.Value[0].Message;
return scriptOutput;
}
else
{
return "The VM is not found or there was an error connecting to it.";
}
}