0
votes

I'm attempting to create a VM programmatically...actually, following an example in a book. Before running the program I went ahead and created an Azure AD application and service principal via the portal https://docs.microsoft.com/en-us/azure/active-directory/develop/howto-create-service-principal-portal. (On a side note, maybe someone can explain to me why one needs to do this, but can create a VM straightaway via the portal without creating a service principal/AD app.)

While running the app, I'm able to successfully create the management client. Next step is to create the resource group, and that's where it fails with a "System.Net.Http.HttpRequestException: 'No such host is known.'" error. Please advise as to what could be the problem here. Thank you.

    //Create the management client. This will be used for all the operations we will perform in Azure.
    var credentials = SdkContext.AzureCredentialsFactory.FromFile("../../../azureauth.properties");
    var azure = Azure.Configure().WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic).Authenticate(credentials).WithDefaultSubscription();

    //Create a resource group
    var groupName = "az204-ResourceGroup";
    var vmName = "az204VMTesting";
    var location = Region.USEast;
    var vNetName = "az204VNET";
    var vNetAddress = "172.16.0.0/16";
    var subnetName = "az204Subnet";
    var subnetAddress = "172.16.0.0/24";
    var nicName = "az204NIC";
    var adminUser = "azureadminuser";
    var adminPassword = "Pa$$w0rd!2019";

    Console.WriteLine($"Creating resource group {groupName} ... ");
//Below fails with 'No such host is known'
    var resourceGroup = azure.ResourceGroups.Define(groupName).WithRegion(location).Create();
2

2 Answers

1
votes

I tried this code in my system .Try with this code

using Microsoft.Azure.Management.Compute.Fluent.Models;  
using Microsoft.Azure.Management.Fluent;  
using Microsoft.Azure.Management.ResourceManager.Fluent;  
using Microsoft.Azure.Management.ResourceManager.Fluent.Core;  
  
namespace AzureVirtualMachine  
{  
    class Program  
    {  
        static void Main(string[] args)  
        {  
            var credentials = SdkContext.AzureCredentialsFactory  
                .FromServicePrincipal("clientId", "clientSecret", "tenantId", AzureEnvironment.AzureGlobalCloud);  


            var azure = Azure
                .Configure()
                .WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
                .Authenticate(credentials)
                .WithSubscription("SubscriptionID”) 

             var groupName = "sampleResourceGroup";  
                var vmName = "VMWithCSharp";  
                var location = Region.EuropeWest;  

            var resourceGroup = azure.ResourceGroups.Define(groupName)  
                .WithRegion(location)  
                .Create();  
  
            var network = azure.Networks.Define("sampleVirtualNetwork")  
              .WithRegion(location)  
              .WithExistingResourceGroup(groupName)  
              .WithAddressSpace("10.0.0.0/16")  
              .WithSubnet("sampleSubNet", "10.0.0.0/24")  
              .Create();  
  
            var publicIPAddress = azure.PublicIPAddresses.Define("samplePublicIP")  
                .WithRegion(location)  
                .WithExistingResourceGroup(groupName)  
                .WithDynamicIP()  
                .Create();  
  
            var networkInterface = azure.NetworkInterfaces.Define("sampleNetWorkInterface")  
                .WithRegion(location)  
                .WithExistingResourceGroup(groupName)  
                .WithExistingPrimaryNetwork(network)  
                .WithSubnet("sampleSubNet")  
                .WithPrimaryPrivateIPAddressDynamic()  
                .WithExistingPrimaryPublicIPAddress(publicIPAddress)  
                .Create();  
  
            var availabilitySet = azure.AvailabilitySets.Define("sampleAvailabilitySet")  
                .WithRegion(location)  
                .WithExistingResourceGroup(groupName)  
                .WithSku(AvailabilitySetSkuTypes.Aligned)   
                .Create();            
  
            azure.VirtualMachines.Define(vmName)  
                .WithRegion(location)  
                .WithExistingResourceGroup(groupName)  
                .WithExistingPrimaryNetworkInterface(networkInterface)                  
                .WithLatestWindowsImage("MicrosoftWindowsServer", "WindowsServer", "2012-R2-Datacenter")  
                .WithAdminUsername("sampleUser")  
                .WithAdminPassword("Sample123467")  
                .WithComputerName(vmName)  
                .WithExistingAvailabilitySet(availabilitySet)  
                .WithSize(VirtualMachineSizeTypes.StandardB1s)  
                .Create();  
        }  
    }  
}

Output:

enter image description here

0
votes

I resolved the issue by replacing AzureCredentialsFactory.FromFile with AzureCredentialsFactory.FromServicePrincipal. Thanks ShrutiJoshi-MT for the input. I simply created a json file with the necessary credentials.

I still had some issues related to authorization. It turns out I didn't give the App Service appropriate authorization level. This post helped resolve that issue: The client with object id does not have authorization to perform action 'Microsoft.DataFactory/datafactories/datapipelines/read' over scope.

Final code:

string jsonString = File.ReadAllText("../../../azureauth.json");
AuthItem authItem = JsonSerializer.Deserialize<AuthItem>(jsonString);
var credentials = SdkContext.AzureCredentialsFactory
    .FromServicePrincipal(authItem.ClientId, authItem.SecretValue, authItem.TenantId, AzureEnvironment.AzureGlobalCloud);

//Create the management client. This will be used for all the operations we will perform in Azure.
var azure = Azure.Configure().WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic).Authenticate(credentials).WithSubscription(authItem.Subscription);

//Create a resource group
var groupName = "az204-ResourceGroup";
var vmName = "az204VMTesting";
var location = Region.USEast;
var vNetName = "az204VNET";
var vNetAddress = "172.16.0.0/16";
var subnetName = "az204Subnet";
var subnetAddress = "172.16.0.0/24";
var nicName = "az204NIC";
var adminUser = "azureadminuser";
var adminPassword = "Pa$$w0rd!2019";

    Console.WriteLine($"Creating resource group {groupName} ... ");
    var resourceGroup = azure.ResourceGroups.Define(groupName).WithRegion(location).Create();

    //Every VM needs to be connected to a virtual network
    Console.WriteLine($"Creating virtual network {vNetName} ...");
    var network = azure.Networks.Define(vNetName)
        .WithRegion(location)
        .WithExistingResourceGroup(groupName)
        .WithAddressSpace(vNetAddress)
        .WithSubnet(subnetName, subnetAddress)
        .Create();

    //Any VM needs a network interface for connecting to the virtual network
    Console.WriteLine($"Creating network interface {nicName} ... ");
    var nic = azure.NetworkInterfaces.Define(nicName)
        .WithRegion(location)
        .WithExistingResourceGroup(groupName)
        .WithExistingPrimaryNetwork(network)
        .WithSubnet(subnetName)
        .WithPrimaryPrivateIPAddressDynamic()
        .Create();

    //Create the VM
    Console.WriteLine($"Creating VM {vmName} ... ");
    azure.VirtualMachines.Define(vmName)
        .WithRegion(location)
        .WithExistingResourceGroup(groupName)
        .WithExistingPrimaryNetworkInterface(nic)
        .WithLatestWindowsImage("MicrosoftWindowsServer", "WindowsServer", "2012-R2-Datacenter")
        .WithAdminUsername(adminUser)
        .WithAdminPassword(adminPassword)
        .WithComputerName(vmName)
        .WithSize(VirtualMachineSizeTypes.StandardDS2V2)
        .Create();