Example #1
0
        public static void Main(string[] args)
        {
            var credentialsPath = "./cred.azure";
            var configPath      = "./base.config.azure";

            if (args.Count() == 2)
            {
                credentialsPath = args[0];
                configPath      = args[1];
            }
            AzureCredentials credentials = AzureCredentials.FromFile(credentialsPath);

            Console.WriteLine("Starting to verify machine state");
            var azureList = Azure.Authenticate(credentials).Subscriptions.List();

            azureList.LoadAll();
            try
            {
                config = JsonConvert.DeserializeObject <ShutdownConfig>(File.ReadAllText(configPath));
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            SlackPayload payload = new SlackPayload();

            foreach (var subscription in config.Subscriptions)
            {
                subscriptionInfo.GetOrAdd(subscription.SubscriptionId, subscription);
            }

            foreach (var subscription in config.Subscriptions)
            {
                AssertVms(credentials, subscription.SubscriptionId);
                if (MachinesStarted.Count > 0 || MachinesStopped.Count > 0)
                {
                    payload.Attachments.Add(ConfigureSlackMessage(azureList.Single(s => s.SubscriptionId == subscription.SubscriptionId).DisplayName, config.Simulate));
                }
                MachinesStarted    = new ConcurrentBag <string>();
                MachinesStopped    = new ConcurrentBag <string>();
                MachinesWithTag    = new ConcurrentBag <string>();
                MachinesWithoutTag = new ConcurrentBag <string>();
            }
            if (payload.Attachments.Count > 0 && config.SendSlackInfo)
            {
                SlackClient client   = new SlackClient(new Uri(config.SlackUrl));
                var         response = client.SendMessageAsync(payload).Result;
                Console.WriteLine(JsonConvert.SerializeObject(response));
            }
        }
Example #2
0
        public static void Main(string[] args)
        {
            try
            {
                //=============================================================
                // Authenticate
                AzureCredentials credentials = AzureCredentials.FromFile(Environment.GetEnvironmentVariable("AZURE_AUTH_LOCATION"));

                var azure = Azure
                            .Configure()
                            .WithLogLevel(HttpLoggingDelegatingHandler.Level.BASIC)
                            .Authenticate(credentials)
                            .WithDefaultSubscription();

                // Print selected subscription
                Console.WriteLine("Selected subscription: " + azure.SubscriptionId);

                try
                {
                    //=============================================================
                    // Create a Linux VM with root (sudo) user
                    Console.WriteLine("Creating a Linux VM");

                    IVirtualMachine linuxVM = azure.VirtualMachines.Define(linuxVmName)
                                              .WithRegion(Region.US_EAST)
                                              .WithNewResourceGroup(rgName)
                                              .WithNewPrimaryNetwork("10.0.0.0/28")
                                              .WithPrimaryPrivateIpAddressDynamic()
                                              .WithNewPrimaryPublicIpAddress(pipDnsLabelLinuxVM)
                                              .WithPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_14_04_LTS)
                                              .WithRootUserName(firstLinuxUserName)
                                              .WithPassword(firstLinuxUserPassword)
                                              .WithSize(VirtualMachineSizeTypes.StandardD3V2)
                                              .Create();

                    Console.WriteLine("Created a Linux VM:" + linuxVM.Id);
                    Utilities.PrintVirtualMachine(linuxVM);

                    //=============================================================
                    // Add a second sudo user to Linux VM using VMAccess extension

                    linuxVM.Update()
                    .DefineNewExtension(linuxVmAccessExtensionName)
                    .WithPublisher(linuxVmAccessExtensionPublisherName)
                    .WithType(linuxVmAccessExtensionTypeName)
                    .WithVersion(linuxVmAccessExtensionVersionName)
                    .WithProtectedSetting("username", secondLinuxUserName)
                    .WithProtectedSetting("password", secondLinuxUserPassword)
                    .WithProtectedSetting("expiration", secondLinuxUserExpiration)
                    .Attach()
                    .Apply();

                    Console.WriteLine("Added a second sudo user to the Linux VM");

                    //=============================================================
                    // Add a third sudo user to Linux VM by updating VMAccess extension

                    linuxVM.Update()
                    .UpdateExtension(linuxVmAccessExtensionName)
                    .WithProtectedSetting("username", thirdLinuxUserName)
                    .WithProtectedSetting("password", thirdLinuxUserPassword)
                    .WithProtectedSetting("expiration", thirdLinuxUserExpiration)
                    .Parent()
                    .Apply();

                    Console.WriteLine("Added a third sudo user to the Linux VM");


                    //=============================================================
                    // Reset ssh password of first user of Linux VM by updating VMAccess extension

                    linuxVM.Update()
                    .UpdateExtension(linuxVmAccessExtensionName)
                    .WithProtectedSetting("username", firstLinuxUserName)
                    .WithProtectedSetting("password", firstLinuxUserNewPassword)
                    .WithProtectedSetting("reset_ssh", "true")
                    .Parent()
                    .Apply();

                    Console.WriteLine("Password of first user of Linux VM has been updated");

                    //=============================================================
                    // Removes the second sudo user from Linux VM using VMAccess extension

                    linuxVM.Update()
                    .UpdateExtension(linuxVmAccessExtensionName)
                    .WithProtectedSetting("remove_user", secondLinuxUserName)
                    .Parent()
                    .Apply();

                    //=============================================================
                    // Install MySQL in Linux VM using CustomScript extension

                    linuxVM.Update()
                    .DefineNewExtension(linuxCustomScriptExtensionName)
                    .WithPublisher(linuxCustomScriptExtensionPublisherName)
                    .WithType(linuxCustomScriptExtensionTypeName)
                    .WithVersion(linuxCustomScriptExtensionVersionName)
                    .WithAutoUpgradeMinorVersionEnabled()
                    .WithPublicSetting("fileUris", mySQLLinuxInstallScriptFileUris)
                    .WithPublicSetting("commandToExecute", mySqlScriptLinuxInstallCommand)
                    .Attach()
                    .Apply();

                    Console.WriteLine("Installed MySql using custom script extension");
                    Utilities.PrintVirtualMachine(linuxVM);

                    //=============================================================
                    // Removes the extensions from Linux VM

                    linuxVM.Update()
                    .WithoutExtension(linuxCustomScriptExtensionName)
                    .WithoutExtension(linuxVmAccessExtensionName)
                    .Apply();
                    Console.WriteLine("Removed the custom script and VM Access extensions from Linux VM");
                    Utilities.PrintVirtualMachine(linuxVM);

                    //=============================================================
                    // Create a Windows VM with admin user

                    Console.WriteLine("Creating a Windows VM");

                    IVirtualMachine windowsVM = azure.VirtualMachines.Define(windowsVmName)
                                                .WithRegion(Region.US_EAST)
                                                .WithExistingResourceGroup(rgName)
                                                .WithNewPrimaryNetwork("10.0.0.0/28")
                                                .WithPrimaryPrivateIpAddressDynamic()
                                                .WithNewPrimaryPublicIpAddress(pipDnsLabelWindowsVM)
                                                .WithPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2012_R2_DATACENTER)
                                                .WithAdminUserName(firstWindowsUserName)
                                                .WithPassword(firstWindowsUserPassword)
                                                .WithSize(VirtualMachineSizeTypes.StandardD3V2)
                                                .DefineNewExtension(windowsCustomScriptExtensionName)
                                                .WithPublisher(windowsCustomScriptExtensionPublisherName)
                                                .WithType(windowsCustomScriptExtensionTypeName)
                                                .WithVersion(windowsCustomScriptExtensionVersionName)
                                                .WithAutoUpgradeMinorVersionEnabled()
                                                .WithPublicSetting("fileUris", mySQLWindowsInstallScriptFileUris)
                                                .WithPublicSetting("commandToExecute", mySqlScriptWindowsInstallCommand)
                                                .Attach()
                                                .Create();

                    Console.WriteLine("Created a Windows VM:" + windowsVM.Id);
                    Utilities.PrintVirtualMachine(windowsVM);

                    //=============================================================
                    // Add a second admin user to Windows VM using VMAccess extension

                    windowsVM.Update()
                    .DefineNewExtension(windowsVmAccessExtensionName)
                    .WithPublisher(windowsVmAccessExtensionPublisherName)
                    .WithType(windowsVmAccessExtensionTypeName)
                    .WithVersion(windowsVmAccessExtensionVersionName)
                    .WithProtectedSetting("username", secondWindowsUserName)
                    .WithProtectedSetting("password", secondWindowsUserPassword)
                    .Attach()
                    .Apply();

                    Console.WriteLine("Added a second admin user to the Windows VM");

                    //=============================================================
                    // Add a third admin user to Windows VM by updating VMAccess extension

                    windowsVM.Update()
                    .UpdateExtension(windowsVmAccessExtensionName)
                    .WithProtectedSetting("username", thirdWindowsUserName)
                    .WithProtectedSetting("password", thirdWindowsUserPassword)
                    .Parent()
                    .Apply();

                    Console.WriteLine("Added a third admin user to the Windows VM");

                    //=============================================================
                    // Reset admin password of first user of Windows VM by updating VMAccess extension

                    windowsVM.Update()
                    .UpdateExtension(windowsVmAccessExtensionName)
                    .WithProtectedSetting("username", firstWindowsUserName)
                    .WithProtectedSetting("password", firstWindowsUserNewPassword)
                    .Parent()
                    .Apply();

                    Console.WriteLine("Password of first user of Windows VM has been updated");

                    //=============================================================
                    // Removes the extensions from Linux VM

                    windowsVM.Update()
                    .WithoutExtension(windowsVmAccessExtensionName)
                    .Apply();
                    Console.WriteLine("Removed the VM Access extensions from Windows VM");
                    Utilities.PrintVirtualMachine(windowsVM);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                }
                finally
                {
                    Console.WriteLine($"Deleting resource group : {rgName}");
                    azure.ResourceGroups.Delete(rgName);
                    Console.WriteLine($"Deleted resource group : {rgName}");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
Example #3
0
        public static void Main(string[] args)
        {
            try
            {
                //=============================================================
                // Authenticate
                AzureCredentials credentials = AzureCredentials.FromFile(Environment.GetEnvironmentVariable("AZURE_AUTH_LOCATION"));

                var azure = Azure
                            .Configure()
                            .WithLogLevel(HttpLoggingDelegatingHandler.Level.BASIC)
                            .Authenticate(credentials)
                            .WithDefaultSubscription();

                // Print selected subscription
                Console.WriteLine("Selected subscription: " + azure.SubscriptionId);

                try
                {
                    // Create a resource group [Where all resources gets created]
                    IResourceGroup resourceGroup = azure.ResourceGroups
                                                   .Define(rgName)
                                                   .WithRegion(Region.US_EAST)
                                                   .Create();

                    // Prepare Creatable Network definition [Where all the virtual machines get added to]
                    var creatableNetwork = azure.Networks
                                           .Define(networkName)
                                           .WithRegion(Region.US_EAST)
                                           .WithExistingResourceGroup(resourceGroup)
                                           .WithAddressSpace("172.16.0.0/16");

                    // Prepare Creatable Storage account definition [For storing VMs disk]
                    var creatableStorageAccount = azure.StorageAccounts
                                                  .Define(storageAccountName)
                                                  .WithRegion(Region.US_EAST)
                                                  .WithExistingResourceGroup(resourceGroup);

                    // Prepare a batch of Creatable Virtual Machines definitions
                    List <ICreatable <IVirtualMachine> > creatableVirtualMachines = new List <ICreatable <IVirtualMachine> >();

                    for (int i = 0; i < vmCount; i++)
                    {
                        var creatableVirtualMachine = azure.VirtualMachines
                                                      .Define("VM-" + i)
                                                      .WithRegion(Region.US_EAST)
                                                      .WithExistingResourceGroup(resourceGroup)
                                                      .WithNewPrimaryNetwork(creatableNetwork)
                                                      .WithPrimaryPrivateIpAddressDynamic()
                                                      .WithoutPrimaryPublicIpAddress()
                                                      .WithPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS)
                                                      .WithRootUserName("tirekicker")
                                                      .WithPassword("12NewPA$$w0rd!")
                                                      .WithSize(VirtualMachineSizeTypes.StandardD3V2)
                                                      .WithNewStorageAccount(creatableStorageAccount);
                        creatableVirtualMachines.Add(creatableVirtualMachine);
                    }

                    var startTime = DateTimeOffset.Now.UtcDateTime;
                    Console.WriteLine("Creating the virtual machines");

                    Console.WriteLine("Created virtual machines");

                    var virtualMachines = azure.VirtualMachines.Create(creatableVirtualMachines.ToArray());

                    foreach (var virtualMachine in virtualMachines)
                    {
                        Console.WriteLine(virtualMachine.Id);
                    }

                    var endTime = DateTimeOffset.Now.UtcDateTime;

                    Console.WriteLine($"Created VM: took {(endTime - startTime).TotalSeconds} seconds");
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                }
                finally
                {
                    Console.WriteLine($"Deleting resource group : {rgName}");
                    azure.ResourceGroups.Delete(rgName);
                    Console.WriteLine($"Deleted resource group : {rgName}");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
Example #4
0
        public static void Main(string[] args)
        {
            try
            {
                //=================================================================
                // Authenticate
                AzureCredentials credentials = AzureCredentials.FromFile(Environment.GetEnvironmentVariable("AZURE_AUTH_LOCATION"));

                var azure = Azure
                            .Configure()
                            .WithLogLevel(HttpLoggingDelegatingHandler.Level.BASIC)
                            .Authenticate(credentials)
                            .WithDefaultSubscription();

                // Print selected subscription
                Console.WriteLine("Selected subscription: " + azure.SubscriptionId);

                try
                {
                    // ===========================================================
                    // Get how many batch accounts can be created in specified region.

                    int allowedNumberOfBatchAccounts = azure.BatchAccounts.GetBatchAccountQuotaByLocation(region);

                    // ===========================================================
                    // List all the batch accounts in subscription.

                    var batchAccounts = azure.BatchAccounts.List();
                    int batchAccountsAtSpecificRegion = batchAccounts.Count(x => x.Region == region);

                    if (batchAccountsAtSpecificRegion >= allowedNumberOfBatchAccounts)
                    {
                        Console.WriteLine("No more batch accounts can be created at "
                                          + region + " region, this region already have "
                                          + batchAccountsAtSpecificRegion
                                          + " batch accounts, current quota to create batch account in "
                                          + region + " region is " + allowedNumberOfBatchAccounts + ".");
                        return;
                    }

                    // ============================================================
                    // Create a batch account

                    Console.WriteLine("Creating a batch Account");

                    var batchAccount = azure.BatchAccounts.Define(batchAccountName)
                                       .WithRegion(region)
                                       .WithNewResourceGroup(rgName)
                                       .DefineNewApplication(applicationName)
                                       .DefineNewApplicationPackage(applicationPackageName)
                                       .WithAllowUpdates(true)
                                       .WithDisplayName(applicationDisplayName)
                                       .Attach()
                                       .WithNewStorageAccount(storageAccountName)
                                       .Create();

                    Console.WriteLine("Created a batch Account:");
                    Utilities.PrintBatchAccount(batchAccount);

                    // ============================================================
                    // Get | regenerate batch account access keys

                    Console.WriteLine("Getting batch account access keys");

                    var batchAccountKeys = batchAccount.GetKeys();

                    Utilities.PrintBatchAccountKey(batchAccountKeys);

                    Console.WriteLine("Regenerating primary batch account primary access key");

                    batchAccountKeys = batchAccount.RegenerateKeys(AccountKeyType.Primary);

                    Utilities.PrintBatchAccountKey(batchAccountKeys);

                    // ============================================================
                    // Regenerate the keys for storage account
                    var storageAccount     = azure.StorageAccounts.GetByGroup(rgName, storageAccountName);
                    var storageAccountKeys = storageAccount.GetKeys();

                    Utilities.PrintStorageAccountKeys(storageAccountKeys);

                    Console.WriteLine("Regenerating first storage account access key");

                    storageAccountKeys = storageAccount.RegenerateKey(storageAccountKeys[0].KeyName);

                    Utilities.PrintStorageAccountKeys(storageAccountKeys);

                    // ============================================================
                    // Synchronize storage account keys with batch account

                    batchAccount.SynchronizeAutoStorageKeys();

                    // ============================================================
                    // Update name of application.
                    batchAccount
                    .Update()
                    .UpdateApplication(applicationName)
                    .WithDisplayName("New application display name")
                    .Parent()
                    .Apply();

                    batchAccount.Refresh();
                    Utilities.PrintBatchAccount(batchAccount);

                    // ============================================================
                    // Create another batch account

                    Console.WriteLine("Creating another Batch Account");

                    allowedNumberOfBatchAccounts = azure.BatchAccounts.GetBatchAccountQuotaByLocation(region2);

                    // ===========================================================
                    // List all the batch accounts in subscription.

                    batchAccounts = azure.BatchAccounts.List();
                    batchAccountsAtSpecificRegion = batchAccounts.Count(x => x.Region == region2);

                    IBatchAccount batchAccount2 = null;
                    if (batchAccountsAtSpecificRegion < allowedNumberOfBatchAccounts)
                    {
                        batchAccount2 = azure.BatchAccounts.Define(batchAccountName2)
                                        .WithRegion(region2)
                                        .WithExistingResourceGroup(rgName)
                                        .WithExistingStorageAccount(storageAccount)
                                        .Create();

                        Console.WriteLine("Created second Batch Account:");
                        Utilities.PrintBatchAccount(batchAccount2);
                    }

                    // ============================================================
                    // List batch accounts

                    Console.WriteLine("Listing Batch accounts");

                    var           accounts = azure.BatchAccounts.ListByGroup(rgName);
                    IBatchAccount ba;
                    foreach (var account in accounts)
                    {
                        Console.WriteLine("Batch Account - " + account.Name);
                    }

                    // ============================================================
                    // Refresh a batch account.
                    batchAccount.Refresh();
                    Utilities.PrintBatchAccount(batchAccount);

                    // ============================================================
                    // Delete a batch account

                    Console.WriteLine("Deleting a batch account - " + batchAccount.Name);

                    foreach (var applicationEntry in batchAccount.Applications)
                    {
                        foreach (var applicationPackageEntry in applicationEntry.Value.ApplicationPackages)
                        {
                            Console.WriteLine("Deleting a application package - " + applicationPackageEntry.Key);
                            applicationPackageEntry.Value.Delete();
                        }
                        Console.WriteLine("Deleting a application - " + applicationEntry.Key);
                        batchAccount.Update().WithoutApplication(applicationEntry.Key).Apply();
                    }

                    try
                    {
                        azure.BatchAccounts.Delete(batchAccount.Id);
                    }
                    catch
                    {
                    }

                    Console.WriteLine("Deleted batch account");

                    if (batchAccount2 != null)
                    {
                        Console.WriteLine("Deleting second batch account - " + batchAccount2.Name);
                        try
                        {
                            azure.BatchAccounts.Delete(batchAccount2.Id);
                        }
                        catch
                        {
                        }

                        Console.WriteLine("Deleted second batch account");
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                }
                finally
                {
                    try
                    {
                        Console.WriteLine("Deleting Resource Group: " + rgName);
                        azure.ResourceGroups.Delete(rgName);
                        Console.WriteLine("Deleted Resource Group: " + rgName);
                    }
                    catch (Exception)
                    {
                        Console.WriteLine("Did not create any resources in Azure. No clean up is necessary");
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
        public static void Main(string[] args)
        {
            try
            {
                //=============================================================
                // Authenticate
                AzureCredentials credentials = AzureCredentials.FromFile(Environment.GetEnvironmentVariable("AZURE_AUTH_LOCATION"));

                var azure = Azure
                            .Configure()
                            .WithLogLevel(HttpLoggingDelegatingHandler.Level.BASIC)
                            .Authenticate(credentials)
                            .WithDefaultSubscription();

                // Print selected subscription
                Console.WriteLine("Selected subscription: " + azure.SubscriptionId);

                try
                {
                    //=============================================================
                    // Create an availability set

                    Console.WriteLine("Creating an availability set");

                    var availSet1 = azure.AvailabilitySets.Define(availSetName1)
                                    .WithRegion(Region.US_EAST)
                                    .WithNewResourceGroup(rgName)
                                    .WithFaultDomainCount(2)
                                    .WithUpdateDomainCount(4)
                                    .WithTag("cluster", "Windowslinux")
                                    .WithTag("tag1", "tag1val")
                                    .Create();

                    Console.WriteLine("Created first availability set: " + availSet1.Id);
                    Utilities.PrintAvailabilitySet(availSet1);

                    //=============================================================
                    // Define a virtual network for the VMs in this availability set
                    var network = azure.Networks
                                  .Define(vnetName)
                                  .WithRegion(Region.US_EAST)
                                  .WithExistingResourceGroup(rgName)
                                  .WithAddressSpace("10.0.0.0/28");

                    //=============================================================
                    // Create a Windows VM in the new availability set

                    Console.WriteLine("Creating a Windows VM in the availability set");

                    var vm1 = azure.VirtualMachines.Define(vm1Name)
                              .WithRegion(Region.US_EAST)
                              .WithExistingResourceGroup(rgName)
                              .WithNewPrimaryNetwork(network)
                              .WithPrimaryPrivateIpAddressDynamic()
                              .WithoutPrimaryPublicIpAddress()
                              .WithPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2012_R2_DATACENTER)
                              .WithAdminUserName(userName)
                              .WithPassword(password)
                              .WithSize(VirtualMachineSizeTypes.StandardD3V2)
                              .WithExistingAvailabilitySet(availSet1)
                              .Create();

                    Console.WriteLine("Created first VM:" + vm1.Id);
                    Utilities.PrintVirtualMachine(vm1);

                    //=============================================================
                    // Create a Linux VM in the same availability set

                    Console.WriteLine("Creating a Linux VM in the availability set");

                    var vm2 = azure.VirtualMachines.Define(vm2Name)
                              .WithRegion(Region.US_EAST)
                              .WithExistingResourceGroup(rgName)
                              .WithNewPrimaryNetwork(network)
                              .WithPrimaryPrivateIpAddressDynamic()
                              .WithoutPrimaryPublicIpAddress()
                              .WithPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS)
                              .WithRootUserName(userName)
                              .WithPassword(password)
                              .WithSize(VirtualMachineSizeTypes.StandardD3V2)
                              .WithExistingAvailabilitySet(availSet1)
                              .Create();

                    Console.WriteLine("Created second VM: " + vm2.Id);
                    Utilities.PrintVirtualMachine(vm2);

                    //=============================================================
                    // Update - Tag the availability set

                    availSet1 = availSet1.Update()
                                .WithTag("server1", "nginx")
                                .WithTag("server2", "iis")
                                .WithoutTag("tag1")
                                .Apply();

                    Console.WriteLine("Tagged availability set: " + availSet1.Id);

                    //=============================================================
                    // Create another availability set

                    Console.WriteLine("Creating an availability set");

                    var availSet2 = azure.AvailabilitySets.Define(availSetName2)
                                    .WithRegion(Region.US_EAST)
                                    .WithExistingResourceGroup(rgName)
                                    .Create();

                    Console.WriteLine("Created second availability set: " + availSet2.Id);
                    Utilities.PrintAvailabilitySet(availSet2);

                    //=============================================================
                    // List availability sets

                    var resourceGroupName = availSet1.ResourceGroupName;

                    Console.WriteLine("Printing list of availability sets  =======");

                    foreach (var availabilitySet in azure.AvailabilitySets.ListByGroup(resourceGroupName))
                    {
                        Utilities.PrintAvailabilitySet(availabilitySet);
                    }

                    //=============================================================
                    // Delete an availability set

                    Console.WriteLine("Deleting an availability set: " + availSet2.Id);

                    azure.AvailabilitySets.Delete(availSet2.Id);

                    Console.WriteLine("Deleted availability set: " + availSet2.Id);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                }
                finally
                {
                    try
                    {
                        Console.WriteLine("Deleting Resource Group: " + rgName);
                        azure.ResourceGroups.Delete(rgName);
                        Console.WriteLine("Deleted Resource Group: " + rgName);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
        public static void Main(string[] args)
        {
            try
            {
                //=================================================================
                // Authenticate
                var credentials = AzureCredentials.FromFile(Environment.GetEnvironmentVariable("AZURE_AUTH_LOCATION"));

                var azure = Azure
                            .Configure()
                            .WithLogLevel(HttpLoggingDelegatingHandler.Level.BASIC)
                            .Authenticate(credentials)
                            .WithDefaultSubscription();

                // Print selected subscription
                Console.WriteLine("Selected subscription: " + azure.SubscriptionId);

                try
                {
                    // Define a virtual network for VMs in this availability set

                    Console.WriteLine("Creating a virtual network ...");

                    var network = azure.Networks
                                  .Define(vnetName)
                                  .WithRegion(Region.US_EAST)
                                  .WithNewResourceGroup(rgName)
                                  .WithAddressSpace("172.16.0.0/16")
                                  .DefineSubnet("Front-end")
                                  .WithAddressPrefix("172.16.1.0/24")
                                  .Attach()
                                  .DefineSubnet("Back-end")
                                  .WithAddressPrefix("172.16.2.0/24")
                                  .Attach()
                                  .Create();

                    Console.WriteLine("Created a virtual network: " + network.Id);
                    Utilities.PrintVirtualNetwork(network);

                    //============================================================
                    // Create a network security group for the front end of a subnet
                    // front end subnet contains two rules
                    // - ALLOW-SSH - allows SSH traffic into the front end subnet
                    // - ALLOW-WEB- allows HTTP traffic into the front end subnet

                    Console.WriteLine("Creating a security group for the front end - allows SSH and HTTP");
                    var frontEndNSG = azure.NetworkSecurityGroups.Define(frontEndNSGName)
                                      .WithRegion(Region.US_EAST)
                                      .WithNewResourceGroup(rgName)
                                      .DefineRule("ALLOW-SSH")
                                      .AllowInbound()
                                      .FromAnyAddress()
                                      .FromAnyPort()
                                      .ToAnyAddress()
                                      .ToPort(22)
                                      .WithProtocol(SecurityRuleProtocol.Tcp)
                                      .WithPriority(100)
                                      .WithDescription("Allow SSH")
                                      .Attach()
                                      .DefineRule("ALLOW-HTTP")
                                      .AllowInbound()
                                      .FromAnyAddress()
                                      .FromAnyPort()
                                      .ToAnyAddress()
                                      .ToPort(80)
                                      .WithProtocol(SecurityRuleProtocol.Tcp)
                                      .WithPriority(101)
                                      .WithDescription("Allow HTTP")
                                      .Attach()
                                      .Create();

                    Console.WriteLine("Created a security group for the front end: " + frontEndNSG.Id);
                    Utilities.PrintNetworkSecurityGroup(frontEndNSG);

                    //============================================================
                    // Create a network security group for the back end of a subnet
                    // back end subnet contains two rules
                    // - ALLOW-SQL - allows SQL traffic only from the front end subnet
                    // - DENY-WEB - denies all outbound internet traffic from the back end subnet

                    Console.WriteLine("Creating a security group for the front end - allows SSH and "
                                      + "denies all outbound internet traffic  ");

                    var backEndNSG = azure.NetworkSecurityGroups.Define(backEndNSGName)
                                     .WithRegion(Region.US_EAST)
                                     .WithExistingResourceGroup(rgName)
                                     .DefineRule("ALLOW-SQL")
                                     .AllowInbound()
                                     .FromAddress("172.16.1.0/24")
                                     .FromAnyPort()
                                     .ToAnyAddress()
                                     .ToPort(1433)
                                     .WithProtocol(SecurityRuleProtocol.Tcp)
                                     .WithPriority(100)
                                     .WithDescription("Allow SQL")
                                     .Attach()
                                     .DefineRule("DENY-WEB")
                                     .DenyOutbound()
                                     .FromAnyAddress()
                                     .FromAnyPort()
                                     .ToAnyAddress()
                                     .ToAnyPort()
                                     .WithAnyProtocol()
                                     .WithDescription("Deny Web")
                                     .WithPriority(200)
                                     .Attach()
                                     .Create();

                    Console.WriteLine("Created a security group for the back end: " + backEndNSG.Id);
                    Utilities.PrintNetworkSecurityGroup(backEndNSG);

                    Console.WriteLine("Creating multiple network interfaces");
                    Console.WriteLine("Creating network interface 1");

                    //========================================================
                    // Create a network interface and apply the
                    // front end network security group

                    Console.WriteLine("Creating a network interface for the front end");

                    var networkInterface1 = azure.NetworkInterfaces.Define(networkInterfaceName1)
                                            .WithRegion(Region.US_EAST)
                                            .WithExistingResourceGroup(rgName)
                                            .WithExistingPrimaryNetwork(network)
                                            .WithSubnet("Front-end")
                                            .WithPrimaryPrivateIpAddressDynamic()
                                            .WithNewPrimaryPublicIpAddress(publicIpAddressLeafDNS1)
                                            .WithIpForwarding()
                                            .WithExistingNetworkSecurityGroup(frontEndNSG)
                                            .Create();

                    Console.WriteLine("Created network interface for the front end");

                    Utilities.PrintNetworkInterface(networkInterface1);

                    //========================================================
                    // Create a network interface and apply the
                    // back end network security group

                    Console.WriteLine("Creating a network interface for the back end");

                    var networkInterface2 = azure.NetworkInterfaces.Define(networkInterfaceName2)
                                            .WithRegion(Region.US_EAST)
                                            .WithExistingResourceGroup(rgName)
                                            .WithExistingPrimaryNetwork(network)
                                            .WithSubnet("Back-end")
                                            .WithPrimaryPrivateIpAddressDynamic()
                                            .WithExistingNetworkSecurityGroup(backEndNSG)
                                            .Create();

                    Utilities.PrintNetworkInterface(networkInterface2);

                    //=============================================================
                    // Create a virtual machine (for the front end)
                    // with the network interface that has the network security group for the front end

                    Console.WriteLine("Creating a Linux virtual machine (for the front end) - "
                                      + "with the network interface that has the network security group for the front end");

                    var t1 = DateTime.UtcNow;

                    var frontEndVM = azure.VirtualMachines.Define(frontEndVMName)
                                     .WithRegion(Region.US_EAST)
                                     .WithExistingResourceGroup(rgName)
                                     .WithExistingPrimaryNetworkInterface(networkInterface1)
                                     .WithPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS)
                                     .WithRootUserName(userName)
                                     .WithSsh(sshKey)
                                     .WithSize(VirtualMachineSizeTypes.StandardD3V2)
                                     .Create();

                    var t2 = DateTime.UtcNow;
                    Console.WriteLine("Created Linux VM: (took "
                                      + (t2 - t1).TotalSeconds + " seconds) " + frontEndVM.Id);
                    // Print virtual machine details
                    Utilities.PrintVirtualMachine(frontEndVM);

                    //=============================================================
                    // Create a virtual machine (for the back end)
                    // with the network interface that has the network security group for the back end

                    Console.WriteLine("Creating a Linux virtual machine (for the back end) - "
                                      + "with the network interface that has the network security group for the back end");

                    t1 = DateTime.UtcNow;

                    var backEndVM = azure.VirtualMachines.Define(backEndVMName)
                                    .WithRegion(Region.US_EAST)
                                    .WithExistingResourceGroup(rgName)
                                    .WithExistingPrimaryNetworkInterface(networkInterface2)
                                    .WithPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS)
                                    .WithRootUserName(userName)
                                    .WithSsh(sshKey)
                                    .WithSize(VirtualMachineSizeTypes.StandardD3V2)
                                    .Create();

                    t2 = DateTime.UtcNow;
                    Console.WriteLine("Created a Linux VM: (took "
                                      + (t2 - t1).TotalSeconds + " seconds) " + backEndVM.Id);
                    Utilities.PrintVirtualMachine(backEndVM);

                    //========================================================
                    // List network security groups

                    Console.WriteLine("Walking through network security groups");
                    var networkSecurityGroups = azure.NetworkSecurityGroups.ListByGroup(rgName);

                    foreach (var networkSecurityGroup in networkSecurityGroups)
                    {
                        Utilities.PrintNetworkSecurityGroup(networkSecurityGroup);
                    }

                    //========================================================
                    // Update a network security group

                    Console.WriteLine("Updating the front end network security group to allow FTP");

                    frontEndNSG.Update()
                    .DefineRule("ALLOW-FTP")
                    .AllowInbound()
                    .FromAnyAddress()
                    .FromAnyPort()
                    .ToAnyAddress()
                    .ToPortRange(20, 21)
                    .WithProtocol(SecurityRuleProtocol.Tcp)
                    .WithDescription("Allow FTP")
                    .WithPriority(200)
                    .Attach()
                    .Apply();

                    Console.WriteLine("Updated the front end network security group");
                    Utilities.PrintNetworkSecurityGroup(frontEndNSG);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                }
                finally
                {
                    try
                    {
                        Console.WriteLine("Deleting Resource Group: " + rgName);
                        azure.ResourceGroups.Delete(rgName);
                        Console.WriteLine("Deleted Resource Group: " + rgName);
                    }
                    catch (NullReferenceException)
                    {
                        Console.WriteLine("Did not create any resources in Azure. No clean up is necessary");
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
Example #7
0
        public static void Main(string[] args)
        {
            try
            {
                //=================================================================
                // Authenticate
                var credentials = AzureCredentials.FromFile(Environment.GetEnvironmentVariable("AZURE_AUTH_LOCATION"));

                var azure = Azure
                            .Configure()
                            .WithLogLevel(HttpLoggingDelegatingHandler.Level.BASIC)
                            .Authenticate(credentials)
                            .WithDefaultSubscription();

                // Print selected subscription
                Console.WriteLine("Selected subscription: " + azure.SubscriptionId);

                try
                {
                    //============================================================
                    // Create a virtual machine with multiple network interfaces

                    // Define a virtual network for the VMs in this availability set

                    Console.WriteLine("Creating a virtual network ...");

                    var network = azure.Networks
                                  .Define(vnetName)
                                  .WithRegion(Region.US_EAST)
                                  .WithNewResourceGroup(rgName)
                                  .WithAddressSpace("172.16.0.0/16")
                                  .DefineSubnet("Front-end")
                                  .WithAddressPrefix("172.16.1.0/24")
                                  .Attach()
                                  .DefineSubnet("Mid-tier")
                                  .WithAddressPrefix("172.16.2.0/24")
                                  .Attach()
                                  .DefineSubnet("Back-end")
                                  .WithAddressPrefix("172.16.3.0/24")
                                  .Attach()
                                  .Create();

                    Console.WriteLine("Created a virtual network: " + network.Id);
                    Utilities.PrintVirtualNetwork(network);

                    Console.WriteLine("Creating multiple network interfaces");
                    Console.WriteLine("Creating network interface 1");

                    var networkInterface1 = azure.NetworkInterfaces.Define(networkInterfaceName1)
                                            .WithRegion(Region.US_EAST)
                                            .WithExistingResourceGroup(rgName)
                                            .WithExistingPrimaryNetwork(network)
                                            .WithSubnet("Front-end")
                                            .WithPrimaryPrivateIpAddressDynamic()
                                            .WithNewPrimaryPublicIpAddress(publicIpAddressLeafDNS1)
                                            .WithIpForwarding()
                                            .Create();

                    Console.WriteLine("Created network interface 1");
                    Utilities.PrintNetworkInterface(networkInterface1);
                    Console.WriteLine("Creating network interface 2");

                    var networkInterface2 = azure.NetworkInterfaces.Define(networkInterfaceName2)
                                            .WithRegion(Region.US_EAST)
                                            .WithExistingResourceGroup(rgName)
                                            .WithExistingPrimaryNetwork(network)
                                            .WithSubnet("Mid-tier")
                                            .WithPrimaryPrivateIpAddressDynamic()
                                            .Create();

                    Console.WriteLine("Created network interface 2");
                    Utilities.PrintNetworkInterface(networkInterface2);

                    Console.WriteLine("Creating network interface 3");

                    var networkInterface3 = azure.NetworkInterfaces.Define(networkInterfaceName3)
                                            .WithRegion(Region.US_EAST)
                                            .WithExistingResourceGroup(rgName)
                                            .WithExistingPrimaryNetwork(network)
                                            .WithSubnet("Back-end")
                                            .WithPrimaryPrivateIpAddressDynamic()
                                            .Create();

                    Console.WriteLine("Created network interface 3");
                    Utilities.PrintNetworkInterface(networkInterface3);

                    //=============================================================
                    // Create a virtual machine with multiple network interfaces

                    Console.WriteLine("Creating a Windows VM");

                    var t1 = DateTime.UtcNow;

                    var vm = azure.VirtualMachines.Define(vmName)
                             .WithRegion(Region.US_EAST)
                             .WithExistingResourceGroup(rgName)
                             .WithExistingPrimaryNetworkInterface(networkInterface1)
                             .WithPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2012_R2_DATACENTER)
                             .WithAdminUserName(userName)
                             .WithPassword(password)
                             .WithSize(VirtualMachineSizeTypes.StandardD3V2)
                             .WithExistingSecondaryNetworkInterface(networkInterface2)
                             .WithExistingSecondaryNetworkInterface(networkInterface3)
                             .Create();

                    var t2 = DateTime.UtcNow;
                    Console.WriteLine("Created VM: (took "
                                      + (t2 - t1).TotalSeconds + " seconds) " + vm.Id);
                    // Print virtual machine details
                    Utilities.PrintVirtualMachine(vm);

                    // ===========================================================
                    // Configure a network interface
                    Console.WriteLine("Updating the first network interface");
                    networkInterface1.Update()
                    .WithNewPrimaryPublicIpAddress(publicIpAddressLeafDNS2)
                    .Apply();

                    Console.WriteLine("Updated the first network interface");
                    Utilities.PrintNetworkInterface(networkInterface1);
                    Console.WriteLine();

                    //============================================================
                    // List network interfaces

                    Console.WriteLine("Walking through network inter4faces in resource group: " + rgName);
                    var networkInterfaces = azure.NetworkInterfaces.ListByGroup(rgName);
                    foreach (var networkInterface in networkInterfaces)
                    {
                        Utilities.PrintNetworkInterface(networkInterface);
                    }

                    //============================================================
                    // Delete a network interface

                    Console.WriteLine("Deleting a network interface: " + networkInterface2.Id);
                    Console.WriteLine("First, deleting the vm");
                    azure.VirtualMachines.Delete(vm.Id);
                    Console.WriteLine("Second, deleting the network interface");
                    azure.NetworkInterfaces.Delete(networkInterface2.Id);
                    Console.WriteLine("Deleted network interface");

                    Console.WriteLine("============================================================");
                    Console.WriteLine("Remaining network interfaces are ...");
                    networkInterfaces = azure.NetworkInterfaces.ListByGroup(rgName);
                    foreach (var networkInterface in networkInterfaces)
                    {
                        Utilities.PrintNetworkInterface(networkInterface);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                }
                finally
                {
                    try
                    {
                        Console.WriteLine("Deleting Resource Group: " + rgName);
                        azure.ResourceGroups.Delete(rgName);
                        Console.WriteLine("Deleted Resource Group: " + rgName);
                    }
                    catch (NullReferenceException)
                    {
                        Console.WriteLine("Did not create any resources in Azure. No clean up is necessary");
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
        public static void Main(string[] args)
        {
            try
            {
                //=============================================================
                // Authenticate
                var credentials = AzureCredentials.FromFile(Environment.GetEnvironmentVariable("AZURE_AUTH_LOCATION"));

                var azure = Azure
                            .Configure()
                            .WithLogLevel(HttpLoggingDelegatingHandler.Level.BASIC)
                            .Authenticate(credentials)
                            .WithDefaultSubscription();

                // Print selected subscription
                Console.WriteLine("Selected subscription: " + azure.SubscriptionId);

                try
                {
                    //=============================================================
                    // Create a virtual network with a frontend subnet
                    Console.WriteLine("Creating virtual network with a frontend subnet ...");

                    var network = azure.Networks.Define(vnetName)
                                  .WithRegion(Region.US_EAST)
                                  .WithNewResourceGroup(rgName)
                                  .WithAddressSpace("172.16.0.0/16")
                                  .DefineSubnet("Front-end")
                                  .WithAddressPrefix("172.16.1.0/24")
                                  .Attach()
                                  .Create();

                    Console.WriteLine("Created a virtual network");
                    // Print the virtual network details
                    Utilities.PrintVirtualNetwork(network);

                    //=============================================================
                    // Create a public IP address
                    Console.WriteLine("Creating a public IP address...");

                    var publicIpAddress = azure.PublicIpAddresses.Define(publicIpName)
                                          .WithRegion(Region.US_EAST)
                                          .WithExistingResourceGroup(rgName)
                                          .WithLeafDomainLabel(publicIpName)
                                          .Create();

                    Console.WriteLine("Created a public IP address");
                    // Print the IPAddress details
                    Utilities.PrintIpAddress(publicIpAddress);

                    //=============================================================
                    // Create an Internet facing load balancer with
                    // One frontend IP address
                    // Two backend address pools which contain network interfaces for the virtual
                    //  machines to receive HTTP and HTTPS network traffic from the load balancer
                    // Two load balancing rules for HTTP and HTTPS to map public ports on the load
                    //  balancer to ports in the backend address pool
                    // Two probes which contain HTTP and HTTPS health probes used to check availability
                    //  of virtual machines in the backend address pool
                    // Three inbound NAT rules which contain rules that map a public port on the load
                    //  balancer to a port for a specific virtual machine in the backend address pool
                    //  - this provides direct VM connectivity for SSH to port 22 and TELNET to port 23

                    Console.WriteLine("Creating a Internet facing load balancer with ...");
                    Console.WriteLine("- A frontend IP address");
                    Console.WriteLine("- Two backend address pools which contain network interfaces for the virtual\n"
                                      + "  machines to receive HTTP and HTTPS network traffic from the load balancer");
                    Console.WriteLine("- Two load balancing rules for HTTP and HTTPS to map public ports on the load\n"
                                      + "  balancer to ports in the backend address pool");
                    Console.WriteLine("- Two probes which contain HTTP and HTTPS health probes used to check availability\n"
                                      + "  of virtual machines in the backend address pool");
                    Console.WriteLine("- Two inbound NAT rules which contain rules that map a public port on the load\n"
                                      + "  balancer to a port for a specific virtual machine in the backend address pool\n"
                                      + "  - this provides direct VM connectivity for SSH to port 22 and TELNET to port 23");

                    var loadBalancer1 = azure.LoadBalancers.Define(loadBalancerName1)
                                        .WithRegion(Region.US_EAST)
                                        .WithExistingResourceGroup(rgName)
                                        .DefinePublicFrontend(frontendName)
                                        .WithExistingPublicIpAddress(publicIpAddress)
                                        .Attach()
                                        // Add two backend one per rule
                                        .DefineBackend(backendPoolName1)
                                        .Attach()
                                        .DefineBackend(backendPoolName2)
                                        .Attach()
                                        // Add two probes one per rule
                                        .DefineHttpProbe(httpProbe)
                                        .WithRequestPath("/")
                                        .WithPort(80)
                                        .Attach()
                                        .DefineHttpProbe(httpsProbe)
                                        .WithRequestPath("/")
                                        .WithPort(443)
                                        .Attach()
                                        // Add two rules that uses above backend and probe
                                        .DefineLoadBalancingRule(httpLoadBalancingRule)
                                        .WithProtocol(TransportProtocol.Tcp)
                                        .WithFrontend(frontendName)
                                        .WithFrontendPort(80)
                                        .WithProbe(httpProbe)
                                        .WithBackend(backendPoolName1)
                                        .Attach()
                                        .DefineLoadBalancingRule(httpsLoadBalancingRule)
                                        .WithProtocol(TransportProtocol.Tcp)
                                        .WithFrontend(frontendName)
                                        .WithFrontendPort(443)
                                        .WithProbe(httpsProbe)
                                        .WithBackend(backendPoolName2)
                                        .Attach()
                                        // Add nat pools to enable direct VM connectivity for
                                        //  SSH to port 22 and TELNET to port 23
                                        .DefineInboundNatPool(natPool50XXto22)
                                        .WithProtocol(TransportProtocol.Tcp)
                                        .WithFrontend(frontendName)
                                        .WithFrontendPortRange(5000, 5099)
                                        .WithBackendPort(22)
                                        .Attach()
                                        .DefineInboundNatPool(natPool60XXto23)
                                        .WithProtocol(TransportProtocol.Tcp)
                                        .WithFrontend(frontendName)
                                        .WithFrontendPortRange(6000, 6099)
                                        .WithBackendPort(23)
                                        .Attach()
                                        .Create();

                    // Print load balancer details
                    Console.WriteLine("Created a load balancer");
                    Utilities.PrintLoadBalancer(loadBalancer1);

                    //=============================================================
                    // Create a virtual machine scale set with three virtual machines
                    // And, install Apache Web servers on them

                    Console.WriteLine("Creating virtual machine scale set with three virtual machines"
                                      + " in the frontend subnet ...");

                    var t1 = DateTime.UtcNow;

                    var fileUris = new List <string>();
                    fileUris.Add(apacheInstallScript);

                    var virtualMachineScaleSet = azure.VirtualMachineScaleSets
                                                 .Define(vmssName)
                                                 .WithRegion(Region.US_EAST)
                                                 .WithExistingResourceGroup(rgName)
                                                 .WithSku(VirtualMachineScaleSetSkuTypes.STANDARD_D3_V2)
                                                 .WithExistingPrimaryNetworkSubnet(network, "Front-end")
                                                 .WithPrimaryInternetFacingLoadBalancer(loadBalancer1)
                                                 .WithPrimaryInternetFacingLoadBalancerBackends(backendPoolName1, backendPoolName2)
                                                 .WithPrimaryInternetFacingLoadBalancerInboundNatPools(natPool50XXto22, natPool60XXto23)
                                                 .WithoutPrimaryInternalLoadBalancer()
                                                 .WithPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS)
                                                 .WithRootUserName(userName)
                                                 .WithSsh(sshKey)
                                                 .WithNewStorageAccount(storageAccountName1)
                                                 .WithNewStorageAccount(storageAccountName2)
                                                 .WithNewStorageAccount(storageAccountName3)
                                                 .WithCapacity(3)
                                                 // Use a VM extension to install Apache Web servers
                                                 .DefineNewExtension("CustomScriptForLinux")
                                                 .WithPublisher("Microsoft.OSTCExtensions")
                                                 .WithType("CustomScriptForLinux")
                                                 .WithVersion("1.4")
                                                 .WithMinorVersionAutoUpgrade()
                                                 .WithPublicSetting("fileUris", fileUris)
                                                 .WithPublicSetting("commandToExecute", installCommand)
                                                 .Attach()
                                                 .Create();

                    var t2 = DateTime.UtcNow;
                    Console.WriteLine("Created a virtual machine scale set with "
                                      + "3 Linux VMs & Apache Web servers on them: (took "
                                      + ((t2 - t1).TotalSeconds) + " seconds) ");
                    Console.WriteLine();

                    // Print virtual machine scale set details
                    // Utilities.Print(virtualMachineScaleSet);

                    //=============================================================
                    // Stop the virtual machine scale set

                    Console.WriteLine("Stopping virtual machine scale set ...");
                    virtualMachineScaleSet.PowerOff();
                    Console.WriteLine("Stopped virtual machine scale set");

                    //=============================================================
                    // Start the virtual machine scale set

                    Console.WriteLine("Starting virtual machine scale set ...");
                    virtualMachineScaleSet.Start();
                    Console.WriteLine("Started virtual machine scale set");

                    //=============================================================
                    // Update the virtual machine scale set
                    // - double the no. of virtual machines

                    Console.WriteLine("Updating virtual machine scale set "
                                      + "- double the no. of virtual machines ...");

                    virtualMachineScaleSet.Update()
                    .WithCapacity(6)
                    .Apply();

                    Console.WriteLine("Doubled the no. of virtual machines in "
                                      + "the virtual machine scale set");

                    //=============================================================
                    // re-start virtual machine scale set

                    Console.WriteLine("re-starting virtual machine scale set ...");
                    virtualMachineScaleSet.Restart();
                    Console.WriteLine("re-started virtual machine scale set");
                }
                catch (Exception f)
                {
                    Console.WriteLine(f);
                }
                finally
                {
                    try
                    {
                        Console.WriteLine("Deleting Resource Group: " + rgName);
                        azure.ResourceGroups.Delete(rgName);
                        Console.WriteLine("Deleted Resource Group: " + rgName);
                    }
                    catch (NullReferenceException npe)
                    {
                        Console.WriteLine("Did not create any resources in Azure. No clean up is necessary");
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
        public static void Main(string[] args)
        {
            try
            {
                var rgName         = ResourceNamer.RandomResourceName("rgRSAT", 24);
                var deploymentName = ResourceNamer.RandomResourceName("dpRSAT", 24);

                try
                {
                    //=================================================================
                    // Authenticate
                    var credentials = AzureCredentials.FromFile(Environment.GetEnvironmentVariable("AZURE_AUTH_LOCATION"));

                    var azure = Azure
                                .Configure()
                                .WithLogLevel(HttpLoggingDelegatingHandler.Level.BASIC)
                                .Authenticate(credentials)
                                .WithDefaultSubscription();

                    try
                    {
                        var templateJson = GetTemplate();

                        //=============================================================
                        // Create resource group.

                        Console.WriteLine("Creating a resource group with name: " + rgName);

                        azure.ResourceGroups.Define(rgName)
                        .WithRegion(Region.US_WEST)
                        .Create();

                        Console.WriteLine("Created a resource group with name: " + rgName);

                        //=============================================================
                        // Create a deployment for an Azure App Service via an ARM
                        // template.

                        Console.WriteLine("Starting a deployment for an Azure App Service: " + deploymentName);

                        azure.Deployments.Define(deploymentName)
                        .WithExistingResourceGroup(rgName)
                        .WithTemplate(templateJson)
                        .WithParameters("{}")
                        .WithMode(Microsoft.Azure.Management.Resource.Fluent.Models.DeploymentMode.Incremental)
                        .Create();

                        Console.WriteLine("Completed the deployment: " + deploymentName);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex);
                    }
                    finally
                    {
                        try
                        {
                            Console.WriteLine("Deleting Resource Group: " + rgName);
                            azure.ResourceGroups.Delete(rgName);
                            Console.WriteLine("Deleted Resource Group: " + rgName);
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
Example #10
0
        public static void Main(string[] args)
        {
            try
            {
                try
                {
                    //=================================================================
                    // Authenticate
                    var credentials = AzureCredentials.FromFile(Environment.GetEnvironmentVariable("AZURE_AUTH_LOCATION"));

                    var azure = Azure
                                .Configure()
                                .WithLogLevel(HttpLoggingDelegatingHandler.Level.BASIC)
                                .Authenticate(credentials)
                                .WithDefaultSubscription();
                    try
                    {
                        var templateJson = GetTemplate();

                        //=============================================================
                        // Create resource group.

                        Console.WriteLine("Creating a resource group with name: " + rgName);

                        azure.ResourceGroups.Define(rgName)
                        .WithRegion(Region.US_WEST)
                        .Create();

                        Console.WriteLine("Created a resource group with name: " + rgName);

                        //=============================================================
                        // Create a deployment for an Azure App Service via an ARM
                        // template.

                        Console.WriteLine("Starting a deployment for an Azure App Service: " + deploymentName);

                        azure.Deployments.Define(deploymentName)
                        .WithExistingResourceGroup(rgName)
                        .WithTemplate(templateJson)
                        .WithParameters("{}")
                        .WithMode(DeploymentMode.Incremental)
                        .BeginCreate();

                        Console.WriteLine("Started a deployment for an Azure App Service: " + deploymentName);

                        var deployment = azure.Deployments.GetByGroup(rgName, deploymentName);
                        Console.WriteLine("Current deployment status : " + deployment.ProvisioningState);

                        while (!(StringComparer.OrdinalIgnoreCase.Equals(deployment.ProvisioningState, "Succeeded") ||
                                 StringComparer.OrdinalIgnoreCase.Equals(deployment.ProvisioningState, "Failed") ||
                                 StringComparer.OrdinalIgnoreCase.Equals(deployment.ProvisioningState, "Cancelled")))
                        {
                            Thread.Sleep(10000);
                            deployment = azure.Deployments.GetByGroup(rgName, deploymentName);
                            Console.WriteLine("Current deployment status : " + deployment.ProvisioningState);
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex);
                    }
                    finally
                    {
                        try
                        {
                            Console.WriteLine("Deleting Resource Group: " + rgName);
                            azure.ResourceGroups.Delete(rgName);
                            Console.WriteLine("Deleted Resource Group: " + rgName);
                        }
                        catch (NullReferenceException)
                        {
                            Console.WriteLine("Did not create any resources in Azure. No clean up is necessary");
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
Example #11
0
        public static void Main(string[] args)
        {
            try
            {
                //=============================================================
                // Authenticate
                AzureCredentials credentials = AzureCredentials.FromFile(Environment.GetEnvironmentVariable("AZURE_AUTH_LOCATION"));

                var azure = Azure
                            .Configure()
                            .WithLogLevel(HttpLoggingDelegatingHandler.Level.BASIC)
                            .Authenticate(credentials)
                            .WithDefaultSubscription();

                // Print selected subscription
                Console.WriteLine("Selected subscription: " + azure.SubscriptionId);

                try
                {
                    var startTime = DateTimeOffset.Now.UtcDateTime;

                    var windowsVM = azure.VirtualMachines.Define(windowsVMName)
                                    .WithRegion(Region.US_EAST)
                                    .WithNewResourceGroup(rgName)
                                    .WithNewPrimaryNetwork("10.0.0.0/28")
                                    .WithPrimaryPrivateIpAddressDynamic()
                                    .WithoutPrimaryPublicIpAddress()
                                    .WithPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2012_R2_DATACENTER)
                                    .WithAdminUserName(userName)
                                    .WithPassword(password)
                                    .WithSize(VirtualMachineSizeTypes.StandardD3V2)
                                    .Create();
                    var endTime = DateTimeOffset.Now.UtcDateTime;

                    Console.WriteLine($"Created VM: took {(endTime - startTime).TotalSeconds} seconds");

                    Utilities.PrintVirtualMachine(windowsVM);

                    windowsVM.Update()
                    .WithTag("who-rocks", "open source")
                    .WithTag("where", "on azure")
                    .Apply();

                    Console.WriteLine("Tagged VM: " + windowsVM.Id);

                    //=============================================================
                    // Update - Attach data disks

                    windowsVM.Update()
                    .WithNewDataDisk(10)
                    .DefineNewDataDisk(dataDiskName)
                    .WithSizeInGB(20)
                    .WithCaching(CachingTypes.ReadWrite)
                    .Attach()
                    .Apply();

                    Console.WriteLine("Attached a new data disk" + dataDiskName + " to VM" + windowsVM.Id);
                    Utilities.PrintVirtualMachine(windowsVM);

                    windowsVM.Update()
                    .WithoutDataDisk(dataDiskName)
                    .Apply();

                    Console.WriteLine("Detached data disk " + dataDiskName + " from VM " + windowsVM.Id);

                    //=============================================================
                    // Update - Resize (expand) the data disk
                    // First, deallocate the virtual machine and then proceed with resize

                    Console.WriteLine("De-allocating VM: " + windowsVM.Id);

                    windowsVM.Deallocate();

                    Console.WriteLine("De-allocated VM: " + windowsVM.Id);

                    var dataDisk = windowsVM.DataDisks.First();

                    windowsVM.Update()
                    .UpdateDataDisk(dataDisk.Name)
                    .WithSizeInGB(30)
                    .Parent()
                    .Apply();

                    //=============================================================
                    // Update - Expand the OS drive size by 10 GB

                    int osDiskSizeInGb = windowsVM.OsDiskSize;
                    if (osDiskSizeInGb == 0)
                    {
                        // Server is not returning the OS Disk size, possible bug in server
                        Console.WriteLine("Server is not returning the OS disk size, possible bug in the server?");
                        Console.WriteLine("Assuming that the OS disk size is 256 GB");
                        osDiskSizeInGb = 256;
                    }

                    windowsVM.Update()
                    .WithOsDiskSizeInGb(osDiskSizeInGb + 10)
                    .Apply();

                    Console.WriteLine("Expanded VM " + windowsVM.Id + "'s OS disk to " + (osDiskSizeInGb + 10));

                    //=============================================================
                    // Start the virtual machine

                    Console.WriteLine("Starting VM " + windowsVM.Id);

                    windowsVM.Start();

                    Console.WriteLine("Started VM: " + windowsVM.Id + "; state = " + windowsVM.PowerState);

                    //=============================================================
                    // Restart the virtual machine

                    Console.WriteLine("Restarting VM: " + windowsVM.Id);

                    windowsVM.Restart();

                    Console.WriteLine("Restarted VM: " + windowsVM.Id + "; state = " + windowsVM.PowerState);

                    //=============================================================
                    // Stop (powerOff) the virtual machine

                    Console.WriteLine("Powering OFF VM: " + windowsVM.Id);

                    windowsVM.PowerOff();

                    Console.WriteLine("Powered OFF VM: " + windowsVM.Id + "; state = " + windowsVM.PowerState);

                    // Get the network where Windows VM is hosted
                    var network = windowsVM.GetPrimaryNetworkInterface().PrimaryIpConfiguration.GetNetwork();

                    //=============================================================
                    // Create a Linux VM in the same virtual network

                    Console.WriteLine("Creating a Linux VM in the network");

                    var linuxVM = azure.VirtualMachines.Define(linuxVMName)
                                  .WithRegion(Region.US_EAST)
                                  .WithExistingResourceGroup(rgName)
                                  .WithExistingPrimaryNetwork(network)
                                  .WithSubnet("subnet1") // Referencing the default subnet name when no name specified at creation
                                  .WithPrimaryPrivateIpAddressDynamic()
                                  .WithoutPrimaryPublicIpAddress()
                                  .WithPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS)
                                  .WithRootUserName(userName)
                                  .WithPassword(password)
                                  .WithSize(VirtualMachineSizeTypes.StandardD3V2)
                                  .Create();

                    Console.WriteLine("Created a Linux VM (in the same virtual network): " + linuxVM.Id);
                    Utilities.PrintVirtualMachine(linuxVM);

                    //=============================================================
                    // List virtual machines in the resource group

                    var resourceGroupName = windowsVM.ResourceGroupName;

                    Console.WriteLine("Printing list of VMs =======");

                    foreach (var virtualMachine in azure.VirtualMachines.ListByGroup(resourceGroupName))
                    {
                        Utilities.PrintVirtualMachine(virtualMachine);
                    }

                    //=============================================================
                    // Delete the virtual machine
                    Console.WriteLine("Deleting VM: " + windowsVM.Id);

                    azure.VirtualMachines.Delete(windowsVM.Id);

                    Console.WriteLine("Deleted VM: " + windowsVM.Id);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                }
                finally
                {
                    Console.WriteLine($"Deleting resource group : {rgName}");
                    azure.ResourceGroups.Delete(rgName);
                    Console.WriteLine($"Deleted resource group : {rgName}");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
        public static void Main(string[] args)
        {
            try
            {
                //=================================================================
                // Authenticate
                var credentials = AzureCredentials.FromFile(Environment.GetEnvironmentVariable("AZURE_AUTH_LOCATION"));

                var azure = Azure
                            .Configure()
                            .WithLogLevel(HttpLoggingDelegatingHandler.Level.BASIC)
                            .Authenticate(credentials)
                            .WithDefaultSubscription();

                // Print selected subscription
                Console.WriteLine("Selected subscription: " + azure.SubscriptionId);

                try
                {
                    // ============================================================
                    // Create a storage account

                    Console.WriteLine("Creating a Storage Account");

                    var storageAccount = azure.StorageAccounts.Define(storageAccountName)
                                         .WithRegion(Region.US_EAST)
                                         .WithNewResourceGroup(rgName)
                                         .Create();

                    Console.WriteLine("Created a Storage Account:");
                    Utilities.PrintStorageAccount(storageAccount);

                    // ============================================================
                    // Get | regenerate storage account access keys

                    Console.WriteLine("Getting storage account access keys");

                    var storageAccountKeys = storageAccount.GetKeys();

                    Utilities.PrintStorageAccountKeys(storageAccountKeys);

                    Console.WriteLine("Regenerating first storage account access key");

                    storageAccountKeys = storageAccount.RegenerateKey(storageAccountKeys[0].KeyName);

                    Utilities.PrintStorageAccountKeys(storageAccountKeys);

                    // ============================================================
                    // Create another storage account

                    Console.WriteLine("Creating a 2nd Storage Account");

                    var storageAccount2 = azure.StorageAccounts.Define(storageAccountName2)
                                          .WithRegion(Region.US_EAST)
                                          .WithNewResourceGroup(rgName)
                                          .Create();

                    Console.WriteLine("Created a Storage Account:");
                    Utilities.PrintStorageAccount(storageAccount2);

                    // ============================================================
                    // List storage accounts

                    Console.WriteLine("Listing storage accounts");

                    var storageAccounts = azure.StorageAccounts;

                    var accounts = storageAccounts.ListByGroup(rgName);

                    foreach (var account in accounts)
                    {
                        Console.WriteLine($"Storage Account {account.Name} created @ {account.CreationTime}");
                    }

                    // ============================================================
                    // Delete a storage account

                    Console.WriteLine($"Deleting a storage account - {accounts[0].Name} created @ {accounts[0].CreationTime}");

                    azure.StorageAccounts.Delete(accounts[0].Id);

                    Console.WriteLine("Deleted storage account");
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                }
                finally
                {
                    if (azure.ResourceGroups.GetByName(rgName) != null)
                    {
                        Console.WriteLine("Deleting Resource Group: " + rgName);
                        azure.ResourceGroups.Delete(rgName);
                        Console.WriteLine("Deleted Resource Group: " + rgName);
                    }
                    else
                    {
                        Console.WriteLine("Did not create any resources in Azure. No clean up is necessary");
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
        public static void Main(string[] args)
        {
            try
            {
                //=================================================================
                // Authenticate
                AzureCredentials credentials = AzureCredentials.FromFile(Environment.GetEnvironmentVariable("AZURE_AUTH_LOCATION"));

                var azure = Azure
                            .Configure()
                            .WithLogLevel(HttpLoggingDelegatingHandler.Level.BASIC)
                            .Authenticate(credentials)
                            .WithDefaultSubscription();

                // Print selected subscription
                Console.WriteLine("Selected subscription: " + azure.SubscriptionId);

                try
                {
                    //============================================================
                    // Create a key vault with empty access policy

                    Console.WriteLine("Creating a key vault...");

                    var vault1 = azure.Vaults
                                 .Define(vaultName1)
                                 .WithRegion(Region.US_WEST)
                                 .WithNewResourceGroup(rgName)
                                 .WithEmptyAccessPolicy()
                                 .Create();

                    Console.WriteLine("Created key vault");
                    Utilities.PrintVault(vault1);

                    //============================================================
                    // Authorize an application

                    Console.WriteLine("Authorizing the application associated with the current service principal...");

                    vault1 = vault1.Update()
                             .DefineAccessPolicy()
                             .ForServicePrincipal(AzureCredentials.FromFile(Environment.GetEnvironmentVariable("AZURE_AUTH_LOCATION")).ClientId)
                             .AllowKeyAllPermissions()
                             .AllowSecretPermissions(SecretPermissions.Get)
                             .AllowSecretPermissions(SecretPermissions.List)
                             .Attach()
                             .Apply();

                    Console.WriteLine("Updated key vault");
                    Utilities.PrintVault(vault1);

                    //============================================================
                    // Update a key vault

                    Console.WriteLine("Update a key vault to enable deployments and add permissions to the application...");

                    vault1 = vault1.Update()
                             .WithDeploymentEnabled()
                             .WithTemplateDeploymentEnabled()
                             .UpdateAccessPolicy(vault1.AccessPolicies[0].ObjectId)
                             .AllowSecretAllPermissions()
                             .Parent()
                             .Apply();

                    Console.WriteLine("Updated key vault");
                    // Print the network security group
                    Utilities.PrintVault(vault1);

                    //============================================================
                    // Create another key vault

                    var vault2 = azure.Vaults
                                 .Define(vaultName2)
                                 .WithRegion(Region.US_EAST)
                                 .WithExistingResourceGroup(rgName)
                                 .DefineAccessPolicy()
                                 .ForServicePrincipal(AzureCredentials.FromFile(Environment.GetEnvironmentVariable("AZURE_AUTH_LOCATION")).ClientId)
                                 .AllowKeyPermissions(KeyPermissions.List)
                                 .AllowKeyPermissions(KeyPermissions.Get)
                                 .AllowKeyPermissions(KeyPermissions.Decrypt)
                                 .AllowSecretPermissions(SecretPermissions.Get)
                                 .Attach()
                                 .Create();

                    Console.WriteLine("Created key vault");
                    // Print the network security group
                    Utilities.PrintVault(vault2);

                    //============================================================
                    // List key vaults

                    Console.WriteLine("Listing key vaults...");

                    foreach (var vault in azure.Vaults.ListByGroup(rgName))
                    {
                        Utilities.PrintVault(vault);
                    }

                    //============================================================
                    // Delete key vaults
                    Console.WriteLine("Deleting the key vaults");
                    azure.Vaults.Delete(vault1.Id);
                    azure.Vaults.Delete(vault2.Id);
                    Console.WriteLine("Deleted the key vaults");
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                }
                finally
                {
                    try
                    {
                        Console.WriteLine("Deleting Resource Group: " + rgName);
                        azure.ResourceGroups.Delete(rgName);
                        Console.WriteLine("Deleted Resource Group: " + rgName);
                    }
                    catch (NullReferenceException)
                    {
                        Console.WriteLine("Did not create any resources in Azure. No clean up is necessary");
                    }
                    catch (Exception g)
                    {
                        Console.WriteLine(g);
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
        public static void Main(string[] args)
        {
            var rgName        = ResourceNamer.RandomResourceName("rgRSMR", 24);
            var resourceName1 = ResourceNamer.RandomResourceName("rn1", 24);
            var resourceName2 = ResourceNamer.RandomResourceName("rn2", 24);

            try
            {
                //=================================================================
                // Authenticate
                AzureCredentials credentials = AzureCredentials.FromFile(Environment.GetEnvironmentVariable("AZURE_AUTH_LOCATION"));

                var azure = Azure
                            .Configure()
                            .WithLogLevel(HttpLoggingDelegatingHandler.Level.BASIC)
                            .Authenticate(credentials)
                            .WithDefaultSubscription();

                try
                {
                    //=============================================================
                    // Create resource group.

                    Console.WriteLine("Creating a resource group with name: " + rgName);

                    azure.ResourceGroups
                    .Define(rgName)
                    .WithRegion(Region.US_WEST)
                    .Create();

                    //=============================================================
                    // Create storage account.

                    Console.WriteLine("Creating a storage account with name: " + resourceName1);

                    var storageAccount = azure.StorageAccounts
                                         .Define(resourceName1)
                                         .WithRegion(Region.US_WEST)
                                         .WithExistingResourceGroup(rgName)
                                         .Create();

                    Console.WriteLine("Storage account created: " + storageAccount.Id);

                    //=============================================================
                    // Update - set the sku name

                    Console.WriteLine("Updating the storage account with name: " + resourceName1);

                    storageAccount.Update()
                    .WithSku(Microsoft.Azure.Management.Storage.Fluent.Models.SkuName.StandardRAGRS)
                    .Apply();

                    Console.WriteLine("Updated the storage account with name: " + resourceName1);

                    //=============================================================
                    // Create another storage account.

                    Console.WriteLine("Creating another storage account with name: " + resourceName2);

                    var storageAccount2 = azure.StorageAccounts.Define(resourceName2)
                                          .WithRegion(Region.US_WEST)
                                          .WithExistingResourceGroup(rgName)
                                          .Create();

                    Console.WriteLine("Storage account created: " + storageAccount2.Id);

                    //=============================================================
                    // List storage accounts.

                    Console.WriteLine("Listing all storage accounts for resource group: " + rgName);

                    foreach (var sAccount in azure.StorageAccounts.List())
                    {
                        Console.WriteLine("Storage account: " + sAccount.Name);
                    }

                    //=============================================================
                    // Delete a storage accounts.

                    Console.WriteLine("Deleting storage account: " + resourceName2);

                    azure.StorageAccounts.Delete(storageAccount2.Id);

                    Console.WriteLine("Deleted storage account: " + resourceName2);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                }
                finally
                {
                    try
                    {
                        Console.WriteLine("Deleting Resource Group: " + rgName);
                        azure.ResourceGroups.Delete(rgName);
                        Console.WriteLine("Deleted Resource Group: " + rgName);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
Example #15
0
        public static void Main(string[] args)
        {
            try
            {
                //=================================================================
                // Authenticate
                AzureCredentials credentials = AzureCredentials.FromFile(Environment.GetEnvironmentVariable("AZURE_AUTH_LOCATION"));

                var azure = Azure
                            .Configure()
                            .WithLogLevel(HttpLoggingDelegatingHandler.Level.BASIC)
                            .Authenticate(credentials)
                            .WithDefaultSubscription();

                //=================================================================
                // List all virtual machine image publishers and
                // list all virtual machine images
                // published by Canonical, Red Hat and SUSE
                // by browsing through locations, publishers, offers, SKUs and images

                var publishers = azure
                                 .VirtualMachineImages
                                 .Publishers
                                 .ListByRegion(Region.US_EAST);

                Console.WriteLine("US East data center: printing list of \n"
                                  + "a) Publishers and\n"
                                  + "b) Images published by Canonical, Red Hat and Suse");
                Console.WriteLine("=======================================================");
                Console.WriteLine("\n");

                foreach (var publisher in publishers)
                {
                    Console.WriteLine("Publisher - " + publisher.Name);

                    if (StringComparer.OrdinalIgnoreCase.Equals(publisher.Name, "Canonical") ||
                        StringComparer.OrdinalIgnoreCase.Equals(publisher.Name, "Suse") ||
                        StringComparer.OrdinalIgnoreCase.Equals(publisher.Name, "RedHat"))
                    {
                        Console.WriteLine("\n\n");
                        Console.WriteLine("=======================================================");
                        Console.WriteLine("Located " + publisher.Name);
                        Console.WriteLine("=======================================================");
                        Console.WriteLine("Printing entries as publisher/offer/sku/image/version");

                        foreach (var offer in publisher.Offers.List())
                        {
                            foreach (var sku in offer.Skus.List())
                            {
                                foreach (var image in sku.Images.List())
                                {
                                    Console.WriteLine($"Image - {publisher.Name}/{offer.Name}/{sku.Name}/{image.Version}");
                                }
                            }
                        }

                        Console.WriteLine("\n\n");
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
        public static void Main(string[] args)
        {
            try
            {
                //=================================================================
                // Authenticate
                var credentials = AzureCredentials.FromFile(Environment.GetEnvironmentVariable("AZURE_AUTH_LOCATION"));

                var azure = Azure
                            .Configure()
                            .WithLogLevel(HttpLoggingDelegatingHandler.Level.BASIC)
                            .Authenticate(credentials)
                            .WithDefaultSubscription();

                // Print selected subscription
                Console.WriteLine("Selected subscription: " + azure.SubscriptionId);

                try
                {
                    //=============================================================
                    // Create a virtual network with a frontend and a backend subnets
                    Console.WriteLine("Creating virtual network with a frontend and a backend subnets...");

                    var network = azure.Networks.Define(vnetName)
                                  .WithRegion(Region.US_EAST)
                                  .WithNewResourceGroup(rgName)
                                  .WithAddressSpace("172.16.0.0/16")
                                  .DefineSubnet("Front-end")
                                  .WithAddressPrefix("172.16.1.0/24")
                                  .Attach()
                                  .DefineSubnet("Back-end")
                                  .WithAddressPrefix("172.16.3.0/24")
                                  .Attach()
                                  .Create();

                    Console.WriteLine("Created a virtual network");
                    // Print the virtual network details
                    Utilities.PrintVirtualNetwork(network);

                    //=============================================================
                    // Create a public IP address
                    Console.WriteLine("Creating a public IP address...");

                    var publicIpAddress = azure.PublicIpAddresses.Define(publicIpName1)
                                          .WithRegion(Region.US_EAST)
                                          .WithExistingResourceGroup(rgName)
                                          .WithLeafDomainLabel(publicIpName1)
                                          .Create();

                    Console.WriteLine("Created a public IP address");
                    // Print the virtual network details
                    Utilities.PrintIpAddress(publicIpAddress);

                    //=============================================================
                    // Create an Internet facing load balancer
                    // Create a frontend IP address
                    // Two backend address pools which contain network interfaces for the virtual
                    //  machines to receive HTTP and HTTPS network traffic from the load balancer
                    // Two load balancing rules for HTTP and HTTPS to map public ports on the load
                    //  balancer to ports in the backend address pool
                    // Two probes which contain HTTP and HTTPS health probes used to check availability
                    //  of virtual machines in the backend address pool
                    // Two inbound NAT rules which contain rules that map a public port on the load
                    //  balancer to a port for a specific virtual machine in the backend address pool
                    //  - this provides direct VM connectivity for SSH to port 22 and TELNET to port 23

                    Console.WriteLine("Creating a Internet facing load balancer with ...");
                    Console.WriteLine("- A frontend IP address");
                    Console.WriteLine("- Two backend address pools which contain network interfaces for the virtual\n"
                                      + "  machines to receive HTTP and HTTPS network traffic from the load balancer");
                    Console.WriteLine("- Two load balancing rules for HTTP and HTTPS to map public ports on the load\n"
                                      + "  balancer to ports in the backend address pool");
                    Console.WriteLine("- Two probes which contain HTTP and HTTPS health probes used to check availability\n"
                                      + "  of virtual machines in the backend address pool");
                    Console.WriteLine("- Two inbound NAT rules which contain rules that map a public port on the load\n"
                                      + "  balancer to a port for a specific virtual machine in the backend address pool\n"
                                      + "  - this provides direct VM connectivity for SSH to port 22 and TELNET to port 23");

                    var loadBalancer1 = azure.LoadBalancers.Define(loadBalancerName1)
                                        .WithRegion(Region.US_EAST)
                                        .WithExistingResourceGroup(rgName)
                                        .DefinePublicFrontend(frontendName)
                                        .WithExistingPublicIpAddress(publicIpAddress)
                                        .Attach()
                                        // Add two backend one per rule
                                        .DefineBackend(backendPoolName1)
                                        .Attach()
                                        .DefineBackend(backendPoolName2)
                                        .Attach()
                                        // Add two probes one per rule
                                        .DefineHttpProbe(httpProbe)
                                        .WithRequestPath("/")
                                        .WithPort(80)
                                        .Attach()
                                        .DefineHttpProbe(httpsProbe)
                                        .WithRequestPath("/")
                                        .WithPort(443)
                                        .Attach()
                                        // Add two rules that uses above backend and probe
                                        .DefineLoadBalancingRule(httpLoadBalancingRule)
                                        .WithProtocol(TransportProtocol.Tcp)
                                        .WithFrontend(frontendName)
                                        .WithFrontendPort(80)
                                        .WithProbe(httpProbe)
                                        .WithBackend(backendPoolName1)
                                        .Attach()
                                        .DefineLoadBalancingRule(httpsLoadBalancingRule)
                                        .WithProtocol(TransportProtocol.Tcp)
                                        .WithFrontend(frontendName)
                                        .WithFrontendPort(443)
                                        .WithProbe(httpsProbe)
                                        .WithBackend(backendPoolName2)
                                        .Attach()
                                        // Add two nat pools to enable direct VM connectivity for
                                        //  SSH to port 22 and TELNET to port 23
                                        .DefineInboundNatRule(natRule5000to22forVM1)
                                        .WithProtocol(TransportProtocol.Tcp)
                                        .WithFrontend(frontendName)
                                        .WithFrontendPort(5000)
                                        .WithBackendPort(22)
                                        .Attach()
                                        .DefineInboundNatRule(natRule5001to23forVM1)
                                        .WithProtocol(TransportProtocol.Tcp)
                                        .WithFrontend(frontendName)
                                        .WithFrontendPort(5001)
                                        .WithBackendPort(23)
                                        .Attach()
                                        .DefineInboundNatRule(natRule5002to22forVM2)
                                        .WithProtocol(TransportProtocol.Tcp)
                                        .WithFrontend(frontendName)
                                        .WithFrontendPort(5002)
                                        .WithBackendPort(22)
                                        .Attach()
                                        .DefineInboundNatRule(natRule5003to23forVM2)
                                        .WithProtocol(TransportProtocol.Tcp)
                                        .WithFrontend(frontendName)
                                        .WithFrontendPort(5003)
                                        .WithBackendPort(23)
                                        .Attach()
                                        .Create();

                    // Print load balancer details
                    Console.WriteLine("Created a load balancer");
                    Utilities.PrintLoadBalancer(loadBalancer1);

                    //=============================================================
                    // Create two network interfaces in the frontend subnet
                    //  associate network interfaces to NAT rules, backend pools

                    Console.WriteLine("Creating two network interfaces in the frontend subnet ...");
                    Console.WriteLine("- And associating network interfaces to backend pools and NAT rules");

                    var networkInterfaceCreatables = new List <ICreatable <INetworkInterface> >();

                    ICreatable <INetworkInterface> networkInterface1Creatable;
                    ICreatable <INetworkInterface> networkInterface2Creatable;

                    networkInterface1Creatable = azure.NetworkInterfaces
                                                 .Define(networkInterfaceName1)
                                                 .WithRegion(Region.US_EAST)
                                                 .WithNewResourceGroup(rgName)
                                                 .WithExistingPrimaryNetwork(network)
                                                 .WithSubnet("Front-end")
                                                 .WithPrimaryPrivateIpAddressDynamic()
                                                 .WithExistingLoadBalancerBackend(loadBalancer1, backendPoolName1)
                                                 .WithExistingLoadBalancerBackend(loadBalancer1, backendPoolName2)
                                                 .WithExistingLoadBalancerInboundNatRule(loadBalancer1, natRule5000to22forVM1)
                                                 .WithExistingLoadBalancerInboundNatRule(loadBalancer1, natRule5001to23forVM1);

                    networkInterfaceCreatables.Add(networkInterface1Creatable);

                    networkInterface2Creatable = azure.NetworkInterfaces
                                                 .Define(networkInterfaceName2)
                                                 .WithRegion(Region.US_EAST)
                                                 .WithNewResourceGroup(rgName)
                                                 .WithExistingPrimaryNetwork(network)
                                                 .WithSubnet("Front-end")
                                                 .WithPrimaryPrivateIpAddressDynamic()
                                                 .WithExistingLoadBalancerBackend(loadBalancer1, backendPoolName1)
                                                 .WithExistingLoadBalancerBackend(loadBalancer1, backendPoolName2)
                                                 .WithExistingLoadBalancerInboundNatRule(loadBalancer1, natRule5002to22forVM2)
                                                 .WithExistingLoadBalancerInboundNatRule(loadBalancer1, natRule5003to23forVM2);

                    networkInterfaceCreatables.Add(networkInterface2Creatable);

                    var networkInterfaces1 = azure.NetworkInterfaces.Create(networkInterfaceCreatables.ToArray());

                    // Print network interface details
                    Console.WriteLine("Created two network interfaces");
                    Console.WriteLine("Network Interface ONE -");
                    Utilities.PrintNetworkInterface(networkInterfaces1.ElementAt(0));
                    Console.WriteLine();
                    Console.WriteLine("Network Interface TWO -");
                    Utilities.PrintNetworkInterface(networkInterfaces1.ElementAt(1));

                    //=============================================================
                    // Create an availability set

                    Console.WriteLine("Creating an availability set ...");

                    var availSet1 = azure.AvailabilitySets.Define(availSetName)
                                    .WithRegion(Region.US_EAST)
                                    .WithNewResourceGroup(rgName)
                                    .WithFaultDomainCount(2)
                                    .WithUpdateDomainCount(4)
                                    .Create();

                    Console.WriteLine("Created first availability set: " + availSet1.Id);
                    Utilities.PrintAvailabilitySet(availSet1);

                    //=============================================================
                    // Create two virtual machines and assign network interfaces

                    Console.WriteLine("Creating two virtual machines in the frontend subnet ...");
                    Console.WriteLine("- And assigning network interfaces");

                    var virtualMachineCreatables1 = new List <ICreatable <IVirtualMachine> >();
                    ICreatable <IVirtualMachine> virtualMachine1Creatable;
                    ICreatable <IVirtualMachine> virtualMachine2Creatable;

                    virtualMachine1Creatable = azure.VirtualMachines
                                               .Define(vmName1)
                                               .WithRegion(Region.US_EAST)
                                               .WithExistingResourceGroup(rgName)
                                               .WithExistingPrimaryNetworkInterface(networkInterfaces1.ElementAt(0))
                                               .WithPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS)
                                               .WithRootUserName(userName)
                                               .WithSsh(sshKey)
                                               .WithSize(VirtualMachineSizeTypes.StandardD3V2)
                                               .WithExistingAvailabilitySet(availSet1);

                    virtualMachineCreatables1.Add(virtualMachine1Creatable);

                    virtualMachine2Creatable = azure.VirtualMachines
                                               .Define(vmName2)
                                               .WithRegion(Region.US_EAST)
                                               .WithExistingResourceGroup(rgName)
                                               .WithExistingPrimaryNetworkInterface(networkInterfaces1.ElementAt(1))
                                               .WithPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS)
                                               .WithRootUserName(userName)
                                               .WithSsh(sshKey)
                                               .WithSize(VirtualMachineSizeTypes.StandardD3V2)
                                               .WithExistingAvailabilitySet(availSet1);

                    virtualMachineCreatables1.Add(virtualMachine2Creatable);

                    var t1 = DateTime.UtcNow;
                    var virtualMachines = azure.VirtualMachines.Create(virtualMachineCreatables1.ToArray());

                    var t2 = DateTime.UtcNow;
                    Console.WriteLine($"Created 2 Linux VMs: (took {(t2 - t1).TotalSeconds} seconds) ");
                    Console.WriteLine();

                    // Print virtual machine details
                    Console.WriteLine("Virtual Machine ONE -");
                    Utilities.PrintVirtualMachine(virtualMachines.ElementAt(0));
                    Console.WriteLine();
                    Console.WriteLine("Virtual Machine TWO - ");
                    Utilities.PrintVirtualMachine(virtualMachines.ElementAt(1));

                    //=============================================================
                    // Update a load balancer
                    //  configure TCP idle timeout to 15 minutes

                    Console.WriteLine("Updating the load balancer ...");

                    loadBalancer1.Update()
                    .UpdateLoadBalancingRule(httpLoadBalancingRule)
                    .WithIdleTimeoutInMinutes(15)
                    .Parent()
                    .UpdateLoadBalancingRule(httpsLoadBalancingRule)
                    .WithIdleTimeoutInMinutes(15)
                    .Parent()
                    .Apply();

                    Console.WriteLine("Update the load balancer with a TCP idle timeout to 15 minutes");

                    //=============================================================
                    // Create another public IP address
                    Console.WriteLine("Creating another public IP address...");

                    var publicIpAddress2 = azure.PublicIpAddresses.Define(publicIpName2)
                                           .WithRegion(Region.US_EAST)
                                           .WithExistingResourceGroup(rgName)
                                           .WithLeafDomainLabel(publicIpName2)
                                           .Create();

                    Console.WriteLine("Created another public IP address");
                    // Print the virtual network details
                    Utilities.PrintIpAddress(publicIpAddress2);

                    //=============================================================
                    // Create another Internet facing load balancer
                    // Create a frontend IP address
                    // Two backend address pools which contain network interfaces for the virtual
                    //  machines to receive HTTP and HTTPS network traffic from the load balancer
                    // Two load balancing rules for HTTP and HTTPS to map public ports on the load
                    //  balancer to ports in the backend address pool
                    // Two probes which contain HTTP and HTTPS health probes used to check availability
                    //  of virtual machines in the backend address pool
                    // Two inbound NAT rules which contain rules that map a public port on the load
                    //  balancer to a port for a specific virtual machine in the backend address pool
                    //  - this provides direct VM connectivity for SSH to port 22 and TELNET to port 23

                    Console.WriteLine("Creating another Internet facing load balancer with ...");
                    Console.WriteLine("- A frontend IP address");
                    Console.WriteLine("- Two backend address pools which contain network interfaces for the virtual\n"
                                      + "  machines to receive HTTP and HTTPS network traffic from the load balancer");
                    Console.WriteLine("- Two load balancing rules for HTTP and HTTPS to map public ports on the load\n"
                                      + "  balancer to ports in the backend address pool");
                    Console.WriteLine("- Two probes which contain HTTP and HTTPS health probes used to check availability\n"
                                      + "  of virtual machines in the backend address pool");
                    Console.WriteLine("- Two inbound NAT rules which contain rules that map a public port on the load\n"
                                      + "  balancer to a port for a specific virtual machine in the backend address pool\n"
                                      + "  - this provides direct VM connectivity for SSH to port 22 and TELNET to port 23");

                    var loadBalancer2 = azure.LoadBalancers.Define(loadBalancerName2)
                                        .WithRegion(Region.US_EAST)
                                        .WithExistingResourceGroup(rgName)
                                        .DefinePublicFrontend(frontendName)
                                        .WithExistingPublicIpAddress(publicIpAddress2)
                                        .Attach()
                                        // Add two backend one per rule
                                        .DefineBackend(backendPoolName1)
                                        .Attach()
                                        .DefineBackend(backendPoolName2)
                                        .Attach()
                                        // Add two probes one per rule
                                        .DefineHttpProbe(httpProbe)
                                        .WithRequestPath("/")
                                        .WithPort(80)
                                        .Attach()
                                        .DefineHttpProbe(httpsProbe)
                                        .WithRequestPath("/")
                                        .WithPort(443)
                                        .Attach()
                                        // Add two rules that uses above backend and probe
                                        .DefineLoadBalancingRule(httpLoadBalancingRule)
                                        .WithProtocol(TransportProtocol.Tcp)
                                        .WithFrontend(frontendName)
                                        .WithFrontendPort(80)
                                        .WithProbe(httpProbe)
                                        .WithBackend(backendPoolName1)
                                        .Attach()
                                        .DefineLoadBalancingRule(httpsLoadBalancingRule)
                                        .WithProtocol(TransportProtocol.Tcp)
                                        .WithFrontend(frontendName)
                                        .WithFrontendPort(443)
                                        .WithProbe(httpsProbe)
                                        .WithBackend(backendPoolName2)
                                        .Attach()
                                        // Add two nat pools to enable direct VM connectivity for
                                        //  SSH to port 22 and TELNET to port 23
                                        .DefineInboundNatRule(natRule5000to22forVM1)
                                        .WithProtocol(TransportProtocol.Tcp)
                                        .WithFrontend(frontendName)
                                        .WithFrontendPort(5000)
                                        .WithBackendPort(22)
                                        .Attach()
                                        .DefineInboundNatRule(natRule5001to23forVM1)
                                        .WithProtocol(TransportProtocol.Tcp)
                                        .WithFrontend(frontendName)
                                        .WithFrontendPort(5001)
                                        .WithBackendPort(23)
                                        .Attach()
                                        .DefineInboundNatRule(natRule5002to22forVM2)
                                        .WithProtocol(TransportProtocol.Tcp)
                                        .WithFrontend(frontendName)
                                        .WithFrontendPort(5002)
                                        .WithBackendPort(22)
                                        .Attach()
                                        .DefineInboundNatRule(natRule5003to23forVM2)
                                        .WithProtocol(TransportProtocol.Tcp)
                                        .WithFrontend(frontendName)
                                        .WithFrontendPort(5003)
                                        .WithBackendPort(23)
                                        .Attach()
                                        .Create();

                    // Print load balancer details
                    Console.WriteLine("Created another load balancer");
                    Utilities.PrintLoadBalancer(loadBalancer2);

                    //=============================================================
                    // List load balancers

                    var loadBalancers = azure.LoadBalancers.List();

                    Console.WriteLine("Walking through the list of load balancers");

                    foreach (var loadBalancer in loadBalancers)
                    {
                        Utilities.PrintLoadBalancer(loadBalancer);
                    }

                    //=============================================================
                    // Remove a load balancer

                    Console.WriteLine("Deleting load balancer " + loadBalancerName2
                                      + "(" + loadBalancer2.Id + ")");
                    azure.LoadBalancers.Delete(loadBalancer2.Id);
                    Console.WriteLine("Deleted load balancer" + loadBalancerName2);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                }
                finally
                {
                    try
                    {
                        Console.WriteLine("Deleting Resource Group: " + rgName);
                        azure.ResourceGroups.Delete(rgName);
                        Console.WriteLine("Deleted Resource Group: " + rgName);
                    }
                    catch (NullReferenceException)
                    {
                        Console.WriteLine("Did not create any resources in Azure. No clean up is necessary");
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
Example #17
0
        public static void Main(string[] args)
        {
            try
            {
                //=============================================================
                // Authenticate
                AzureCredentials credentials = AzureCredentials.FromFile(Environment.GetEnvironmentVariable("AZURE_AUTH_LOCATION"));

                var azure = Azure
                            .Configure()
                            .WithLogLevel(HttpLoggingDelegatingHandler.Level.BASIC)
                            .Authenticate(credentials)
                            .WithDefaultSubscription();

                // Print selected subscription
                Console.WriteLine("Selected subscription: " + azure.SubscriptionId);

                try
                {
                    // Create a resource group [Where all resources gets created]
                    IResourceGroup resourceGroup = azure.ResourceGroups
                                                   .Define(rgName)
                                                   .WithRegion(Region.US_EAST)
                                                   .Create();

                    //============================================================
                    // Define a network security group for the front end of a subnet
                    // front end subnet contains two rules
                    // - ALLOW-SSH - allows SSH traffic into the front end subnet
                    // - ALLOW-WEB- allows HTTP traffic into the front end subnet

                    var frontEndNSGCreatable = azure.NetworkSecurityGroups
                                               .Define(frontEndNSGName)
                                               .WithRegion(Region.US_EAST)
                                               .WithExistingResourceGroup(resourceGroup)
                                               .DefineRule("ALLOW-SSH")
                                               .AllowInbound()
                                               .FromAnyAddress()
                                               .FromAnyPort()
                                               .ToAnyAddress()
                                               .ToPort(22)
                                               .WithProtocol(SecurityRuleProtocol.Tcp)
                                               .WithPriority(100)
                                               .WithDescription("Allow SSH")
                                               .Attach()
                                               .DefineRule("ALLOW-HTTP")
                                               .AllowInbound()
                                               .FromAnyAddress()
                                               .FromAnyPort()
                                               .ToAnyAddress()
                                               .ToPort(80)
                                               .WithProtocol(SecurityRuleProtocol.Tcp)
                                               .WithPriority(101)
                                               .WithDescription("Allow HTTP")
                                               .Attach();

                    //============================================================
                    // Define a network security group for the back end of a subnet
                    // back end subnet contains two rules
                    // - ALLOW-SQL - allows SQL traffic only from the front end subnet
                    // - DENY-WEB - denies all outbound internet traffic from the back end subnet

                    var backEndNSGCreatable = azure.NetworkSecurityGroups
                                              .Define(backEndNSGName)
                                              .WithRegion(Region.US_EAST)
                                              .WithExistingResourceGroup(resourceGroup)
                                              .DefineRule("ALLOW-SQL")
                                              .AllowInbound()
                                              .FromAddress("172.16.1.0/24")
                                              .FromAnyPort()
                                              .ToAnyAddress()
                                              .ToPort(1433)
                                              .WithProtocol(SecurityRuleProtocol.Tcp)
                                              .WithPriority(100)
                                              .WithDescription("Allow SQL")
                                              .Attach()
                                              .DefineRule("DENY-WEB")
                                              .DenyOutbound()
                                              .FromAnyAddress()
                                              .FromAnyPort()
                                              .ToAnyAddress()
                                              .ToAnyPort()
                                              .WithAnyProtocol()
                                              .WithDescription("Deny Web")
                                              .WithPriority(200)
                                              .Attach();

                    Console.WriteLine("Creating a security group for the front ends - allows SSH and HTTP");
                    Console.WriteLine("Creating a security group for the back ends - allows SSH and denies all outbound internet traffic");

                    var networkSecurityGroups = azure.NetworkSecurityGroups
                                                .Create(frontEndNSGCreatable, backEndNSGCreatable);

                    INetworkSecurityGroup frontendNSG = networkSecurityGroups.First(n => n.Name.Equals(frontEndNSGName, StringComparison.OrdinalIgnoreCase));
                    INetworkSecurityGroup backendNSG  = networkSecurityGroups.First(n => n.Name.Equals(backEndNSGName, StringComparison.OrdinalIgnoreCase));

                    Console.WriteLine("Created a security group for the front end: " + frontendNSG.Id);
                    Utilities.PrintNetworkSecurityGroup(frontendNSG);

                    Console.WriteLine("Created a security group for the back end: " + backendNSG.Id);
                    Utilities.PrintNetworkSecurityGroup(backendNSG);

                    // Create Network [Where all the virtual machines get added to]
                    var network = azure.Networks
                                  .Define(networkName)
                                  .WithRegion(Region.US_EAST)
                                  .WithExistingResourceGroup(resourceGroup)
                                  .WithAddressSpace("172.16.0.0/16")
                                  .DefineSubnet("Front-end")
                                  .WithAddressPrefix("172.16.1.0/24")
                                  .WithExistingNetworkSecurityGroup(frontendNSG)
                                  .Attach()
                                  .DefineSubnet("Back-end")
                                  .WithAddressPrefix("172.16.2.0/24")
                                  .WithExistingNetworkSecurityGroup(backendNSG)
                                  .Attach()
                                  .Create();

                    // Prepare Creatable Storage account definition [For storing VMs disk]
                    var creatableStorageAccount = azure.StorageAccounts
                                                  .Define(storageAccountName)
                                                  .WithRegion(Region.US_EAST)
                                                  .WithExistingResourceGroup(resourceGroup);

                    // Prepare a batch of Creatable Virtual Machines definitions
                    List <ICreatable <IVirtualMachine> > frontendCreatableVirtualMachines = new List <ICreatable <IVirtualMachine> >();

                    for (int i = 0; i < frontendVmCount; i++)
                    {
                        var creatableVirtualMachine = azure.VirtualMachines
                                                      .Define("VM-FE-" + i)
                                                      .WithRegion(Region.US_EAST)
                                                      .WithExistingResourceGroup(resourceGroup)
                                                      .WithExistingPrimaryNetwork(network)
                                                      .WithSubnet("Front-end")
                                                      .WithPrimaryPrivateIpAddressDynamic()
                                                      .WithoutPrimaryPublicIpAddress()
                                                      .WithPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS)
                                                      .WithRootUserName(userName)
                                                      .WithPassword(password)
                                                      .WithSize(VirtualMachineSizeTypes.StandardD3V2)
                                                      .WithNewStorageAccount(creatableStorageAccount);
                        frontendCreatableVirtualMachines.Add(creatableVirtualMachine);
                    }

                    List <ICreatable <IVirtualMachine> > backendCreatableVirtualMachines = new List <ICreatable <IVirtualMachine> >();

                    for (int i = 0; i < backendVmCount; i++)
                    {
                        var creatableVirtualMachine = azure.VirtualMachines
                                                      .Define("VM-BE-" + i)
                                                      .WithRegion(Region.US_EAST)
                                                      .WithExistingResourceGroup(resourceGroup)
                                                      .WithExistingPrimaryNetwork(network)
                                                      .WithSubnet("Back-end")
                                                      .WithPrimaryPrivateIpAddressDynamic()
                                                      .WithoutPrimaryPublicIpAddress()
                                                      .WithPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS)
                                                      .WithRootUserName(userName)
                                                      .WithPassword(password)
                                                      .WithSize(VirtualMachineSizeTypes.StandardD3V2)
                                                      .WithNewStorageAccount(creatableStorageAccount);
                        backendCreatableVirtualMachines.Add(creatableVirtualMachine);
                    }

                    var startTime = DateTimeOffset.Now.UtcDateTime;
                    Console.WriteLine("Creating the virtual machines");

                    List <ICreatable <IVirtualMachine> > allCreatableVirtualMachines = new List <ICreatable <IVirtualMachine> >();
                    allCreatableVirtualMachines.AddRange(frontendCreatableVirtualMachines);
                    allCreatableVirtualMachines.AddRange(backendCreatableVirtualMachines);

                    var virtualMachines = azure.VirtualMachines.Create(allCreatableVirtualMachines.ToArray());

                    var endTime = DateTimeOffset.Now.UtcDateTime;
                    Console.WriteLine("Created virtual machines");

                    foreach (var virtualMachine in virtualMachines)
                    {
                        Console.WriteLine(virtualMachine.Id);
                    }

                    Console.WriteLine($"Virtual machines create: took {(endTime - startTime).TotalSeconds } seconds");
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                }
                finally
                {
                    Console.WriteLine($"Deleting resource group : {rgName}");
                    azure.ResourceGroups.Delete(rgName);
                    Console.WriteLine($"Deleted resource group : {rgName}");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
        public static void Main(string[] args)
        {
            try
            {
                var rgName           = ResourceNamer.RandomResourceName("rgRSMA", 24);
                var rgName2          = ResourceNamer.RandomResourceName("rgRSMA", 24);
                var resourceTagName  = ResourceNamer.RandomResourceName("rgRSTN", 24);
                var resourceTagValue = ResourceNamer.RandomResourceName("rgRSTV", 24);

                try
                {
                    //=================================================================
                    // Authenticate
                    AzureCredentials credentials = AzureCredentials.FromFile(Environment.GetEnvironmentVariable("AZURE_AUTH_LOCATION"));

                    var azure = Azure
                                .Configure()
                                .WithLogLevel(HttpLoggingDelegatingHandler.Level.BASIC)
                                .Authenticate(credentials)
                                .WithDefaultSubscription();

                    try
                    {
                        //=============================================================
                        // Create resource group.

                        Console.WriteLine("Creating a resource group with name: " + rgName);

                        var resourceGroup = azure.ResourceGroups
                                            .Define(rgName)
                                            .WithRegion(Region.US_WEST)
                                            .Create();

                        Console.WriteLine("Created a resource group with name: " + rgName);

                        //=============================================================
                        // Update the resource group.

                        Console.WriteLine("Updating the resource group with name: " + rgName);

                        resourceGroup.Update()
                        .WithTag(resourceTagName, resourceTagValue)
                        .Apply();

                        Console.WriteLine("Updated the resource group with name: " + rgName);

                        //=============================================================
                        // Create another resource group.

                        Console.WriteLine("Creating another resource group with name: " + rgName2);

                        var resourceGroup2 = azure.ResourceGroups
                                             .Define(rgName2)
                                             .WithRegion(Region.US_WEST)
                                             .Create();

                        Console.WriteLine("Created another resource group with name: " + rgName2);

                        //=============================================================
                        // List resource groups.

                        Console.WriteLine("Listing all resource groups");

                        foreach (var rGroup in azure.ResourceGroups.List())
                        {
                            Console.WriteLine("Resource group: " + rGroup.Name);
                        }

                        //=============================================================
                        // Delete a resource group.

                        Console.WriteLine("Deleting resource group: " + rgName2);

                        azure.ResourceGroups.Delete(rgName2);

                        Console.WriteLine("Deleted resource group: " + rgName2);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex);
                    }
                    finally
                    {
                        try
                        {
                            Console.WriteLine("Deleting Resource Group: " + rgName);
                            azure.ResourceGroups.Delete(rgName);
                            Console.WriteLine("Deleted Resource Group: " + rgName);
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
        public static void Main(string[] args)
        {
            try
            {
                //=================================================================
                // Authenticate
                var credentials = AzureCredentials.FromFile(Environment.GetEnvironmentVariable("AZURE_AUTH_LOCATION"));

                var azure = Azure
                            .Configure()
                            .WithLogLevel(HttpLoggingDelegatingHandler.Level.BASIC)
                            .Authenticate(credentials)
                            .WithDefaultSubscription();

                // Print selected subscription
                Console.WriteLine("Selected subscription: " + azure.SubscriptionId);
                try
                {
                    //============================================================
                    // Assign a public IP address for a VM during its creation

                    // Define a public IP address to be used during VM creation time

                    Console.WriteLine("Creating a public IP address...");

                    var publicIpAddress = azure.PublicIpAddresses
                                          .Define(publicIpAddressName1)
                                          .WithRegion(Region.US_EAST)
                                          .WithNewResourceGroup(rgName)
                                          .WithLeafDomainLabel(publicIpAddressLeafDNS1)
                                          .Create();

                    Console.WriteLine("Created a public IP address");
                    // Print public IP address details
                    Utilities.PrintIpAddress(publicIpAddress);

                    // Use the pre-created public IP for the new VM

                    Console.WriteLine("Creating a Windows VM");

                    var t1 = DateTime.UtcNow;

                    var vm = azure.VirtualMachines.Define(vmName)
                             .WithRegion(Region.US_EAST)
                             .WithExistingResourceGroup(rgName)
                             .WithNewPrimaryNetwork("10.0.0.0/28")
                             .WithPrimaryPrivateIpAddressDynamic()
                             .WithExistingPrimaryPublicIpAddress(publicIpAddress)
                             .WithPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2012_R2_DATACENTER)
                             .WithAdminUserName(userName)
                             .WithPassword(password)
                             .WithSize(VirtualMachineSizeTypes.StandardD3V2)
                             .Create();

                    var t2 = DateTime.UtcNow;
                    Console.WriteLine("Created VM: (took "
                                      + (t2 - t1).TotalSeconds + " seconds) " + vm.Id);
                    // Print virtual machine details
                    Utilities.PrintVirtualMachine(vm);

                    //============================================================
                    // Gets the public IP address associated with the VM's primary NIC

                    Console.WriteLine("Public IP address associated with the VM's primary NIC [After create]");
                    // Print the public IP address details
                    Utilities.PrintIpAddress(vm.GetPrimaryPublicIpAddress());

                    //============================================================
                    // Assign a new public IP address for the VM

                    // Define a new public IP address

                    var publicIpAddress2 = azure.PublicIpAddresses
                                           .Define(publicIpAddressName2)
                                           .WithRegion(Region.US_EAST)
                                           .WithNewResourceGroup(rgName)
                                           .WithLeafDomainLabel(publicIpAddressLeafDNS2)
                                           .Create();

                    // Update VM's primary NIC to use the new public IP address

                    Console.WriteLine("Updating the VM's primary NIC with new public IP address");

                    var primaryNetworkInterface = vm.GetPrimaryNetworkInterface();
                    primaryNetworkInterface
                    .Update()
                    .WithExistingPrimaryPublicIpAddress(publicIpAddress2)
                    .Apply();

                    //============================================================
                    // Gets the updated public IP address associated with the VM

                    // Get the associated public IP address for a virtual machine
                    Console.WriteLine("Public IP address associated with the VM's primary NIC [After Update]");
                    vm.Refresh();
                    Utilities.PrintIpAddress(vm.GetPrimaryPublicIpAddress());

                    //============================================================
                    // Remove public IP associated with the VM

                    Console.WriteLine("Removing public IP address associated with the VM");
                    vm.Refresh();
                    primaryNetworkInterface = vm.GetPrimaryNetworkInterface();
                    publicIpAddress         = primaryNetworkInterface.PrimaryIpConfiguration.GetPublicIpAddress();
                    primaryNetworkInterface.Update()
                    .WithoutPrimaryPublicIpAddress()
                    .Apply();

                    Console.WriteLine("Removed public IP address associated with the VM");

                    //============================================================
                    // Delete the public ip
                    Console.WriteLine("Deleting the public IP address");
                    azure.PublicIpAddresses.Delete(publicIpAddress.Id);
                    Console.WriteLine("Deleted the public IP address");
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                }
                finally
                {
                    try
                    {
                        Console.WriteLine("Deleting Resource Group: " + rgName);
                        azure.ResourceGroups.Delete(rgName);
                        Console.WriteLine("Deleted Resource Group: " + rgName);
                    }
                    catch (NullReferenceException)
                    {
                        Console.WriteLine("Did not create any resources in Azure. No clean up is necessary");
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
        public static void Main(string[] args)
        {
            try
            {
                //=================================================================
                // Authenticate
                var credentials = AzureCredentials.FromFile(Environment.GetEnvironmentVariable("AZURE_AUTH_LOCATION"));

                var azure = Azure
                            .Configure()
                            .WithLogLevel(HttpLoggingDelegatingHandler.Level.BASIC)
                            .Authenticate(credentials)
                            .WithDefaultSubscription();

                // Print selected subscription
                Console.WriteLine("Selected subscription: " + azure.SubscriptionId);

                try
                {
                    //============================================================
                    // Create a virtual network with specific address-space and two subnet

                    // Creates a network security group for backend subnet

                    Console.WriteLine("Creating a network security group for virtual network backend subnet...");

                    var backEndSubnetNsg = azure.NetworkSecurityGroups
                                           .Define(vnet1BackEndSubnetNsgName)
                                           .WithRegion(Region.US_EAST)
                                           .WithNewResourceGroup(rgName)
                                           .DefineRule("DenyInternetInComing")
                                           .DenyInbound()
                                           .FromAddress("INTERNET")
                                           .FromAnyPort()
                                           .ToAnyAddress()
                                           .ToAnyPort()
                                           .WithAnyProtocol()
                                           .Attach()
                                           .DefineRule("DenyInternetOutGoing")
                                           .DenyOutbound()
                                           .FromAnyAddress()
                                           .FromAnyPort()
                                           .ToAddress("INTERNET")
                                           .ToAnyPort()
                                           .WithAnyProtocol()
                                           .Attach()
                                           .Create();

                    Console.WriteLine("Created network security group");
                    // Print the network security group
                    Utilities.PrintNetworkSecurityGroup(backEndSubnetNsg);

                    // Create the virtual network with frontend and backend subnets, with
                    // network security group rule applied to backend subnet]

                    Console.WriteLine("Creating virtual network #1...");

                    var virtualNetwork1 = azure.Networks
                                          .Define(vnetName1)
                                          .WithRegion(Region.US_EAST)
                                          .WithExistingResourceGroup(rgName)
                                          .WithAddressSpace("192.168.0.0/16")
                                          .WithSubnet(vnet1FrontEndSubnetName, "192.168.1.0/24")
                                          .DefineSubnet(vnet1BackEndSubnetName)
                                          .WithAddressPrefix("192.168.2.0/24")
                                          .WithExistingNetworkSecurityGroup(backEndSubnetNsg)
                                          .Attach()
                                          .Create();

                    Console.WriteLine("Created a virtual network");
                    // Print the virtual network details
                    Utilities.PrintVirtualNetwork(virtualNetwork1);

                    //============================================================
                    // Update a virtual network

                    // Creates a network security group for frontend subnet

                    Console.WriteLine("Creating a network security group for virtual network backend subnet...");

                    var frontEndSubnetNsg = azure.NetworkSecurityGroups
                                            .Define(vnet1FrontEndSubnetNsgName)
                                            .WithRegion(Region.US_EAST)
                                            .WithExistingResourceGroup(rgName)
                                            .DefineRule("AllowHttpInComing")
                                            .AllowInbound()
                                            .FromAddress("INTERNET")
                                            .FromAnyPort()
                                            .ToAnyAddress()
                                            .ToPort(80)
                                            .WithProtocol(SecurityRuleProtocol.Tcp)
                                            .Attach()
                                            .DefineRule("DenyInternetOutGoing")
                                            .DenyOutbound()
                                            .FromAnyAddress()
                                            .FromAnyPort()
                                            .ToAddress("INTERNET")
                                            .ToAnyPort()
                                            .WithAnyProtocol()
                                            .Attach()
                                            .Create();

                    Console.WriteLine("Created network security group");
                    // Print the network security group
                    Utilities.PrintNetworkSecurityGroup(frontEndSubnetNsg);

                    // Update the virtual network frontend subnet by associating it with network security group

                    Console.WriteLine("Associating network security group rule to frontend subnet");

                    virtualNetwork1.Update()
                    .UpdateSubnet(vnet1FrontEndSubnetName)
                    .WithExistingNetworkSecurityGroup(frontEndSubnetNsg)
                    .Parent()
                    .Apply();

                    Console.WriteLine("Network security group rule associated with the frontend subnet");
                    // Print the virtual network details
                    Utilities.PrintVirtualNetwork(virtualNetwork1);

                    //============================================================
                    // Create a virtual machine in each subnet

                    // Creates the first virtual machine in frontend subnet

                    Console.WriteLine("Creating a Linux virtual machine in the frontend subnet");

                    var t1 = DateTime.UtcNow;

                    var frontEndVM = azure.VirtualMachines.Define(frontEndVmName)
                                     .WithRegion(Region.US_EAST)
                                     .WithExistingResourceGroup(rgName)
                                     .WithExistingPrimaryNetwork(virtualNetwork1)
                                     .WithSubnet(vnet1FrontEndSubnetName)
                                     .WithPrimaryPrivateIpAddressDynamic()
                                     .WithNewPrimaryPublicIpAddress(publicIpAddressLeafDnsForFrontEndVm)
                                     .WithPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS)
                                     .WithRootUserName(userName)
                                     .WithSsh(sshKey)
                                     .WithSize(VirtualMachineSizeTypes.StandardD3V2)
                                     .Create();

                    var t2 = DateTime.UtcNow;
                    Console.WriteLine("Created Linux VM: (took "
                                      + (t2 - t1).TotalSeconds + " seconds) " + frontEndVM.Id);
                    // Print virtual machine details
                    Utilities.PrintVirtualMachine(frontEndVM);

                    // Creates the second virtual machine in the backend subnet

                    Console.WriteLine("Creating a Linux virtual machine in the backend subnet");

                    var t3 = DateTime.UtcNow;

                    var backEndVM = azure.VirtualMachines.Define(backEndVmName)
                                    .WithRegion(Region.US_EAST)
                                    .WithExistingResourceGroup(rgName)
                                    .WithExistingPrimaryNetwork(virtualNetwork1)
                                    .WithSubnet(vnet1BackEndSubnetName)
                                    .WithPrimaryPrivateIpAddressDynamic()
                                    .WithoutPrimaryPublicIpAddress()
                                    .WithPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS)
                                    .WithRootUserName(userName)
                                    .WithSsh(sshKey)
                                    .WithSize(VirtualMachineSizeTypes.StandardD3V2)
                                    .Create();

                    var t4 = DateTime.UtcNow;
                    Console.WriteLine("Created Linux VM: (took "
                                      + (t4 - t3).TotalSeconds + " seconds) " + backEndVM.Id);
                    // Print virtual machine details
                    Utilities.PrintVirtualMachine(backEndVM);

                    //============================================================
                    // Create a virtual network with default address-space and one default subnet

                    Console.WriteLine("Creating virtual network #2...");

                    var virtualNetwork2 = azure.Networks
                                          .Define(vnetName2)
                                          .WithRegion(Region.US_EAST)
                                          .WithNewResourceGroup(rgName)
                                          .Create();

                    Console.WriteLine("Created a virtual network");
                    // Print the virtual network details
                    Utilities.PrintVirtualNetwork(virtualNetwork2);

                    //============================================================
                    // List virtual networks

                    foreach (var virtualNetwork in azure.Networks.ListByGroup(rgName))
                    {
                        Utilities.PrintVirtualNetwork(virtualNetwork);
                    }

                    //============================================================
                    // Delete a virtual network
                    Console.WriteLine("Deleting the virtual network");
                    azure.Networks.Delete(virtualNetwork2.Id);
                    Console.WriteLine("Deleted the virtual network");
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                }
                finally
                {
                    try
                    {
                        Console.WriteLine("Deleting Resource Group: " + rgName);
                        azure.ResourceGroups.Delete(rgName);
                        Console.WriteLine("Deleted Resource Group: " + rgName);
                    }
                    catch (NullReferenceException)
                    {
                        Console.WriteLine("Did not create any resources in Azure. No clean up is necessary");
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
        public static void Main(string[] args)
        {
            try
            {
                //=================================================================
                // Authenticate
                AzureCredentials credentials = AzureCredentials.FromFile(Environment.GetEnvironmentVariable("AZURE_AUTH_LOCATION"));

                var azure = Azure
                            .Configure()
                            .WithLogLevel(HttpLoggingDelegatingHandler.Level.BASIC)
                            .Authenticate(credentials)
                            .WithDefaultSubscription();

                //=================================================================
                // List all virtual machine extension image publishers and
                // list all virtual machine extension images
                // published by Microsoft.OSTCExtensions and Microsoft.Azure.Extensions
                // y browsing through extension image publishers, types, and versions

                var publishers = azure
                                 .VirtualMachineImages
                                 .Publishers
                                 .ListByRegion(Region.US_EAST);

                Console.WriteLine("US East data center: printing list of \n"
                                  + "a) Publishers and\n"
                                  + "b) virtual machine images published by Microsoft.OSTCExtensions and Microsoft.Azure.Extensions");
                Console.WriteLine("=======================================================");
                Console.WriteLine("\n");

                foreach (var publisher in publishers)
                {
                    Console.WriteLine("Publisher - " + publisher.Name);

                    if (StringComparer.OrdinalIgnoreCase.Equals(publisher.Name, "Microsoft.OSTCExtensions") ||
                        StringComparer.OrdinalIgnoreCase.Equals(publisher.Name, "Microsoft.Azure.Extensions"))
                    {
                        Console.WriteLine("\n\n");
                        Console.WriteLine("=======================================================");
                        Console.WriteLine("Located " + publisher.Name);
                        Console.WriteLine("=======================================================");
                        Console.WriteLine("Printing entries as publisher/type/version");

                        foreach (var imageType in publisher.ExtensionTypes.List())
                        {
                            foreach (var version in imageType.Versions.List())
                            {
                                var image = version.GetImage();
                                Console.WriteLine($"Image - {publisher.Name}/{image.TypeName}/{image.VersionName}");
                            }
                        }
                        Console.WriteLine("\n\n");
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }