Reputation: 3571
I have a VM powered on and running in azure. I know its name but want to retrieve its IP address programmatically using the new C# SDK and avoiding the REST API. How can I do this?
Upvotes: 1
Views: 2760
Reputation: 69
The easiest way to retrieve the public IP Address of Azure Virtual Machine is
{_VirtualMachineInstance}.GetPrimaryPublicIPAddress().IPAddress;
Very good explanation of this matter you can find here- Tom Sun answer:
Get Azure VM using resource manager deployment and rest api
Upvotes: 1
Reputation: 3571
Try this:
string subId = "deadbeef-beef-beef-beef-beefbeefbeef";
string resourceGroup = "SORG01";
string vmName = "SORG01-BOX01";
using (var client = new ComputeManagementClient(credentials))
{
client.SubscriptionId = subId;
VirtualMachine vm = VirtualMachinesOperationsExtensions.Get(client.VirtualMachines, resourceGroup, vmName);
networkName = vm.NetworkProfile.NetworkInterfaces[0].Id.Split('/').Last();
}
using (var client = new NetworkManagementClient(credentials))
{
client.SubscriptionId = subId;
var network = NetworkInterfacesOperationsExtensions.Get(client.NetworkInterfaces, resourceGroup, vmName);
string ip = network.IpConfigurations[0].PrivateIPAddress;
}
To have these classes, you'll need to install from nuget:
Note that you'll have to select "Include Prerelease" on the nuget search window in order to find these packages. credentials
is a Microsoft.Rest.TokenCredentials
object that you acquire in this manner:
var authContext = new AuthenticationContext("https://login.windows.net/{YourTenantId}");
var credential = new ClientCredential("{YourAppID}", "{YourAppSecret}");
var result = authContext.AcquireTokenAsync("https://management.core.windows.net/", credential);
result.Wait();
if (result.Result == null)
throw new AuthenticationException("Failed to obtain the JWT token");
credentials = new TokenCredentials(result.Result.AccessToken);
Upvotes: 1