示例#1
0
        /**
         * Azure Compute sample for managing virtual machines -
         *  - Create an managed virtual machine from PIR image with data disks
         *  - Create snapshot from the virtual machine's OS and data disks
         *  - Create managed disks from the snapshots
         *  - Create virtual machine by attaching the managed disks
         *  - Get SAS Uri to the virtual machine's managed disks.
         */
        public static void RunSample(IAzure azure)
        {
            var linuxVmName1                  = Utilities.CreateRandomName("VM1");
            var linuxVmName2                  = Utilities.CreateRandomName("VM2");
            var managedOSSnapshotName         = Utilities.CreateRandomName("ss-os-");
            var managedDataDiskSnapshotPrefix = Utilities.CreateRandomName("ss-data-");
            var managedNewOSDiskName          = Utilities.CreateRandomName("ds-os-nw-");
            var managedNewDataDiskNamePrefix  = Utilities.CreateRandomName("ds-data-nw-");

            var rgName               = Utilities.CreateRandomName("rgCOMV");
            var publicIpDnsLabel     = Utilities.CreateRandomName("pip");
            var apacheInstallScript  = "https://raw.githubusercontent.com/Azure/azure-libraries-for-net/master/Samples/Asset/install_apache.sh";
            var apacheInstallCommand = "bash install_apache.sh";

            var apacheInstallScriptUris = new List <string>();

            apacheInstallScriptUris.Add(apacheInstallScript);

            try
            {
                //=============================================================
                // Create a Linux VM using a PIR image with managed OS and data disks and customize virtual
                // machine using custom script extension

                Utilities.Log("Creating a un-managed Linux VM");

                var linuxVM = azure.VirtualMachines.Define(linuxVmName1)
                              .WithRegion(region)
                              .WithNewResourceGroup(rgName)
                              .WithNewPrimaryNetwork("10.0.0.0/28")
                              .WithPrimaryPrivateIPAddressDynamic()
                              .WithNewPrimaryPublicIPAddress(publicIpDnsLabel)
                              .WithPopularLinuxImage(KnownLinuxVirtualMachineImage.UbuntuServer16_04_Lts)
                              .WithRootUsername(userName)
                              .WithRootPassword(password)
                              .WithNewDataDisk(100)
                              .WithNewDataDisk(100, 1, CachingTypes.ReadWrite)
                              .WithSize(VirtualMachineSizeTypes.Parse("Standard_D2a_v4"))
                              .DefineNewExtension("CustomScriptForLinux")
                              .WithPublisher("Microsoft.OSTCExtensions")
                              .WithType("CustomScriptForLinux")
                              .WithVersion("1.4")
                              .WithMinorVersionAutoUpgrade()
                              .WithPublicSetting("fileUris", apacheInstallScriptUris)
                              .WithPublicSetting("commandToExecute", apacheInstallCommand)
                              .Attach()
                              .Create();

                Utilities.Log("Created a Linux VM with managed OS and data disks: " + linuxVM.Id);
                Utilities.PrintVirtualMachine(linuxVM);

                // Gets the specialized managed OS and Data disks of the virtual machine
                //
                var osDisk    = azure.Disks.GetById(linuxVM.OSDiskId);
                var dataDisks = new List <IDisk>();
                foreach (var disk in linuxVM.DataDisks.Values)
                {
                    var dataDisk = azure.Disks.GetById(disk.Id);
                    dataDisks.Add(dataDisk);
                }

                //=============================================================
                // Delete the virtual machine
                Utilities.Log("Deleting VM: " + linuxVM.Id);

                azure.VirtualMachines.DeleteById(linuxVM.Id);

                Utilities.Log("Deleted the VM");

                //=============================================================
                // Create Snapshot from the OS managed disk

                Utilities.Log($"Creating managed snapshot from the managed disk (holding specialized OS): {osDisk.Id}");

                var osSnapshot = azure.Snapshots.Define(managedOSSnapshotName)
                                 .WithRegion(region)
                                 .WithExistingResourceGroup(rgName)
                                 .WithLinuxFromDisk(osDisk)
                                 .Create();

                Utilities.Log("Created managed snapshot holding OS: " + osSnapshot.Id);
                // Utilities.Print(osSnapshot); TODO

                //=============================================================
                // Create Managed snapshot from the Data managed disks

                var dataSnapshots = new List <ISnapshot>();
                var i             = 0;
                foreach (var dataDisk in dataDisks)
                {
                    Utilities.Log($"Creating managed snapshot from the managed disk (holding data): {dataDisk.Id} ");

                    var dataSnapshot = azure.Snapshots.Define(managedDataDiskSnapshotPrefix + "-" + i)
                                       .WithRegion(region)
                                       .WithExistingResourceGroup(rgName)
                                       .WithDataFromDisk(dataDisk)
                                       .WithSku(DiskSkuTypes.StandardLRS)
                                       .Create();
                    dataSnapshots.Add(dataSnapshot);

                    Utilities.Log("Created managed snapshot holding data: " + dataSnapshot.Id);
                    // Utilities.Print(dataDisk); TODO
                    i++;
                }

                //=============================================================
                // Create Managed disk from the specialized OS snapshot

                Utilities.Log(String.Format("Creating managed disk from the snapshot holding OS: %s ", osSnapshot.Id));

                var newOSDisk = azure.Disks.Define(managedNewOSDiskName)
                                .WithRegion(region)
                                .WithExistingResourceGroup(rgName)
                                .WithLinuxFromSnapshot(osSnapshot)
                                .WithSizeInGB(100)
                                .Create();

                Utilities.Log("Created managed disk holding OS: " + osDisk.Id);
                // Utilities.Print(osDisk); TODO

                //=============================================================
                // Create Managed disks from the data snapshots

                var newDataDisks = new List <IDisk>();
                i = 0;
                foreach (var dataSnapshot in dataSnapshots)
                {
                    Utilities.Log($"Creating managed disk from the Data snapshot: {dataSnapshot.Id} ");

                    var dataDisk = azure.Disks.Define(managedNewDataDiskNamePrefix + "-" + i)
                                   .WithRegion(region)
                                   .WithExistingResourceGroup(rgName)
                                   .WithData()
                                   .FromSnapshot(dataSnapshot)
                                   .Create();
                    newDataDisks.Add(dataDisk);

                    Utilities.Log("Created managed disk holding data: " + dataDisk.Id);
                    // Utilities.Print(dataDisk); TODO
                    i++;
                }

                //
                //=============================================================
                // Create a Linux VM by attaching the managed disks

                Utilities.Log("Creating a Linux VM using specialized OS and data disks");

                var linuxVM2 = azure.VirtualMachines.Define(linuxVmName2)
                               .WithRegion(region)
                               .WithExistingResourceGroup(rgName)
                               .WithNewPrimaryNetwork("10.0.0.0/28")
                               .WithPrimaryPrivateIPAddressDynamic()
                               .WithoutPrimaryPublicIPAddress()
                               .WithSpecializedOSDisk(newOSDisk, OperatingSystemTypes.Linux)
                               .WithExistingDataDisk(newDataDisks[0])
                               .WithExistingDataDisk(newDataDisks[1], 1, CachingTypes.ReadWrite)
                               .WithSize(VirtualMachineSizeTypes.Parse("Standard_D2a_v4"))
                               .Create();

                Utilities.PrintVirtualMachine(linuxVM2);

                //=============================================================
                //
                Utilities.Log("Deleting OS snapshot - " + osSnapshot.Id);

                azure.Snapshots.DeleteById(osSnapshot.Id);

                Utilities.Log("Deleted OS snapshot");

                foreach (var dataSnapshot in dataSnapshots)
                {
                    Utilities.Log("Deleting data snapshot - " + dataSnapshot.Id);

                    azure.Snapshots.DeleteById(dataSnapshot.Id);

                    Utilities.Log("Deleted data snapshot");
                }

                // Getting the SAS URIs requires virtual machines to be de-allocated
                // [Access not permitted because'disk' is currently attached to running VM]
                //
                Utilities.Log("De-allocating the virtual machine - " + linuxVM2.Id);

                linuxVM2.Deallocate();

                //=============================================================
                // Get the readonly SAS URI to the OS and data disks

                Utilities.Log("Getting OS and data disks SAS Uris");

                // OS Disk SAS Uri
                osDisk = azure.Disks.GetById(linuxVM2.OSDiskId);

                var osDiskSasUri = osDisk.GrantAccess(24 * 60);

                Utilities.Log("OS disk SAS Uri: " + osDiskSasUri);

                // Data disks SAS Uri
                foreach (var disk in linuxVM2.DataDisks.Values)
                {
                    var dataDisk       = azure.Disks.GetById(disk.Id);
                    var dataDiskSasUri = dataDisk.GrantAccess(24 * 60);
                    Utilities.Log($"Data disk (lun: {disk.Lun}) SAS Uri: {dataDiskSasUri}");
                }
            }
            finally
            {
                try
                {
                    Utilities.Log("Deleting Resource Group: " + rgName);
                    azure.ResourceGroups.DeleteByName(rgName);
                    Utilities.Log("Deleted Resource Group: " + rgName);
                }
                catch (NullReferenceException)
                {
                    Utilities.Log("Did not create any resources in Azure. No clean up is necessary");
                }
                catch (Exception g)
                {
                    Utilities.Log(g);
                }
            }
        }
示例#2
0
        /**
         * Azure Compute sample for managing virtual machines -
         *  - Create a Resource Group and User Assigned MSI with CONTRIBUTOR access to the resource group
         *  - Create a Linux VM and associate it with User Assigned MSI
         *      - Install Java8, Maven3 and GIT on the VM using Azure Custom Script Extension
         *  - Run Java application in the MSI enabled Linux VM which uses MSI credentials to manage Azure resource
         *  - Retrieve the Virtual machine created from the MSI enabled Linux VM.
         */
        public static void RunSample(IAzure azure)
        {
            var rgName1      = Utilities.CreateRandomName("uamsi-rg-1");
            var rgName2      = Utilities.CreateRandomName("uamsi-rg-2");
            var identityName = Utilities.CreateRandomName("id");
            var linuxVMName  = Utilities.CreateRandomName("VM1");
            var pipName      = Utilities.CreateRandomName("pip1");
            var userName     = "******";
            var password     = "******";
            var region       = Region.USWestCentral;

            try
            {
                //============================================================================================
                // Create a Resource Group and User Assigned MSI with CONTRIBUTOR access to the resource group

                Utilities.Log("Creating a Resource Group and User Assigned MSI with CONTRIBUTOR access to the resource group");

                var resourceGroup1 = azure.ResourceGroups
                                     .Define(rgName1)
                                     .WithRegion(region)
                                     .Create();

                var identity = azure.Identities
                               .Define(identityName)
                               .WithRegion(region)
                               .WithNewResourceGroup(rgName2)
                               .WithAccessTo(resourceGroup1.Id, BuiltInRole.Contributor)
                               .Create();

                Utilities.Log("Created Resource Group and User Assigned MSI");

                Utilities.PrintResourceGroup(resourceGroup1);
                Utilities.PrintIdentity(identity);

                //============================================================================================
                // Create a Linux VM and associate it with User Assigned MSI
                // Install DontNet and Git on the VM using Azure Custom Script Extension

                // The script to install DontNet and Git on a virtual machine using Azure Custom Script Extension
                //
                var           invokeScriptCommand = "bash install_dotnet_git.sh";
                List <string> fileUris            = new List <string>()
                {
                    "https://raw.githubusercontent.com/Azure/azure-libraries-for-net/master/Samples/Asset/install_dotnet_git.sh"
                };

                Utilities.Log("Creating a Linux VM with MSI associated and install DotNet and Git");

                var virtualMachine = azure.VirtualMachines
                                     .Define(linuxVMName)
                                     .WithRegion(region)
                                     .WithExistingResourceGroup(rgName2)
                                     .WithNewPrimaryNetwork("10.0.0.0/28")
                                     .WithPrimaryPrivateIPAddressDynamic()
                                     .WithNewPrimaryPublicIPAddress(pipName)
                                     .WithPopularLinuxImage(KnownLinuxVirtualMachineImage.UbuntuServer16_04_Lts)
                                     .WithRootUsername(userName)
                                     .WithRootPassword(password)
                                     .WithSize(VirtualMachineSizeTypes.Parse("Standard_D2a_v4"))
                                     .WithExistingUserAssignedManagedServiceIdentity(identity)
                                     .DefineNewExtension("CustomScriptForLinux")
                                     .WithPublisher("Microsoft.OSTCExtensions")
                                     .WithType("CustomScriptForLinux")
                                     .WithVersion("1.4")
                                     .WithMinorVersionAutoUpgrade()
                                     .WithPublicSetting("fileUris", fileUris)
                                     .WithPublicSetting("commandToExecute", invokeScriptCommand)
                                     .Attach()
                                     .Create();

                Utilities.Log("Created Linux VM");

                Utilities.PrintVirtualMachine(virtualMachine);

                //=============================================================
                // Run Java application in the MSI enabled Linux VM which uses MSI credentials to manage Azure resource

                Utilities.Log("Running .NET application in the MSI enabled VM which creates another virtual machine");

                List <String> commands = new List <string>
                {
                    "git clone https://github.com/Azure-Samples/compute-dotnet-manage-vm-from-vm-with-msi-credentials.git",
                    "cd compute-dotnet-manage-vm-from-vm-with-msi-credentials",
                    $"dotnet run {azure.SubscriptionId} {rgName1} {identity.ClientId}"
                };

                RunCommandOnVM(azure, virtualMachine, commands);

                Utilities.Log("DotNet application executed");

                //=============================================================
                // Retrieve the Virtual machine created from the MSI enabled Linux VM

                Utilities.Log("Retrieving the virtual machine created from the MSI enabled Linux VM");

                var virtualMachines = azure.VirtualMachines.ListByResourceGroup(resourceGroup1.Name);
                foreach (var vm in virtualMachines)
                {
                    Utilities.PrintVirtualMachine(vm);
                }
            }
            finally
            {
                try
                {
                    Utilities.Log($"Deleting Resource Group: {rgName1}");
                    azure.ResourceGroups.DeleteByName(rgName1);
                    Utilities.Log($"Deleted Resource Group: {rgName1}");

                    Utilities.Log($"Deleting Resource Group: {rgName2}");
                    azure.ResourceGroups.DeleteByName(rgName2);
                    Utilities.Log($"Deleted Resource Group: {rgName2}");
                }
                catch (NullReferenceException)
                {
                    Utilities.Log("Did not create any resources in Azure. No clean up is necessary");
                }
                catch (Exception g)
                {
                    Utilities.Log(g);
                }
            }
        }
        /**
         * Azure Compute sample for managing virtual machines -
         *  - Create a virtual machine
         *  - Deallocate the virtual machine
         *  - Generalize the virtual machine
         *  - Capture the virtual machine to create a generalized image
         *  - Create a second virtual machine using the generalized image
         *  - Delete the second virtual machine
         *  - Create a new virtual machine by attaching OS disk of deleted VM to it.
         */
        public static void RunSample(IAzure azure)
        {
            string rgName           = SdkContext.RandomResourceName("rgCOMV", 10);
            string linuxVmName1     = SdkContext.RandomResourceName("VM1", 10);
            string linuxVmName2     = SdkContext.RandomResourceName("VM2", 10);
            string linuxVmName3     = SdkContext.RandomResourceName("VM3", 10);
            string publicIpDnsLabel = SdkContext.RandomResourceName("pip", 10);

            try
            {
                //=============================================================
                // Create a Linux VM using an image from PIR (Platform Image Repository)

                Utilities.Log("Creating a Linux VM");

                var linuxVM = azure.VirtualMachines.Define(linuxVmName1)
                              .WithRegion(Region.USWest)
                              .WithNewResourceGroup(rgName)
                              .WithNewPrimaryNetwork("10.0.0.0/28")
                              .WithPrimaryPrivateIPAddressDynamic()
                              .WithNewPrimaryPublicIPAddress(publicIpDnsLabel)
                              .WithPopularLinuxImage(KnownLinuxVirtualMachineImage.UbuntuServer16_04_Lts)
                              .WithRootUsername(UserName)
                              .WithRootPassword(Password)
                              .WithUnmanagedDisks()
                              .WithSize(VirtualMachineSizeTypes.Parse("Standard_D2a_v4"))
                              .DefineNewExtension("CustomScriptForLinux")
                              .WithPublisher("Microsoft.OSTCExtensions")
                              .WithType("CustomScriptForLinux")
                              .WithVersion("1.4")
                              .WithMinorVersionAutoUpgrade()
                              .WithPublicSetting("fileUris", ApacheInstallScriptUris)
                              .WithPublicSetting("commandToExecute", ApacheInstallCommand)
                              .Attach()
                              .Create();

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

                // De-provision the virtual machine
                Utilities.DeprovisionAgentInLinuxVM(linuxVM.GetPrimaryPublicIPAddress().Fqdn, 22, UserName, Password);

                //=============================================================
                // Deallocate the virtual machine
                Utilities.Log("Deallocate VM: " + linuxVM.Id);

                linuxVM.Deallocate();

                Utilities.Log("Deallocated VM: " + linuxVM.Id + "; state = " + linuxVM.PowerState);

                //=============================================================
                // Generalize the virtual machine
                Utilities.Log("Generalize VM: " + linuxVM.Id);

                linuxVM.Generalize();

                Utilities.Log("Generalized VM: " + linuxVM.Id);

                //=============================================================
                // Capture the virtual machine to get a 'Generalized image' with Apache
                Utilities.Log("Capturing VM: " + linuxVM.Id);

                var capturedResultJson = linuxVM.Capture("capturedvhds", "img", true);

                Utilities.Log("Captured VM: " + linuxVM.Id);

                //=============================================================
                // Create a Linux VM using captured image (Generalized image)
                JObject o             = JObject.Parse(capturedResultJson);
                JToken  resourceToken = o.SelectToken("$.resources[?(@.properties.storageProfile.osDisk.image.uri != null)]");
                if (resourceToken == null)
                {
                    throw new Exception("Could not locate image uri under expected section in the capture result -" + capturedResultJson);
                }
                string capturedImageUri = (string)(resourceToken["properties"]["storageProfile"]["osDisk"]["image"]["uri"]);

                Utilities.Log("Creating a Linux VM using captured image - " + capturedImageUri);

                var linuxVM2 = azure.VirtualMachines.Define(linuxVmName2)
                               .WithRegion(Region.USWest)
                               .WithExistingResourceGroup(rgName)
                               .WithNewPrimaryNetwork("10.0.0.0/28")
                               .WithPrimaryPrivateIPAddressDynamic()
                               .WithoutPrimaryPublicIPAddress()
                               .WithStoredLinuxImage(capturedImageUri) // Note: A Generalized Image can also be an uploaded VHD prepared from an on-premise generalized VM.
                               .WithRootUsername(UserName)
                               .WithRootPassword(Password)
                               .WithSize(VirtualMachineSizeTypes.Parse("Standard_D2a_v4"))
                               .Create();

                Utilities.PrintVirtualMachine(linuxVM2);

                var specializedVhd = linuxVM2.OSUnmanagedDiskVhdUri;
                //=============================================================
                // Deleting the virtual machine
                Utilities.Log("Deleting VM: " + linuxVM2.Id);

                azure.VirtualMachines.DeleteById(linuxVM2.Id); // VM required to be deleted to be able to attach it's
                                                               // OS Disk VHD to another VM (Deallocate is not sufficient)

                Utilities.Log("Deleted VM");

                //=============================================================
                // Create a Linux VM using 'specialized VHD' of previous VM

                Utilities.Log("Creating a new Linux VM by attaching OS Disk vhd - "
                              + specializedVhd
                              + " of deleted VM");

                var linuxVM3 = azure.VirtualMachines.Define(linuxVmName3)
                               .WithRegion(Region.USWest)
                               .WithExistingResourceGroup(rgName)
                               .WithNewPrimaryNetwork("10.0.0.0/28")
                               .WithPrimaryPrivateIPAddressDynamic()
                               .WithoutPrimaryPublicIPAddress()
                               .WithSpecializedOSUnmanagedDisk(specializedVhd, OperatingSystemTypes.Linux) // New user credentials cannot be specified
                               .WithSize(VirtualMachineSizeTypes.Parse("Standard_D2a_v4"))                 // when attaching a specialized VHD
                               .Create();

                Utilities.PrintVirtualMachine(linuxVM3);
            }
            finally
            {
                try
                {
                    Utilities.Log("Deleting Resource Group: " + rgName);
                    azure.ResourceGroups.DeleteByName(rgName);
                    Utilities.Log("Deleted Resource Group: " + rgName);
                }
                catch
                {
                    Utilities.Log("Did not create any resources in Azure. No clean up is necessary");
                }
            }
        }
示例#4
0
        /**
         * Azure Compute sample for managing virtual machines -
         *  - Create an un-managed virtual machine from PIR image with data disks
         *  - Deallocate the virtual machine
         *  - Generalize the virtual machine
         *  - Create a virtual machine custom image from OS and Data disk VHDs of virtual machine
         *  - Create a second virtual machine using the custom image
         *  - Create a second virtual machine using the custom image and configure the data disks
         *  - Deletes the custom image
         *  - Get SAS Uri to the virtual machine's managed disks.
         */
        public static void RunSample(IAzure azure)
        {
            var linuxVmName1     = SdkContext.RandomResourceName("VM1", 10);
            var linuxVmName2     = SdkContext.RandomResourceName("VM2", 10);
            var linuxVmName3     = SdkContext.RandomResourceName("VM3", 10);
            var customImageName  = SdkContext.RandomResourceName("img", 10);
            var rgName           = SdkContext.RandomResourceName("rgCOMV", 15);
            var publicIpDnsLabel = SdkContext.RandomResourceName("pip", 10);

            var apacheInstallScript     = "https://raw.githubusercontent.com/Azure/azure-libraries-for-net/master/Samples/Asset/install_apache.sh";
            var apacheInstallCommand    = "bash install_apache.sh";
            var apacheInstallScriptUris = new List <string>();

            apacheInstallScriptUris.Add(apacheInstallScript);

            try
            {
                //=============================================================
                // Create a Linux VM using a PIR image with un-managed OS and data disks and customize virtual
                // machine using custom script extension

                Utilities.Log("Creating a un-managed Linux VM");

                var linuxVM = azure.VirtualMachines.Define(linuxVmName1)
                              .WithRegion(region)
                              .WithNewResourceGroup(rgName)
                              .WithNewPrimaryNetwork("10.0.0.0/28")
                              .WithPrimaryPrivateIPAddressDynamic()
                              .WithNewPrimaryPublicIPAddress(publicIpDnsLabel)
                              .WithPopularLinuxImage(KnownLinuxVirtualMachineImage.UbuntuServer16_04_Lts)
                              .WithRootUsername(userName)
                              .WithRootPassword(password)
                              .WithUnmanagedDisks()
                              .DefineUnmanagedDataDisk("disk-1")
                              .WithNewVhd(100)
                              .WithLun(1)
                              .Attach()
                              .DefineUnmanagedDataDisk("disk-2")
                              .WithNewVhd(50)
                              .WithLun(2)
                              .Attach()
                              .DefineUnmanagedDataDisk("disk-3")
                              .WithNewVhd(60)
                              .WithLun(3)
                              .Attach()
                              .DefineNewExtension("CustomScriptForLinux")
                              .WithPublisher("Microsoft.OSTCExtensions")
                              .WithType("CustomScriptForLinux")
                              .WithVersion("1.4")
                              .WithMinorVersionAutoUpgrade()
                              .WithPublicSetting("fileUris", apacheInstallScriptUris)
                              .WithPublicSetting("commandToExecute", apacheInstallCommand)
                              .Attach()
                              .WithSize(VirtualMachineSizeTypes.Parse("Standard_D2a_v4"))
                              .Create();

                Utilities.Log("Created a Linux VM with un-managed OS and data disks: " + linuxVM.Id);
                Utilities.PrintVirtualMachine(linuxVM);

                // De-provision the virtual machine
                Utilities.DeprovisionAgentInLinuxVM(linuxVM.GetPrimaryPublicIPAddress().Fqdn, 22, userName, password);

                //=============================================================
                // Deallocate the virtual machine
                Utilities.Log("Deallocate VM: " + linuxVM.Id);

                linuxVM.Deallocate();

                Utilities.Log("De-allocated VM: " + linuxVM.Id + "; state = " + linuxVM.PowerState);

                //=============================================================
                // Generalize the virtual machine
                Utilities.Log("Generalize VM: " + linuxVM.Id);

                linuxVM.Generalize();

                Utilities.Log("Generalized VM: " + linuxVM.Id);

                //=============================================================
                // Create a virtual machine custom image from OS and data disks of the virtual machine

                Utilities.Log("Creating virtual machine custom image from un-managed disk VHDs: " + linuxVM.Id);

                var virtualMachineCustomImage = azure.VirtualMachineCustomImages
                                                .Define(customImageName)
                                                .WithRegion(region)
                                                .WithExistingResourceGroup(rgName)
                                                .WithLinuxFromVhd(linuxVM.OSUnmanagedDiskVhdUri, OperatingSystemStateTypes.Generalized)
                                                .DefineDataDiskImage()
                                                .WithLun(linuxVM.UnmanagedDataDisks[1].Lun)
                                                .FromVhd(linuxVM.UnmanagedDataDisks[1].VhdUri)
                                                .Attach()
                                                .DefineDataDiskImage()
                                                .WithLun(linuxVM.UnmanagedDataDisks[2].Lun)
                                                .FromVhd(linuxVM.UnmanagedDataDisks[2].VhdUri)
                                                .Attach()
                                                .DefineDataDiskImage()
                                                .WithLun(linuxVM.UnmanagedDataDisks[3].Lun)
                                                .FromVhd(linuxVM.UnmanagedDataDisks[3].VhdUri)
                                                .WithDiskCaching(CachingTypes.ReadOnly)
                                                .Attach()
                                                .Create();

                Utilities.Log("Created custom image");

                Utilities.PrintVirtualMachineCustomImage(virtualMachineCustomImage);

                //=============================================================
                // Create a Linux VM using custom image

                Utilities.Log("Creating a Linux VM using custom image: " + virtualMachineCustomImage.Id);

                var linuxVM2 = azure.VirtualMachines.Define(linuxVmName2)
                               .WithRegion(region)
                               .WithExistingResourceGroup(rgName)
                               .WithNewPrimaryNetwork("10.0.0.0/28")
                               .WithPrimaryPrivateIPAddressDynamic()
                               .WithoutPrimaryPublicIPAddress()
                               .WithLinuxCustomImage(virtualMachineCustomImage.Id)
                               .WithRootUsername(userName)
                               .WithRootPassword(password)
                               .WithSize(VirtualMachineSizeTypes.Parse("Standard_D2a_v4"))
                               .Create();

                Utilities.Log("Created Linux VM");
                Utilities.PrintVirtualMachine(linuxVM2);

                //=============================================================
                // Create another Linux VM using custom image and configure the data disks from image and
                // add another data disk

                var linuxVM3 = azure.VirtualMachines.Define(linuxVmName3)
                               .WithRegion(region)
                               .WithExistingResourceGroup(rgName)
                               .WithNewPrimaryNetwork("10.0.0.0/28")
                               .WithPrimaryPrivateIPAddressDynamic()
                               .WithoutPrimaryPublicIPAddress()
                               .WithLinuxCustomImage(virtualMachineCustomImage.Id)
                               .WithRootUsername(userName)
                               .WithRootPassword(password)
                               .WithNewDataDiskFromImage(1, 200, CachingTypes.ReadWrite)
                               .WithNewDataDiskFromImage(2, 100, CachingTypes.ReadOnly)
                               .WithNewDataDiskFromImage(3, 100, CachingTypes.ReadWrite)
                               .WithNewDataDisk(50)
                               .WithSize(VirtualMachineSizeTypes.Parse("Standard_D2a_v4"))
                               .Create();

                Utilities.PrintVirtualMachine(linuxVM3);

                // Getting the SAS URIs requires virtual machines to be de-allocated
                // [Access not permitted because'disk' is currently attached to running VM]
                //
                Utilities.Log("De-allocating the virtual machine - " + linuxVM3.Id);

                linuxVM3.Deallocate();

                //=============================================================
                // Get the readonly SAS URI to the OS and data disks

                Utilities.Log("Getting OS and data disks SAS Uris");

                // OS Disk SAS Uri
                var osDisk = azure.Disks.GetById(linuxVM3.OSDiskId);

                var osDiskSasUri = osDisk.GrantAccess(24 * 60);

                Utilities.Log("OS disk SAS Uri: " + osDiskSasUri);

                // Data Disks SAS Uri
                foreach (var disk  in  linuxVM3.DataDisks.Values)
                {
                    var dataDisk       = azure.Disks.GetById(disk.Id);
                    var dataDiskSasUri = dataDisk.GrantAccess(24 * 60);
                    Utilities.Log($"Data disk (lun: {disk.Lun}) SAS Uri: {dataDiskSasUri}");
                }

                //=============================================================
                // Deleting the custom image
                Utilities.Log("Deleting custom Image: " + virtualMachineCustomImage.Id);

                azure.VirtualMachineCustomImages.DeleteById(virtualMachineCustomImage.Id);

                Utilities.Log("Deleted custom image");
            }
            finally
            {
                try
                {
                    Utilities.Log("Deleting Resource Group: " + rgName);
                    azure.ResourceGroups.DeleteByName(rgName);
                    Utilities.Log("Deleted Resource Group: " + rgName);
                }
                catch (NullReferenceException)
                {
                    Utilities.Log("Did not create any resources in Azure. No clean up is necessary");
                }
                catch (Exception g)
                {
                    Utilities.Log(g);
                }
            }
        }
        public static void RunSample(IAzure azure)
        {
            string rgName             = SdkContext.RandomResourceName("rgSTMS", 20);
            string networkName        = SdkContext.RandomResourceName("nw", 20);
            string subnetName         = "subnetA";
            string storageAccountName = SdkContext.RandomResourceName("sa", 15);
            string publicIpName       = SdkContext.RandomResourceName("pip", 20);
            string vmName             = SdkContext.RandomResourceName("vm", 10);

            try
            {
                // ============================================================
                // Create a virtual network and a subnet with storage service subnet access enabled

                Utilities.Log("Creating a Virtual network and subnet with storage service subnet access enabled:");

                INetwork network = azure.Networks.Define(networkName)
                                   .WithRegion(Region.USEast)
                                   .WithNewResourceGroup(rgName)
                                   .WithAddressSpace("10.0.0.0/28")
                                   .DefineSubnet(subnetName)
                                   .WithAddressPrefix("10.0.0.8/29")
                                   .WithAccessFromService(ServiceEndpointType.MicrosoftStorage)
                                   .Attach()
                                   .Create();

                Utilities.Log("Created a Virtual network with subnet:");
                Utilities.PrintVirtualNetwork(network);

                // ============================================================
                // Create a storage account with access to it allowed only from a specific subnet

                var subnetId = $"{network.Id}/subnets/{subnetName}";

                Utilities.Log($"Creating a storage account with access allowed only from the subnet{subnetId}");

                IStorageAccount storageAccount = azure.StorageAccounts.Define(storageAccountName)
                                                 .WithRegion(Region.USEast)
                                                 .WithExistingResourceGroup(rgName)
                                                 .WithAccessFromSelectedNetworks()
                                                 .WithAccessFromNetworkSubnet(subnetId)
                                                 .Create();

                Utilities.Log("Created storage account:");
                Utilities.PrintStorageAccount(storageAccount);


                // ============================================================
                // Create a public IP address

                Utilities.Log("Creating a Public IP address");

                IPublicIPAddress publicIPAddress = azure.PublicIPAddresses
                                                   .Define(publicIpName)
                                                   .WithRegion(Region.USEast)
                                                   .WithExistingResourceGroup(rgName)
                                                   .WithLeafDomainLabel(publicIpName)
                                                   .Create();

                Utilities.Log("Created Public IP address:");
                Utilities.PrintIPAddress(publicIPAddress);

                // ============================================================
                // Create a virtual machine and associate the public IP address

                Utilities.Log("Creating a VM with the Public IP address");

                IVirtualMachine linuxVM = azure.VirtualMachines
                                          .Define(vmName)
                                          .WithRegion(Region.USEast)
                                          .WithExistingResourceGroup(rgName)
                                          .WithNewPrimaryNetwork("10.1.0.0/28")
                                          .WithPrimaryPrivateIPAddressDynamic()
                                          .WithExistingPrimaryPublicIPAddress(publicIPAddress)
                                          .WithPopularLinuxImage(KnownLinuxVirtualMachineImage.UbuntuServer16_04_Lts)
                                          .WithRootUsername("tirekicker")
                                          .WithRootPassword("12NewPA$$w0rd!")
                                          .WithSize(VirtualMachineSizeTypes.Parse("Standard_D2a_v4"))
                                          .Create();

                Utilities.Log($"Created the VM: {linuxVM.Id}");
                Utilities.PrintVirtualMachine(linuxVM);

                publicIPAddress.Refresh();  // Refresh public IP resource to populate the assigned IPv4 address

                // ============================================================
                // Update the storage account so that it can also be accessed from the PublicIP address

                Utilities.Log($"Updating storage account with access also allowed from publicIP{publicIPAddress.IPAddress}");

                storageAccount.Update()
                .WithAccessFromIpAddress(publicIPAddress.IPAddress)
                .Apply();

                Utilities.Log("Updated storage account:");
                Utilities.PrintStorageAccount(storageAccount);

                // ============================================================
                //  Update the storage account to restrict incoming traffic to HTTPS

                Utilities.Log("Restricting access to storage account only via HTTPS");

                storageAccount.Update()
                .WithOnlyHttpsTraffic()
                .Apply();

                Utilities.Log("Updated the storage account:");
                Utilities.PrintStorageAccount(storageAccount);
            }
            finally
            {
                if (azure.ResourceGroups.GetByName(rgName) != null)
                {
                    Utilities.Log("Deleting Resource Group: " + rgName);
                    azure.ResourceGroups.DeleteByName(rgName);
                    Utilities.Log("Deleted Resource Group: " + rgName);
                }
                else
                {
                    Utilities.Log("Did not create any resources in Azure. No clean up is necessary");
                }
            }
        }
        public void CanHandleExtensionReference()
        {
            using (var context = FluentMockContext.Start(GetType().FullName))
            {
                string rgName   = TestUtilities.GenerateName("vmexttest");
                string location = "eastus";
                string vmName   = "javavm";

                var azure = TestHelper.CreateRollupClient();

                // Create a Linux VM
                //
                try
                {
                    var vm = azure.VirtualMachines
                             .Define(vmName)
                             .WithRegion(location)
                             .WithNewResourceGroup(rgName)
                             .WithNewPrimaryNetwork("10.0.0.0/28")
                             .WithPrimaryPrivateIPAddressDynamic()
                             .WithoutPrimaryPublicIPAddress()
                             .WithPopularLinuxImage(KnownLinuxVirtualMachineImage.UbuntuServer14_04_Lts)
                             .WithRootUsername("Foo12")
                             .WithRootPassword("BaR@12abc!")
                             .WithSize(VirtualMachineSizeTypes.Parse("Standard_D2a_v4"))
                             .DefineNewExtension("VMAccessForLinux")
                             .WithPublisher("Microsoft.OSTCExtensions")
                             .WithType("VMAccessForLinux")
                             .WithVersion("1.4")
                             .WithProtectedSetting("username", "Foo12")
                             .WithProtectedSetting("password", "B12a6@12xyz!")
                             .WithProtectedSetting("reset_ssh", "true")
                             .Attach()
                             .Create();

                    Assert.True(vm.ListExtensions().Count() > 0);

                    // Get the created virtual machine via VM List not by VM GET
                    var virtualMachines = azure.VirtualMachines
                                          .ListByResourceGroup(rgName);
                    IVirtualMachine vmWithExtensionReference = null;
                    foreach (var virtualMachine in virtualMachines)
                    {
                        if (virtualMachine.Name.Equals(vmName, StringComparison.OrdinalIgnoreCase))
                        {
                            vmWithExtensionReference = virtualMachine;
                            break;
                        }
                    }
                    // The VM retrieved from the list will contain extensions as reference (i.e. with only id)
                    Assert.NotNull(vmWithExtensionReference);

                    // Update the extension
                    var vmWithExtensionUpdated = vmWithExtensionReference.Update()
                                                 .UpdateExtension("VMAccessForLinux")
                                                 .WithProtectedSetting("username", "Foo12")
                                                 .WithProtectedSetting("password", "muy!234OR")
                                                 .WithProtectedSetting("reset_ssh", "true")
                                                 .Parent()
                                                 .Apply();

                    // Again getting VM with extension reference
                    virtualMachines = azure.VirtualMachines
                                      .ListByResourceGroup(rgName);
                    vmWithExtensionReference = null;
                    foreach (var virtualMachine in virtualMachines)
                    {
                        vmWithExtensionReference = virtualMachine;
                    }

                    Assert.NotNull(vmWithExtensionReference);

                    IVirtualMachineExtension accessExtension = null;
                    foreach (var extension in vmWithExtensionReference.ListExtensions().Values)
                    {
                        if (extension.Name.Equals("VMAccessForLinux", StringComparison.OrdinalIgnoreCase))
                        {
                            accessExtension = extension;
                            break;
                        }
                    }

                    // Even though VM's inner contain just extension reference VirtualMachine::extensions()
                    // should resolve the reference and get full extension.
                    Assert.NotNull(accessExtension);
                    Assert.NotNull(accessExtension.PublisherName);
                    Assert.NotNull(accessExtension.TypeName);
                    Assert.NotNull(accessExtension.VersionName);
                }
                finally
                {
                    try
                    {
                        azure.ResourceGroups.DeleteByName(rgName);
                    }
                    catch { }
                }
            }
        }
示例#7
0
        /**
         * Azure Compute sample for managing virtual machines -
         *  - Create a virtual machine with
         *      - Implicit data disks
         *      - Creatable data disks
         *      - Existing data disks
         *  - Update a virtual machine
         *      - Attach data disks
         *      - Detach data disks
         *  - Stop a virtual machine
         *  - Update a virtual machine
         *      - Expand the OS disk
         *      - Expand data disks.
         */
        public static void RunSample(IAzure azure)
        {
            var linuxVmName1     = Utilities.CreateRandomName("VM1");
            var rgName           = Utilities.CreateRandomName("rgCOMV");
            var publicIpDnsLabel = Utilities.CreateRandomName("pip");

            try
            {
                // Creates an empty data disk to attach to the virtual machine
                //
                Utilities.Log("Creating an empty managed disk");

                var dataDisk1 = azure.Disks.Define(Utilities.CreateRandomName("dsk-"))
                                .WithRegion(region)
                                .WithNewResourceGroup(rgName)
                                .WithData()
                                .WithSizeInGB(50)
                                .Create();

                Utilities.Log("Created managed disk");

                // Prepare first creatable data disk
                //
                var dataDiskCreatable1 = azure.Disks.Define(Utilities.CreateRandomName("dsk-"))
                                         .WithRegion(region)
                                         .WithExistingResourceGroup(rgName)
                                         .WithData()
                                         .WithSizeInGB(100);

                // Prepare second creatable data disk
                //
                var dataDiskCreatable2 = azure.Disks.Define(Utilities.CreateRandomName("dsk-"))
                                         .WithRegion(region)
                                         .WithExistingResourceGroup(rgName)
                                         .WithData()
                                         .WithSizeInGB(50)
                                         .WithSku(DiskSkuTypes.StandardLRS);

                //======================================================================
                // Create a Linux VM using a PIR image with managed OS and Data disks

                Utilities.Log("Creating a managed Linux VM");

                var linuxVM = azure.VirtualMachines.Define(linuxVmName1)
                              .WithRegion(region)
                              .WithNewResourceGroup(rgName)
                              .WithNewPrimaryNetwork("10.0.0.0/28")
                              .WithPrimaryPrivateIPAddressDynamic()
                              .WithNewPrimaryPublicIPAddress(publicIpDnsLabel)
                              .WithPopularLinuxImage(KnownLinuxVirtualMachineImage.UbuntuServer16_04_Lts)
                              .WithRootUsername(userName)
                              .WithRootPassword(password)

                              // Begin: Managed data disks
                              .WithNewDataDisk(100)
                              .WithNewDataDisk(100, 1, CachingTypes.ReadWrite)
                              .WithNewDataDisk(dataDiskCreatable1)
                              .WithNewDataDisk(dataDiskCreatable2, 2, CachingTypes.ReadOnly)
                              .WithExistingDataDisk(dataDisk1)

                              // End: Managed data disks
                              .WithSize(VirtualMachineSizeTypes.Parse("Standard_D2a_v4"))
                              .Create();

                Utilities.Log("Created a Linux VM with managed OS and data disks: " + linuxVM.Id);
                Utilities.PrintVirtualMachine(linuxVM);

                //======================================================================
                // Update the virtual machine by detaching two data disks with lun 3 and 4 and adding one

                Utilities.Log("Updating Linux VM");

                var lun3DiskId = linuxVM.DataDisks[3].Id;

                linuxVM.Update()
                .WithoutDataDisk(3)
                .WithoutDataDisk(4)
                .WithNewDataDisk(200)
                .Apply();

                Utilities.Log("Updated Linux VM: " + linuxVM.Id);
                Utilities.PrintVirtualMachine(linuxVM);

                // ======================================================================
                // Delete a managed disk

                var disk = azure.Disks.GetById(lun3DiskId);
                Utilities.Log("Delete managed disk: " + disk.Id);

                azure.Disks.DeleteByResourceGroup(disk.ResourceGroupName, disk.Name);

                Utilities.Log("Deleted managed disk");

                //======================================================================
                // Deallocate the virtual machine

                Utilities.Log("De-allocate Linux VM");

                linuxVM.Deallocate();

                Utilities.Log("De-allocated Linux VM");

                //======================================================================
                // Resize the OS and Data Disks

                var osDisk    = azure.Disks.GetById(linuxVM.OSDiskId);
                var dataDisks = new List <IDisk>();
                foreach (var vmDataDisk  in  linuxVM.DataDisks.Values)
                {
                    var dataDisk = azure.Disks.GetById(vmDataDisk.Id);
                    dataDisks.Add(dataDisk);
                }

                Utilities.Log("Update OS disk: " + osDisk.Id);

                osDisk.Update()
                .WithSizeInGB(2 * osDisk.SizeInGB)
                .Apply();

                Utilities.Log("OS disk updated");

                foreach (var dataDisk in dataDisks)
                {
                    Utilities.Log("Update data disk: " + dataDisk.Id);

                    dataDisk.Update()
                    .WithSizeInGB(dataDisk.SizeInGB + 10)
                    .Apply();

                    Utilities.Log("Data disk updated");
                }

                //======================================================================
                // Starting the virtual machine

                Utilities.Log("Starting Linux VM");

                linuxVM.Start();

                Utilities.Log("Started Linux VM");
                Utilities.PrintVirtualMachine(linuxVM);
            }
            finally
            {
                try
                {
                    Utilities.Log("Deleting Resource Group: " + rgName);
                    azure.ResourceGroups.DeleteByName(rgName);
                    Utilities.Log("Deleted Resource Group: " + rgName);
                }
                catch (NullReferenceException)
                {
                    Utilities.Log("Did not create any resources in Azure. No clean up is necessary");
                }
                catch (Exception g)
                {
                    Utilities.Log(g);
                }
            }
        }
        public void CanCreateUpdateVirtualMachineWithEmptyManagedDataDisks()
        {
            using (var context = FluentMockContext.Start(GetType().FullName))
            {
                var publicIPDnsLabel = SdkContext.RandomResourceName("pip", 20);
                var uname            = "juser";
                var password         = "******";
                // Create with implicit + explicit empty disks, check default and override
                //
                var vmName1 = "myvm1";
                var explicitlyCreatedEmptyDiskName1 = SdkContext.RandomResourceName(vmName1 + "_mdisk_", 25);
                var explicitlyCreatedEmptyDiskName2 = SdkContext.RandomResourceName(vmName1 + "_mdisk_", 25);
                var explicitlyCreatedEmptyDiskName3 = SdkContext.RandomResourceName(vmName1 + "_mdisk_", 25);
                var resourceManager = TestHelper.CreateRollupClient();
                var computeManager  = TestHelper.CreateComputeManager();
                var rgName          = TestUtilities.GenerateName("rgfluentchash-");

                try
                {
                    var resourceGroup = resourceManager.ResourceGroups
                                        .Define(rgName)
                                        .WithRegion(Location)
                                        .Create();

                    var creatableEmptyDisk1 = computeManager.Disks
                                              .Define(explicitlyCreatedEmptyDiskName1)
                                              .WithRegion(Location)
                                              .WithExistingResourceGroup(resourceGroup)
                                              .WithData()
                                              .WithSizeInGB(150);

                    var creatableEmptyDisk2 = computeManager.Disks
                                              .Define(explicitlyCreatedEmptyDiskName2)
                                              .WithRegion(Location)
                                              .WithExistingResourceGroup(resourceGroup)
                                              .WithData()
                                              .WithSizeInGB(150);

                    var creatableEmptyDisk3 = computeManager.Disks
                                              .Define(explicitlyCreatedEmptyDiskName3)
                                              .WithRegion(Location)
                                              .WithExistingResourceGroup(resourceGroup)
                                              .WithData()
                                              .WithSizeInGB(150);

                    var virtualMachine = computeManager.VirtualMachines
                                         .Define(vmName1)
                                         .WithRegion(Location)
                                         .WithExistingResourceGroup(resourceGroup)
                                         .WithNewPrimaryNetwork("10.0.0.0/28")
                                         .WithPrimaryPrivateIPAddressDynamic()
                                         .WithNewPrimaryPublicIPAddress(publicIPDnsLabel)
                                         .WithPopularLinuxImage(LinuxImage)
                                         .WithRootUsername(uname)
                                         .WithRootPassword(password)
                                                                                                     // Start: Add 5 empty managed disks
                                         .WithNewDataDisk(100)                                       // CreateOption: EMPTY
                                         .WithNewDataDisk(100, 1, CachingTypes.ReadOnly)             // CreateOption: EMPTY
                                         .WithNewDataDisk(creatableEmptyDisk1)                       // CreateOption: ATTACH
                                         .WithNewDataDisk(creatableEmptyDisk2, 2, CachingTypes.None) // CreateOption: ATTACH
                                         .WithNewDataDisk(creatableEmptyDisk3, 3, CachingTypes.None) // CreateOption: ATTACH
                                                                                                     // End : Add 5 empty managed disks
                                         .WithSize(VirtualMachineSizeTypes.Parse("Standard_D2a_v4"))
                                         .WithOSDiskCaching(CachingTypes.ReadWrite)
                                         .Create();

                    Assert.True(virtualMachine.IsManagedDiskEnabled);
                    // There should not be any un-managed data disks
                    //
                    Assert.NotNull(virtualMachine.UnmanagedDataDisks);
                    Assert.Equal(0, virtualMachine.UnmanagedDataDisks.Count);
                    // Validate the managed data disks
                    //
                    var dataDisks = virtualMachine.DataDisks;
                    Assert.NotNull(dataDisks);
                    Assert.True(dataDisks.Count == 5);
                    Assert.True(dataDisks.ContainsKey(1));
                    var dataDiskLun1 = dataDisks[1];
                    Assert.NotNull(dataDiskLun1.Id);
                    Assert.Equal(CachingTypes.ReadOnly, dataDiskLun1.CachingType);
                    Assert.Equal(100, dataDiskLun1.Size);

                    Assert.True(dataDisks.ContainsKey(2));
                    var dataDiskLun2 = dataDisks[2];
                    Assert.NotNull(dataDiskLun2.Id);
                    Assert.Equal(CachingTypes.None, dataDiskLun2.CachingType);
                    Assert.Equal(150, dataDiskLun2.Size);

                    Assert.True(dataDisks.ContainsKey(3));
                    var dataDiskLun3 = dataDisks[3];
                    Assert.NotNull(dataDiskLun3.Id);
                    Assert.Equal(CachingTypes.None, dataDiskLun3.CachingType);
                    Assert.Equal(150, dataDiskLun3.Size);
                    // Validate the defaults assigned
                    //
                    foreach (var dataDisk in dataDisks.Values)
                    {
                        if (dataDisk.Lun != 1 && dataDisk.Lun != 2 && dataDisk.Lun != 3)
                        {
                            Assert.Equal(CachingTypes.ReadWrite, dataDisk.CachingType);
                            Assert.Equal(StorageAccountTypes.StandardLRS, dataDisk.StorageAccountType);
                        }
                    }

                    // Updating and adding disk as part of VM Update seems consistency failing, CRP is aware of
                    // this, hence until it is fixed comment-out the test
                    //
                    //        {
                    //            "startTime": "2017-01-26T05:48:59.9290573+00:00",
                    //                "endTime": "2017-01-26T05:49:02.2884052+00:00",
                    //                "status": "Failed",
                    //                "error": {
                    //            "code": "InternalExecutionError",
                    //                    "message": "An internal execution error occurred."
                    //        },
                    //            "name": "bc8072a7-38bb-445b-ae59-f16cf125342c"
                    //        }
                    //
                    //        virtualMachine.Deallocate();
                    //
                    //        virtualMachine.Update()
                    //                .WithDataDiskUpdated(1, 200)
                    //                .WithDataDiskUpdated(2, 200, CachingTypes.ReadWrite)
                    //                .WithNewDataDisk(60)
                    //                .Apply();
                    //
                    //        Assert.True(virtualMachine.IsManagedDiskEnabled());
                    //        // There should not be any un-managed data disks
                    //        //
                    //        Assert.NotNull(virtualMachine.UnmanagedDataDisks());
                    //        Assert.Equal(virtualMachine.UnmanagedDataDisks().Count, 0);
                    //
                    //        // Validate the managed data disks
                    //        //
                    //         dataDisks = virtualMachine.DataDisks;
                    //        Assert.NotNull(dataDisks);
                    //        Assert.True(dataDisks.Count == 6);
                    //        Assert.True(dataDisks.ContainsKey(1));
                    //        dataDiskLun1 = dataDisks[1];
                    //        Assert.NotNull(dataDiskLun1.Id);
                    //        Assert.Equal(dataDiskLun1.CachingType(), CachingTypes.ReadOnly);
                    //        Assert.Equal(dataDiskLun1.Count, 200);  // 100 -> 200
                    //
                    //        Assert.True(dataDisks.ContainsKey(2));
                    //        dataDiskLun2 = dataDisks[2];
                    //        Assert.NotNull(dataDiskLun2.Id);
                    //        Assert.Equal(dataDiskLun2.CachingType(), CachingTypes.ReadWrite); // None -> ReadWrite
                    //        Assert.Equal(dataDiskLun2.Count, 200);  // 150 -> 200
                    //
                    //        Assert.True(dataDisks.ContainsKey(3));
                    //        dataDiskLun3 = dataDisks[3];
                    //        Assert.NotNull(dataDiskLun3.Id);
                    //        Assert.Equal(dataDiskLun3.CachingType(), CachingTypes.None);
                    //        Assert.Equal(dataDiskLun3.Count, 150);
                    //
                    //        // Ensure defaults of other disks are not affected
                    //        foreach (VirtualMachineDataDisk dataDisk  in  dataDisks.Values()) {
                    //            if (dataDisk.Lun != 1 && dataDisk.Lun != 3) {
                    //                Assert.Equal(dataDisk.CachingType(), CachingTypes.ReadWrite);
                    //                Assert.Equal(dataDisk.StorageAccountType(), StorageAccountTypes.STANDARD_LRS);
                    //            }
                    //        }
                }
                finally
                {
                    try
                    {
                        resourceManager.ResourceGroups.DeleteByName(rgName);
                    }
                    catch { }
                }
            }
        }
示例#9
0
        /**
         * Azure Compute sample for managing virtual machines -
         *  - Create a virtual machine with managed OS Disk based on Windows OS image
         *  - Once Network is created start creation of virtual machine based on Linux OS image in the same network
         *  - Update both virtual machines
         *    - for Linux based:
         *      - add Tag
         *    - for Windows based:
         *      - deallocate the virtual machine
         *      - add a data disk
         *      - start the virtual machine
         *  - List virtual machines and print details
         *  - Delete all virtual machines.
         */
        public async static Task RunSampleAsync(IAzure azure)
        {
            var region        = Region.USWestCentral;
            var windowsVmName = Utilities.CreateRandomName("wVM");
            var linuxVmName   = Utilities.CreateRandomName("lVM");
            var rgName        = Utilities.CreateRandomName("rgCOMV");
            var userName      = Utilities.CreateUsername();
            var password      = Utilities.CreatePassword();

            try
            {
                //=============================================================
                // Create a Windows virtual machine

                // Prepare a creatable data disk for VM
                //
                var dataDiskCreatable = azure.Disks.Define(Utilities.CreateRandomName("dsk-"))
                                        .WithRegion(region)
                                        .WithExistingResourceGroup(rgName)
                                        .WithData()
                                        .WithSizeInGB(100);

                // Create a data disk to attach to VM
                //
                var dataDisk = await azure.Disks.Define(Utilities.CreateRandomName("dsk-"))
                               .WithRegion(region)
                               .WithNewResourceGroup(rgName)
                               .WithData()
                               .WithSizeInGB(50)
                               .CreateAsync();

                Utilities.Log("Creating a Windows VM");

                var t1 = new DateTime();

                var windowsVM = await azure.VirtualMachines.Define(windowsVmName)
                                .WithRegion(region)
                                .WithNewResourceGroup(rgName)
                                .WithNewPrimaryNetwork("10.0.0.0/28")
                                .WithPrimaryPrivateIPAddressDynamic()
                                .WithoutPrimaryPublicIPAddress()
                                .WithPopularWindowsImage(KnownWindowsVirtualMachineImage.WindowsServer2012R2Datacenter)
                                .WithAdminUsername(userName)
                                .WithAdminPassword(password)
                                .WithNewDataDisk(10)
                                .WithNewDataDisk(dataDiskCreatable)
                                .WithExistingDataDisk(dataDisk)
                                .WithSize(VirtualMachineSizeTypes.Parse("Standard_D2a_v4"))
                                .CreateAsync();

                var t2 = new DateTime();
                Utilities.Log($"Created VM: (took {(t2 - t1).TotalSeconds} seconds) " + windowsVM.Id);
                // Print virtual machine details
                Utilities.PrintVirtualMachine(windowsVM);

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

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

                Utilities.Log("Creating a Linux VM in the network");

                var linuxVM = await azure.VirtualMachines.Define(linuxVmName)
                              .WithRegion(region)
                              .WithExistingResourceGroup(rgName)
                              .WithExistingPrimaryNetwork(network)
                              .WithSubnet("subnet1") // Referencing the default subnet name when no name specified at creation
                              .WithPrimaryPrivateIPAddressDynamic()
                              .WithoutPrimaryPublicIPAddress()
                              .WithPopularLinuxImage(KnownLinuxVirtualMachineImage.UbuntuServer16_04_Lts)
                              .WithRootUsername(userName)
                              .WithRootPassword(password)
                              .WithSize(VirtualMachineSizeTypes.Parse("Standard_D2a_v4"))
                              .CreateAsync();

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

                //=============================================================
                // Update - Tag the virtual machine

                await linuxVM.Update()
                .WithTag("who-rocks-on-linux", "java")
                .WithTag("where", "on azure")
                .ApplyAsync();

                Utilities.Log("Tagged Linux VM: " + linuxVM.Id);

                //=============================================================
                // Update - Add a data disk on Windows VM.

                await windowsVM.Update()
                .WithNewDataDisk(200)
                .ApplyAsync();

                Utilities.Log("Expanded VM " + windowsVM.Id + "'s OS and data disks");
                Utilities.PrintVirtualMachine(windowsVM);

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

                var resourceGroupName = windowsVM.ResourceGroupName;

                Utilities.Log("Printing list of VMs =======");

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

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

                await azure.VirtualMachines.DeleteByIdAsync(windowsVM.Id);

                Utilities.Log("Deleted VM: " + windowsVM.Id);
            }
            finally
            {
                try
                {
                    Utilities.Log("Deleting Resource Group: " + rgName);
                    await azure.ResourceGroups.DeleteByNameAsync(rgName);

                    Utilities.Log("Deleted Resource Group: " + rgName);
                }
                catch (NullReferenceException)
                {
                    Utilities.Log("Did not create any resources in Azure. No clean up is necessary");
                }
                catch (Exception g)
                {
                    Utilities.Log(g);
                }
            }
        }
        public void CanUpdateVirtualMachineByReimagingDisks()
        {
            using (var context = FluentMockContext.Start(GetType().FullName))
            {
                var publicIPDnsLabel = SdkContext.RandomResourceName("pip", 20);
                var uname            = "juser";
                var password         = "******";
                // Create with implicit + explicit empty disks, check default and override
                //
                var vmName1 = "myvm1";
                var explicitlyCreatedEmptyDiskName1 = SdkContext.RandomResourceName(vmName1 + "_mdisk_", 25);
                var explicitlyCreatedEmptyDiskName2 = SdkContext.RandomResourceName(vmName1 + "_mdisk_", 25);
                var explicitlyCreatedEmptyDiskName3 = SdkContext.RandomResourceName(vmName1 + "_mdisk_", 25);
                var resourceManager = TestHelper.CreateRollupClient();
                var computeManager  = TestHelper.CreateComputeManager();
                var rgName          = TestUtilities.GenerateName("rgfluentchash-");

                try
                {
                    var resourceGroup = resourceManager.ResourceGroups
                                        .Define(rgName)
                                        .WithRegion(Location)
                                        .Create();

                    var creatableEmptyDisk1 = computeManager.Disks
                                              .Define(explicitlyCreatedEmptyDiskName1)
                                              .WithRegion(Location)
                                              .WithExistingResourceGroup(resourceGroup)
                                              .WithData()
                                              .WithSizeInGB(1);

                    var creatableEmptyDisk2 = computeManager.Disks
                                              .Define(explicitlyCreatedEmptyDiskName2)
                                              .WithRegion(Location)
                                              .WithExistingResourceGroup(resourceGroup)
                                              .WithData()
                                              .WithSizeInGB(1);

                    var creatableEmptyDisk3 = computeManager.Disks
                                              .Define(explicitlyCreatedEmptyDiskName3)
                                              .WithRegion(Location)
                                              .WithExistingResourceGroup(resourceGroup)
                                              .WithData()
                                              .WithSizeInGB(1);

                    var virtualMachine1 = computeManager.VirtualMachines
                                          .Define(vmName1)
                                          .WithRegion(Location)
                                          .WithExistingResourceGroup(resourceGroup)
                                          .WithNewPrimaryNetwork("10.0.0.0/28")
                                          .WithPrimaryPrivateIPAddressDynamic()
                                          .WithNewPrimaryPublicIPAddress(publicIPDnsLabel)
                                          .WithPopularWindowsImage(KnownWindowsVirtualMachineImage.WindowsServer2008R2_SP1)
                                          .WithAdminUsername(uname)
                                          .WithAdminPassword(password)
                                          // Start: Add bunch of empty managed disks
                                          .WithNewDataDisk(1)
                                          .WithNewDataDisk(1, 1, CachingTypes.ReadOnly)
                                          .WithNewDataDisk(creatableEmptyDisk1)
                                          .WithNewDataDisk(creatableEmptyDisk2, 2, CachingTypes.ReadOnly)
                                          .WithDataDiskDefaultCachingType(CachingTypes.ReadOnly)
                                          .WithDataDiskDefaultStorageAccountType(StorageAccountTypes.StandardLRS)
                                          .WithSize(VirtualMachineSizeTypes.Parse("Standard_D2a_v4"))
                                          .WithOSDiskCaching(CachingTypes.ReadOnly)
                                          .WithEphemeralOSDisk(DiffDiskOptions.Local)
                                          .Create();

                    virtualMachine1.Update()
                    .WithoutDataDisk(1)
                    .WithNewDataDisk(1, 6, CachingTypes.ReadOnly)                         // CreateOption: EMPTY
                    .Apply();

                    Assert.NotNull(virtualMachine1.DataDisks);
                    Assert.Equal(4, virtualMachine1.DataDisks.Count); // Removed one added another
                    Assert.True(virtualMachine1.DataDisks.ContainsKey(6));
                    Assert.False(virtualMachine1.DataDisks.ContainsKey(1));

                    virtualMachine1.Reimage();
                    virtualMachine1.Refresh();

                    Assert.NotNull(virtualMachine1.DataDisks);
                    Assert.Equal(4, virtualMachine1.DataDisks.Count); // Removed one added another
                    Assert.True(virtualMachine1.DataDisks.ContainsKey(6));
                    Assert.False(virtualMachine1.DataDisks.ContainsKey(1));
                }
                finally
                {
                    try
                    {
                        resourceManager.ResourceGroups.DeleteByName(rgName);
                    }
                    catch { }
                }
            }
        }
        public void CanCreateVirtualMachineByAttachingManagedOsDisk()
        {
            using (var context = FluentMockContext.Start(GetType().FullName))
            {
                var uname              = "juser";
                var password           = "******";
                var vmName             = "myvm6";
                var resourceManager    = TestHelper.CreateRollupClient();
                var computeManager     = TestHelper.CreateComputeManager();
                var rgName             = TestUtilities.GenerateName("rgfluentchash-");
                var storageAccountName = SdkContext.RandomResourceName("stg", 17);
                try
                {
                    // Creates a native virtual machine
                    //
                    var nativeVM = computeManager.VirtualMachines
                                   .Define(vmName)
                                   .WithRegion(Location)
                                   .WithNewResourceGroup(rgName)
                                   .WithNewPrimaryNetwork("10.0.0.0/28")
                                   .WithPrimaryPrivateIPAddressDynamic()
                                   .WithoutPrimaryPublicIPAddress()
                                   .WithLatestLinuxImage("Canonical", "UbuntuServer", "14.04.2-LTS")
                                   .WithRootUsername(uname)
                                   .WithRootPassword(password)
                                   .WithUnmanagedDisks()           /* UN-MANAGED OS and DATA DISKS */
                                   .WithSize(VirtualMachineSizeTypes.Parse("Standard_D2a_v4"))
                                   .WithNewStorageAccount(storageAccountName)
                                   .WithOSDiskCaching(CachingTypes.ReadWrite)
                                   .Create();

                    Assert.False(nativeVM.IsManagedDiskEnabled);
                    var osVhdUri = nativeVM.OSUnmanagedDiskVhdUri;
                    Assert.NotNull(osVhdUri);

                    computeManager.VirtualMachines.DeleteById(nativeVM.Id);

                    var diskName = SdkContext.RandomResourceName("dsk-", 15);
                    var osDisk   = computeManager.Disks.Define(diskName)
                                   .WithRegion(Location)
                                   .WithExistingResourceGroup(rgName)
                                   .WithLinuxFromVhd(osVhdUri)
                                   .WithStorageAccountName(storageAccountName)
                                   .Create();

                    // Creates a managed virtual machine
                    //
                    var managedVM = computeManager.VirtualMachines
                                    .Define(vmName)
                                    .WithRegion(Location)
                                    .WithExistingResourceGroup(rgName)
                                    .WithNewPrimaryNetwork("10.0.0.0/28")
                                    .WithPrimaryPrivateIPAddressDynamic()
                                    .WithoutPrimaryPublicIPAddress()
                                    .WithSpecializedOSDisk(osDisk, OperatingSystemTypes.Linux)
                                    .WithSize(VirtualMachineSizeTypes.Parse("Standard_D2a_v4"))
                                    .WithOSDiskCaching(CachingTypes.ReadWrite)
                                    .Create();

                    Assert.True(managedVM.IsManagedDiskEnabled);
                    Assert.Equal(managedVM.OSDiskId, osDisk.Id, ignoreCase: true);
                }
                finally
                {
                    try
                    {
                        resourceManager.ResourceGroups.DeleteByName(rgName);
                    }
                    catch { }
                }
            }
        }
        public void CanCreateVirtualMachineFromCustomImageWithManagedDisks()
        {
            using (var context = FluentMockContext.Start(GetType().FullName))
            {
                var publicIPDnsLabel = SdkContext.RandomResourceName("pip", 20);
                var uname            = "juser";
                var password         = "******";
                // Create with implicit + explicit empty disks, check default and override
                //
                var vmName1 = "myvm1";
                var explicitlyCreatedEmptyDiskName1 = SdkContext.RandomResourceName(vmName1 + "_mdisk_", 25);
                var explicitlyCreatedEmptyDiskName2 = SdkContext.RandomResourceName(vmName1 + "_mdisk_", 25);
                var explicitlyCreatedEmptyDiskName3 = SdkContext.RandomResourceName(vmName1 + "_mdisk_", 25);
                var resourceManager = TestHelper.CreateRollupClient();
                var computeManager  = TestHelper.CreateComputeManager();
                var rgName          = TestUtilities.GenerateName("rgfluentchash-");

                try
                {
                    var resourceGroup = resourceManager.ResourceGroups
                                        .Define(rgName)
                                        .WithRegion(Location)
                                        .Create();

                    var creatableEmptyDisk1 = computeManager.Disks
                                              .Define(explicitlyCreatedEmptyDiskName1)
                                              .WithRegion(Location)
                                              .WithExistingResourceGroup(resourceGroup)
                                              .WithData()
                                              .WithSizeInGB(150);

                    var creatableEmptyDisk2 = computeManager.Disks
                                              .Define(explicitlyCreatedEmptyDiskName2)
                                              .WithRegion(Location)
                                              .WithExistingResourceGroup(resourceGroup)
                                              .WithData()
                                              .WithSizeInGB(150);

                    var creatableEmptyDisk3 = computeManager.Disks
                                              .Define(explicitlyCreatedEmptyDiskName3)
                                              .WithRegion(Location)
                                              .WithExistingResourceGroup(resourceGroup)
                                              .WithData()
                                              .WithSizeInGB(150);

                    var virtualMachine1 = computeManager.VirtualMachines
                                          .Define(vmName1)
                                          .WithRegion(Location)
                                          .WithExistingResourceGroup(resourceGroup)
                                          .WithNewPrimaryNetwork("10.0.0.0/28")
                                          .WithPrimaryPrivateIPAddressDynamic()
                                          .WithNewPrimaryPublicIPAddress(publicIPDnsLabel)
                                          .WithPopularLinuxImage(LinuxImage)
                                          .WithRootUsername(uname)
                                          .WithRootPassword(password)
                                                                                                      // Start: Add bunch of empty managed disks
                                          .WithNewDataDisk(100)                                       // CreateOption: EMPTY
                                          .WithNewDataDisk(100, 1, CachingTypes.ReadOnly)             // CreateOption: EMPTY
                                          .WithNewDataDisk(creatableEmptyDisk1)                       // CreateOption: ATTACH
                                          .WithNewDataDisk(creatableEmptyDisk2, 2, CachingTypes.None) // CreateOption: ATTACH
                                          .WithNewDataDisk(creatableEmptyDisk3, 3, CachingTypes.None) // CreateOption: ATTACH
                                                                                                      // End : Add bunch of empty managed disks
                                          .WithSize(VirtualMachineSizeTypes.Parse("Standard_D2a_v4"))
                                          .WithOSDiskCaching(CachingTypes.ReadWrite)
                                          .Create();
                    TestHelper.Delay(60 * 1000); // Wait for some time to ensure vm is publicly accessible
                    TestHelper.DeprovisionAgentInLinuxVM(virtualMachine1.GetPrimaryPublicIPAddress().Fqdn,
                                                         22,
                                                         uname,
                                                         password);

                    virtualMachine1.Deallocate();
                    virtualMachine1.Generalize();

                    var customImageName = SdkContext.RandomResourceName("img-", 10);
                    var customImage     = computeManager.VirtualMachineCustomImages.Define(customImageName)
                                          .WithRegion(Location)
                                          .WithExistingResourceGroup(resourceGroup)
                                          .FromVirtualMachine(virtualMachine1)
                                          .Create();
                    Assert.NotNull(customImage);
                    Assert.NotNull(customImage.SourceVirtualMachineId);
                    Assert.Equal(customImage.SourceVirtualMachineId, virtualMachine1.Id, ignoreCase: true);
                    Assert.NotNull(customImage.OSDiskImage);
                    Assert.Equal(OperatingSystemStateTypes.Generalized, customImage.OSDiskImage.OsState);
                    Assert.Equal(OperatingSystemTypes.Linux, customImage.OSDiskImage.OsType);
                    Assert.NotNull(customImage.DataDiskImages);
                    Assert.Equal(5, customImage.DataDiskImages.Count);
                    foreach (ImageDataDisk imageDataDisk in customImage.DataDiskImages.Values)
                    {
                        Assert.Null(imageDataDisk.BlobUri);
                        Assert.NotNull(imageDataDisk.ManagedDisk.Id);
                    }

                    // Create virtual machine from the custom image
                    // This one relies on CRP's capability to create implicit data disks from the virtual machine
                    // image data disk images.
                    //
                    var vmName2         = "myvm2";
                    var virtualMachine2 = computeManager.VirtualMachines
                                          .Define(vmName2)
                                          .WithRegion(Location)
                                          .WithExistingResourceGroup(resourceGroup)
                                          .WithNewPrimaryNetwork("10.0.0.0/28")
                                          .WithPrimaryPrivateIPAddressDynamic()
                                          .WithoutPrimaryPublicIPAddress()
                                          .WithLinuxCustomImage(customImage.Id)
                                          .WithRootUsername(uname)
                                          .WithRootPassword(password)
                                          // No explicit data disks, let CRP create it from the image's data disk images
                                          .WithSize(VirtualMachineSizeTypes.Parse("Standard_D2a_v4"))
                                          .WithOSDiskCaching(CachingTypes.ReadWrite)
                                          .Create();

                    var dataDisks = virtualMachine2.DataDisks;
                    Assert.NotNull(dataDisks);
                    Assert.Equal(dataDisks.Count, customImage.DataDiskImages.Count);
                    foreach (var imageDataDisk in customImage.DataDiskImages.Values)
                    {
                        Assert.True(dataDisks.ContainsKey(imageDataDisk.Lun));
                        var dataDisk = dataDisks[imageDataDisk.Lun];
                        Assert.Equal(dataDisk.CachingType, imageDataDisk.Caching);
                        // Fails with new service.
                        //Assert.Equal(dataDisk.Size, (long)imageDataDisk.DiskSizeGB.Value);
                    }

                    // Create virtual machine from the custom image
                    // This one override the size and caching type of data disks from data disk images and
                    // adds one additional disk
                    //

                    var vmName3 = "myvm3";
                    var creatableVirtualMachine3 = computeManager.VirtualMachines
                                                   .Define(vmName3)
                                                   .WithRegion(Location)
                                                   .WithExistingResourceGroup(resourceGroup)
                                                   .WithNewPrimaryNetwork("10.0.0.0/28")
                                                   .WithPrimaryPrivateIPAddressDynamic()
                                                   .WithoutPrimaryPublicIPAddress()
                                                   .WithLinuxCustomImage(customImage.Id)
                                                   .WithRootUsername(uname)
                                                   .WithRootPassword(password);
                    foreach (var dataDiskImage in customImage.DataDiskImages.Values)
                    {
                        // Explicitly override the properties of the data disks created from disk image
                        //
                        // CreateOption: FROM_IMAGE
                        var dataDisk = dataDisks[dataDiskImage.Lun];
                        creatableVirtualMachine3.WithNewDataDiskFromImage(dataDiskImage.Lun,
                                                                          dataDisk.Size + 10, // increase size by 10 GB
                                                                          CachingTypes.ReadOnly);
                    }
                    var virtualMachine3 = creatableVirtualMachine3
                                          .WithNewDataDisk(200)                 // CreateOption: EMPTY
                                          .WithSize(VirtualMachineSizeTypes.Parse("Standard_D2a_v4"))
                                          .WithOSDiskCaching(CachingTypes.ReadWrite)
                                          .Create();

                    dataDisks = virtualMachine3.DataDisks;
                    Assert.NotNull(dataDisks);
                    Assert.Equal(dataDisks.Count, customImage.DataDiskImages.Count + 1 /* count one extra empty disk */);
                    foreach (var imageDataDisk in customImage.DataDiskImages.Values)
                    {
                        Assert.True(dataDisks.ContainsKey(imageDataDisk.Lun));
                        var dataDisk = dataDisks[imageDataDisk.Lun];
                        Assert.Equal(CachingTypes.ReadOnly, dataDisk.CachingType);
                        // Fails with new service.
                        //Assert.Equal(dataDisk.Size, (long)imageDataDisk.DiskSizeGB + 10);
                    }
                }
                finally
                {
                    try
                    {
                        resourceManager.ResourceGroups.DeleteByName(rgName);
                    }
                    catch { }
                }
            }
        }
 public void CanCreateVirtualMachineFromPIRImageWithManagedOsDisk()
 {
     using (var context = FluentMockContext.Start(GetType().FullName))
     {
         var vmName1          = "myvm1";
         var publicIPDnsLabel = SdkContext.RandomResourceName("pip", 20);
         var uname            = "juser";
         var password         = "******";
         var resourceManager  = TestHelper.CreateRollupClient();
         var computeManager   = TestHelper.CreateComputeManager();
         var rgName           = TestUtilities.GenerateName("rgfluentchash-");
         try
         {
             var virtualMachine = computeManager.VirtualMachines
                                  .Define(vmName1)
                                  .WithRegion(Location)
                                  .WithNewResourceGroup(rgName)
                                  .WithNewPrimaryNetwork("10.0.0.0/28")
                                  .WithPrimaryPrivateIPAddressDynamic()
                                  .WithNewPrimaryPublicIPAddress(publicIPDnsLabel)
                                  .WithPopularLinuxImage(LinuxImage)
                                  .WithRootUsername(uname)
                                  .WithRootPassword(password)
                                  .WithSize(VirtualMachineSizeTypes.Parse("Standard_D2a_v4"))
                                  .WithOSDiskCaching(CachingTypes.ReadWrite)
                                  .Create();
             // Ensure default to managed disk
             //
             Assert.True(virtualMachine.IsManagedDiskEnabled);
             // Validate caching, size and the default storage account type set for the managed disk
             // backing os disk
             //
             Assert.NotNull(virtualMachine.OSDiskStorageAccountType);
             Assert.Equal(CachingTypes.ReadWrite, virtualMachine.OSDiskCachingType);
             Assert.Equal(virtualMachine.Size, VirtualMachineSizeTypes.StandardD5V2);
             // Validate the implicit managed disk created by CRP to back the os disk
             //
             Assert.NotNull(virtualMachine.OSDiskId);
             var osDisk = computeManager.Disks.GetById(virtualMachine.OSDiskId);
             Assert.True(osDisk.IsAttachedToVirtualMachine);
             Assert.Equal(OperatingSystemTypes.Linux, osDisk.OSType);
             // Check the auto created public ip
             //
             var publicIPId = virtualMachine.GetPrimaryPublicIPAddressId();
             Assert.NotNull(publicIPId);
             // Validates the options which are valid only for native disks
             //
             Assert.Null(virtualMachine.OSUnmanagedDiskVhdUri);
             Assert.NotNull(virtualMachine.UnmanagedDataDisks);
             Assert.True(virtualMachine.UnmanagedDataDisks.Count == 0);
         }
         finally
         {
             try
             {
                 resourceManager.ResourceGroups.DeleteByName(rgName);
             }
             catch { }
         }
     }
 }
        public void CanCreateFromCustomImageWithManagedDisk()
        {
            using (var context = FluentMockContext.Start(GetType().FullName))
            {
                var userName         = "******";
                var password         = "******";
                var publicIPDnsLabel = SdkContext.RandomResourceName("pip", 10);
                var customImageName  = SdkContext.RandomResourceName("img", 10);
                var vmssName         = SdkContext.RandomResourceName("vmss", 10);
                var resourceManager  = TestHelper.CreateRollupClient();
                var computeManager   = TestHelper.CreateComputeManager();
                var networkManager   = TestHelper.CreateNetworkManager();
                var rgName           = TestUtilities.GenerateName("rgfluentchash-");
                try
                {
                    var resourceGroup = resourceManager.ResourceGroups
                                        .Define(rgName)
                                        .WithRegion(Location)
                                        .Create();

                    var vm = computeManager.VirtualMachines.Define(SdkContext.RandomResourceName("vm", 10))
                             .WithRegion(Location)
                             .WithExistingResourceGroup(resourceGroup)
                             .WithNewPrimaryNetwork("10.0.0.0/28")
                             .WithPrimaryPrivateIPAddressDynamic()
                             .WithNewPrimaryPublicIPAddress(publicIPDnsLabel)
                             .WithPopularLinuxImage(KnownLinuxVirtualMachineImage.UbuntuServer16_04_Lts)
                             .WithRootUsername(userName)
                             .WithRootPassword(password)
                             .WithUnmanagedDisks()
                             .DefineUnmanagedDataDisk("disk-1")
                             .WithNewVhd(100)
                             .WithLun(1)
                             .Attach()
                             .DefineUnmanagedDataDisk("disk-2")
                             .WithNewVhd(50)
                             .WithLun(2)
                             .Attach()
                             .WithSize(VirtualMachineSizeTypes.Parse("Standard_D2a_v4"))
                             .Create();

                    Assert.NotNull(vm);

                    TestHelper.DeprovisionAgentInLinuxVM(vm.GetPrimaryPublicIPAddress().Fqdn, 22, userName, password);
                    vm.Deallocate();
                    vm.Generalize();

                    var virtualMachineCustomImage = computeManager.VirtualMachineCustomImages
                                                    .Define(customImageName)
                                                    .WithRegion(Location)
                                                    .WithExistingResourceGroup(resourceGroup)
                                                    .FromVirtualMachine(vm)
                                                    .Create();

                    Assert.NotNull(virtualMachineCustomImage);

                    var network = networkManager
                                  .Networks
                                  .Define(SdkContext.RandomResourceName("vmssvnet", 15))
                                  .WithRegion(Location)
                                  .WithExistingResourceGroup(resourceGroup)
                                  .WithAddressSpace("10.0.0.0/28")
                                  .WithSubnet("subnet1", "10.0.0.0/28")
                                  .Create();

                    var publicLoadBalancer = ScaleSet.CreateHttpLoadBalancers(resourceManager, resourceGroup, "1", Location);
                    var vmScaleSet         = computeManager.VirtualMachineScaleSets
                                             .Define(vmssName)
                                             .WithRegion(Location)
                                             .WithExistingResourceGroup(resourceGroup)
                                             .WithSku(VirtualMachineScaleSetSkuTypes.StandardD5v2)
                                             .WithExistingPrimaryNetworkSubnet(network, "subnet1")
                                             .WithExistingPrimaryInternetFacingLoadBalancer(publicLoadBalancer)
                                             .WithoutPrimaryInternalLoadBalancer()
                                             .WithLinuxCustomImage(virtualMachineCustomImage.Id)
                                             .WithRootUsername(userName)
                                             .WithRootPassword(password)
                                             .Create();

                    var virtualMachineScaleSetVMs = vmScaleSet.VirtualMachines;
                    var virtualMachines           = virtualMachineScaleSetVMs.List();
                    Assert.Equal(virtualMachines.Count(), vmScaleSet.Capacity);
                    foreach (var vm1 in virtualMachines)
                    {
                        Assert.True(vm1.IsOSBasedOnCustomImage);
                        Assert.False(vm1.IsOSBasedOnPlatformImage);
                        Assert.False(vm1.IsOSBasedOnStoredImage);
                        Assert.True(vm1.IsManagedDiskEnabled);
                        Assert.NotNull(vm1.UnmanagedDataDisks);
                        Assert.Empty(vm1.UnmanagedDataDisks);
                        Assert.NotNull(vm1.DataDisks);
                        Assert.Equal(2, vm1.DataDisks.Count); // Disks from data disk image from custom image
                        Assert.True(vm1.DataDisks.ContainsKey(1));
                        var disk = vm1.DataDisks[1];
                        Assert.Equal(100, disk.Size);
                        Assert.True(vm1.DataDisks.ContainsKey(2));
                        disk = vm1.DataDisks[2];
                        Assert.Equal(50, disk.Size);
                    }

                    vmScaleSet.Deallocate();

                    // Updating and adding disk as part of VMSS Update seems consistency failing, CRP is aware of
                    // this, hence until it is fixed comment-out the test
                    //
                    //        {
                    //            "startTime": "2017-01-25T06:10:55.2243509+00:00",
                    //                "endTime": "2017-01-25T06:11:07.8649525+00:00",
                    //                "status": "Failed",
                    //                "error": {
                    //            "code": "InternalExecutionError",
                    //                    "message": "An internal execution error occurred."
                    //        },
                    //            "name": "6786df83-ed3f-4d7a-bf58-d295b96fef46"
                    //        }
                    //
                    //        vmScaleSet.Update()
                    //                .WithDataDiskUpdated(1, 200) // update not supported
                    //                .WithNewDataDisk(100)
                    //                .Apply();
                    //
                    //        vmScaleSet.Start();
                    //
                    //        virtualMachineScaleSetVMs = vmScaleSet.VirtualMachines;
                    //        virtualMachines = virtualMachineScaleSetVMs.List();
                    //        foreach (VirtualMachineScaleSetVM vm1 in virtualMachines) {
                    //            Assert.True(vm1.IsOSBasedOnCustomImage());
                    //            Assert.False(vm1.IsOSBasedOnPlatformImage());
                    //            Assert.False(vm1.IsOSBasedOnStoredImage());
                    //            Assert.True(vm1.IsManagedDiskEnabled());
                    //            Assert.NotNull(vm1.UnmanagedDataDisks());
                    //            Assert.Equal(vm1.UnmanagedDataDisks().Size(), 0);
                    //            Assert.NotNull(vm1.DataDisks());
                    //            Assert.Equal(vm1.DataDisks().Size(), 3);
                    //            Assert.True(vm1.DataDisks().ContainsKey(1));
                    //            VirtualMachineDataDisk disk = vm1.DataDisks().Get(1);
                    //            Assert.Equal(disk.Size(), 200);
                    //            Assert.True(vm1.DataDisks().ContainsKey(2));
                    //            disk = vm1.DataDisks().Get(2);
                    //            Assert.Equal(disk.Size(), 50);
                    //            Assert.True(vm1.DataDisks().ContainsKey(0));
                    //            disk = vm1.DataDisks().Get(0);
                    //            Assert.Equal(disk.Size(), 100);
                    //        }
                }
                finally
                {
                    try
                    {
                        resourceManager.ResourceGroups.DeleteByName(rgName);
                    }
                    catch { }
                }
            }
        }
        public void CanCreateImageFromNativeVhd()
        {
            using (var context = FluentMockContext.Start(GetType().FullName))
            {
                var vhdBasedImageName = SdkContext.RandomResourceName("img", 20);
                var resourceManager   = TestHelper.CreateRollupClient();
                var computeManager    = TestHelper.CreateComputeManager();
                var rgName            = TestUtilities.GenerateName("rgfluentchash-");

                try
                {
                    var linuxVM = PrepareGeneralizedVMWith2EmptyDataDisks(rgName,
                                                                          SdkContext.RandomResourceName("muldvm", 15),
                                                                          Location,
                                                                          computeManager);
                    //
                    var creatableDisk = computeManager.VirtualMachineCustomImages.Define(vhdBasedImageName)
                                        .WithRegion(Location)
                                        .WithNewResourceGroup(rgName)
                                        .WithLinuxFromVhd(linuxVM.OSUnmanagedDiskVhdUri, OperatingSystemStateTypes.Generalized)
                                        .WithOSDiskCaching(linuxVM.OSDiskCachingType);
                    foreach (var disk in linuxVM.UnmanagedDataDisks.Values)
                    {
                        creatableDisk.DefineDataDiskImage()
                        .WithLun(disk.Lun)
                        .FromVhd(disk.VhdUri)
                        .WithDiskCaching(disk.CachingType)
                        .WithDiskSizeInGB(disk.Size + 10)         // Resize each data disk image by +10GB
                        .Attach();
                    }
                    var customImage = creatableDisk.Create();
                    Assert.NotNull(customImage.Id);
                    Assert.Equal(customImage.Name, vhdBasedImageName);
                    Assert.False(customImage.IsCreatedFromVirtualMachine);
                    Assert.Null(customImage.SourceVirtualMachineId);
                    Assert.NotNull(customImage.OSDiskImage);
                    Assert.NotNull(customImage.OSDiskImage.BlobUri);
                    Assert.Equal(CachingTypes.ReadWrite, customImage.OSDiskImage.Caching);
                    Assert.Equal(OperatingSystemStateTypes.Generalized, customImage.OSDiskImage.OsState);
                    Assert.Equal(OperatingSystemTypes.Linux, customImage.OSDiskImage.OsType);
                    Assert.NotNull(customImage.DataDiskImages);
                    Assert.Equal(customImage.DataDiskImages.Count, linuxVM.UnmanagedDataDisks.Count);
                    Assert.Equal(customImage.HyperVGeneration, HyperVGenerationTypes.V1);
                    foreach (ImageDataDisk diskImage in customImage.DataDiskImages.Values)
                    {
                        IVirtualMachineUnmanagedDataDisk matchedDisk = null;
                        foreach (var vmDisk in linuxVM.UnmanagedDataDisks.Values)
                        {
                            if (vmDisk.Lun == diskImage.Lun)
                            {
                                matchedDisk = vmDisk;
                                break;
                            }
                        }
                        Assert.NotNull(matchedDisk);
                        Assert.Equal(matchedDisk.CachingType, diskImage.Caching);
                        Assert.Equal(matchedDisk.VhdUri, diskImage.BlobUri);
                        Assert.Equal((long)matchedDisk.Size + 10, (long)diskImage.DiskSizeGB);
                    }
                    var image = computeManager
                                .VirtualMachineCustomImages
                                .GetByResourceGroup(rgName, vhdBasedImageName);
                    Assert.NotNull(image);
                    var images = computeManager
                                 .VirtualMachineCustomImages
                                 .ListByResourceGroup(rgName);
                    Assert.True(images.Count() > 0);

                    // Create virtual machine from custom image
                    //
                    var virtualMachine = computeManager.VirtualMachines
                                         .Define(SdkContext.RandomResourceName("cusvm", 15))
                                         .WithRegion(Location)
                                         .WithNewResourceGroup(rgName)
                                         .WithNewPrimaryNetwork("10.0.0.0/28")
                                         .WithPrimaryPrivateIPAddressDynamic()
                                         .WithoutPrimaryPublicIPAddress()
                                         .WithLinuxCustomImage(image.Id)
                                         .WithRootUsername("javauser")
                                         .WithRootPassword("12NewPA$$w0rd!")
                                         .WithSize(VirtualMachineSizeTypes.Parse("Standard_D2a_v4"))
                                         .WithOSDiskCaching(CachingTypes.ReadWrite)
                                         .Create();

                    var dataDisks = virtualMachine.DataDisks;
                    Assert.NotNull(dataDisks);
                    Assert.Equal(dataDisks.Count, image.DataDiskImages.Count);

                    //Create a hyperv Gen2 image
                    var creatableDiskGen2 = computeManager
                                            .VirtualMachineCustomImages
                                            .Define(vhdBasedImageName + "Gen2")
                                            .WithRegion(Location)
                                            .WithNewResourceGroup(rgName)
                                            .WithHyperVGeneration(HyperVGenerationTypes.V2)
                                            .WithLinuxFromVhd(linuxVM.OSUnmanagedDiskVhdUri, OperatingSystemStateTypes.Generalized)
                                            .WithOSDiskCaching(linuxVM.OSDiskCachingType);
                    foreach (var disk in linuxVM.UnmanagedDataDisks.Values)
                    {
                        creatableDisk.DefineDataDiskImage()
                        .WithLun(disk.Lun)
                        .FromVhd(disk.VhdUri)
                        .WithDiskCaching(disk.CachingType)
                        .WithDiskSizeInGB(disk.Size + 10)         // Resize each data disk image by +10GB
                        .Attach();
                    }
                    IVirtualMachineCustomImage customImageGen2 = creatableDiskGen2.Create();
                    Assert.NotNull(customImageGen2.Id);
                    Assert.Equal(customImageGen2.Name, vhdBasedImageName + "Gen2");
                    Assert.False(customImageGen2.IsCreatedFromVirtualMachine);
                    Assert.Null(customImageGen2.SourceVirtualMachineId);
                    Assert.NotNull(customImageGen2.OSDiskImage);
                    Assert.NotNull(customImageGen2.OSDiskImage);
                    Assert.Equal(CachingTypes.ReadWrite, customImageGen2.OSDiskImage.Caching);
                    Assert.Equal(OperatingSystemStateTypes.Generalized, customImageGen2.OSDiskImage.OsState);
                    Assert.Equal(OperatingSystemTypes.Linux, customImageGen2.OSDiskImage.OsType);
                    Assert.NotNull(customImageGen2.DataDiskImages);
                    Assert.Equal(0, customImageGen2.DataDiskImages.Count);
                    Assert.Equal(customImageGen2.HyperVGeneration, HyperVGenerationTypes.V2);
                }
                finally
                {
                    try
                    {
                        resourceManager.ResourceGroups.DeleteByName(rgName);
                    }
                    catch { }
                }
            }
        }
        /**
         * Azure Network sample for managing virtual networks.
         *  - Create a virtual network with Subnets
         *  - Update a virtual network
         *  - Create virtual machines in the virtual network subnets
         *  - Create another virtual network
         *  - List virtual networks
         */
        public async static Task RunSampleAsync(IAzure azure)
        {
            string vnetName1      = SdkContext.RandomResourceName("vnet1", 20);
            string vnetName2      = SdkContext.RandomResourceName("vnet2", 20);
            string frontEndVmName = SdkContext.RandomResourceName("fevm", 24);
            string backEndVmName  = SdkContext.RandomResourceName("bevm", 24);
            string publicIpAddressLeafDnsForFrontEndVm = SdkContext.RandomResourceName("pip1", 24);

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

                // Creates a network security group for backend subnet

                Utilities.Log("Creating a network security group for virtual network backend subnet...");
                Utilities.Log("Creating a network security group for virtual network frontend subnet...");

                var backEndSubnetNsg = await azure.NetworkSecurityGroups
                                       .Define(VNet1BackEndSubnetNsgName)
                                       .WithRegion(Region.USEast)
                                       .WithNewResourceGroup(ResourceGroupName)
                                       .DefineRule("DenyInternetInComing")
                                       .DenyInbound()
                                       .FromAddress("INTERNET")
                                       .FromAnyPort()
                                       .ToAnyAddress()
                                       .ToAnyPort()
                                       .WithAnyProtocol()
                                       .Attach()
                                       .DefineRule("DenyInternetOutGoing")
                                       .DenyOutbound()
                                       .FromAnyAddress()
                                       .FromAnyPort()
                                       .ToAddress("INTERNET")
                                       .ToAnyPort()
                                       .WithAnyProtocol()
                                       .Attach()
                                       .CreateAsync();

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

                var frontEndSubnetNsg = await azure.NetworkSecurityGroups.Define(VNet1FrontEndSubnetNsgName)
                                        .WithRegion(Region.USEast)
                                        .WithExistingResourceGroup(ResourceGroupName)
                                        .DefineRule("AllowHttpInComing")
                                        .AllowInbound()
                                        .FromAddress("INTERNET")
                                        .FromAnyPort()
                                        .ToAnyAddress()
                                        .ToPort(80)
                                        .WithProtocol(SecurityRuleProtocol.Tcp)
                                        .Attach()
                                        .DefineRule("DenyInternetOutGoing")
                                        .DenyOutbound()
                                        .FromAnyAddress()
                                        .FromAnyPort()
                                        .ToAddress("INTERNET")
                                        .ToAnyPort()
                                        .WithAnyProtocol()
                                        .Attach()
                                        .CreateAsync();

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

                Utilities.Log("Creating virtual network #1...");

                INetwork virtualNetwork1 = await azure.Networks.Define(vnetName1)
                                           .WithRegion(Region.USEast)
                                           .WithExistingResourceGroup(ResourceGroupName)
                                           .WithAddressSpace("192.168.0.0/16")
                                           .WithSubnet(VNet1FrontEndSubnetName, "192.168.1.0/24")
                                           .DefineSubnet(VNet1BackEndSubnetName)
                                           .WithAddressPrefix("192.168.2.0/24")
                                           .WithExistingNetworkSecurityGroup(backEndSubnetNsg)
                                           .Attach()
                                           .CreateAsync();

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

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

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

                Utilities.Log("Associating network security group rule to frontend subnet");

                await virtualNetwork1.Update()
                .UpdateSubnet(VNet1FrontEndSubnetName)
                .WithExistingNetworkSecurityGroup(frontEndSubnetNsg)
                .Parent()
                .ApplyAsync();

                Utilities.Log("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
                Utilities.Log("Creating a Linux virtual machine in the frontend subnet");
                // Creates the second virtual machine in the backend subnet
                Utilities.Log("Creating a Linux virtual machine in the backend subnet");
                // Create a virtual network with default address-space and one default subnet
                Utilities.Log("Creating virtual network #2...");

                var t1 = DateTime.UtcNow;

                var frontEndVM = await azure.VirtualMachines.Define(frontEndVmName)
                                 .WithRegion(Region.USEast)
                                 .WithExistingResourceGroup(ResourceGroupName)
                                 .WithExistingPrimaryNetwork(virtualNetwork1)
                                 .WithSubnet(VNet1FrontEndSubnetName)
                                 .WithPrimaryPrivateIPAddressDynamic()
                                 .WithNewPrimaryPublicIPAddress(publicIpAddressLeafDnsForFrontEndVm)
                                 .WithPopularLinuxImage(KnownLinuxVirtualMachineImage.UbuntuServer16_04_Lts)
                                 .WithRootUsername(UserName)
                                 .WithSsh(SshKey)
                                 .WithSize(VirtualMachineSizeTypes.Parse("Standard_D2a_v4"))
                                 .CreateAsync();

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

                var backEndVM = await azure.VirtualMachines.Define(backEndVmName)
                                .WithRegion(Region.USEast)
                                .WithExistingResourceGroup(ResourceGroupName)
                                .WithExistingPrimaryNetwork(virtualNetwork1)
                                .WithSubnet(VNet1BackEndSubnetName)
                                .WithPrimaryPrivateIPAddressDynamic()
                                .WithoutPrimaryPublicIPAddress()
                                .WithPopularLinuxImage(KnownLinuxVirtualMachineImage.UbuntuServer16_04_Lts)
                                .WithRootUsername(UserName)
                                .WithSsh(SshKey)
                                .WithSize(VirtualMachineSizeTypes.Parse("Standard_D2a_v4"))
                                .CreateAsync();

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

                var virtualNetwork2 = await azure.Networks.Define(vnetName2)
                                      .WithRegion(Region.USEast)
                                      .WithNewResourceGroup(ResourceGroupName)
                                      .CreateAsync();

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

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

                foreach (var virtualNetwork in await azure.Networks.ListByResourceGroupAsync(ResourceGroupName))
                {
                    Utilities.PrintVirtualNetwork(virtualNetwork);
                }

                //============================================================
                // Delete a virtual network
                Utilities.Log("Deleting the virtual network");
                await azure.Networks.DeleteByIdAsync(virtualNetwork2.Id);

                Utilities.Log("Deleted the virtual network");
            }
            finally
            {
                try
                {
                    Utilities.Log("Deleting Resource Group: " + ResourceGroupName);
                    await azure.ResourceGroups.DeleteByNameAsync(ResourceGroupName);

                    Utilities.Log("Deleted Resource Group: " + ResourceGroupName);
                }
                catch (NullReferenceException)
                {
                    Utilities.Log("Did not create any resources in Azure. No clean up is necessary");
                }
                catch (Exception ex)
                {
                    Utilities.Log(ex);
                }
            }
        }
        public void CanCreateImageFromManagedDisk()
        {
            using (var context = FluentMockContext.Start(GetType().FullName))
            {
                var vmName             = SdkContext.RandomResourceName("vm7-", 20);
                var storageAccountName = SdkContext.RandomResourceName("stg", 17);
                var uname           = "juser";
                var password        = "******";
                var resourceManager = TestHelper.CreateRollupClient();
                var computeManager  = TestHelper.CreateComputeManager();
                var storageManager  = TestHelper.CreateStorageManager();
                var rgName          = TestUtilities.GenerateName("rgfluentchash-");
                try
                {
                    var nativeVM = computeManager.VirtualMachines
                                   .Define(vmName)
                                   .WithRegion(Location)
                                   .WithNewResourceGroup(rgName)
                                   .WithNewPrimaryNetwork("10.0.0.0/28")
                                   .WithPrimaryPrivateIPAddressDynamic()
                                   .WithoutPrimaryPublicIPAddress()
                                   .WithLatestLinuxImage("Canonical", "UbuntuServer", "14.04.2-LTS")
                                   .WithRootUsername(uname)
                                   .WithRootPassword(password)
                                   .WithUnmanagedDisks()           /* UN-MANAGED OS and DATA DISKS */
                                   .DefineUnmanagedDataDisk("disk1")
                                   .WithNewVhd(100)
                                   .WithCaching(CachingTypes.ReadWrite)
                                   .Attach()
                                   .WithNewUnmanagedDataDisk(100)
                                   .WithSize(VirtualMachineSizeTypes.Parse("Standard_D2a_v4"))
                                   .WithNewStorageAccount(storageAccountName)
                                   .WithOSDiskCaching(CachingTypes.ReadWrite)
                                   .Create();

                    Assert.False(nativeVM.IsManagedDiskEnabled);
                    var osVhdUri = nativeVM.OSUnmanagedDiskVhdUri;
                    Assert.NotNull(osVhdUri);
                    var dataDisks = nativeVM.UnmanagedDataDisks;
                    Assert.Equal(2, dataDisks.Count);

                    computeManager.VirtualMachines.DeleteById(nativeVM.Id);

                    var osDiskName = SdkContext.RandomResourceName("dsk", 15);
                    // Create managed disk with Os from vm's Os disk
                    //
                    var managedOsDisk = computeManager.Disks.Define(osDiskName)
                                        .WithRegion(Location)
                                        .WithNewResourceGroup(rgName)
                                        .WithLinuxFromVhd(osVhdUri)
                                        .WithStorageAccountName(storageAccountName)
                                        .Create();

                    // Create managed disk with Data from vm's lun0 data disk
                    //
                    var storageAccount = storageManager.StorageAccounts.GetByResourceGroup(rgName, storageAccountName);

                    var dataDiskName1     = SdkContext.RandomResourceName("dsk", 15);
                    var vmNativeDataDisk1 = dataDisks[0];
                    var managedDataDisk1  = computeManager.Disks.Define(dataDiskName1)
                                            .WithRegion(Location)
                                            .WithNewResourceGroup(rgName)
                                            .WithData()
                                            .FromVhd(vmNativeDataDisk1.VhdUri)
                                            .WithStorageAccount(storageAccount)
                                            .Create();

                    // Create managed disk with Data from vm's lun1 data disk
                    //
                    var dataDiskName2     = SdkContext.RandomResourceName("dsk", 15);
                    var vmNativeDataDisk2 = dataDisks[1];
                    var managedDataDisk2  = computeManager.Disks.Define(dataDiskName2)
                                            .WithRegion(Location)
                                            .WithNewResourceGroup(rgName)
                                            .WithData()
                                            .FromVhd(vmNativeDataDisk2.VhdUri)
                                            .WithStorageAccountId(storageAccount.Id)
                                            .Create();

                    // Create an image from the above managed disks
                    // Note that this is not a direct user scenario, but including this as per CRP team request
                    //
                    var imageName   = SdkContext.RandomResourceName("img", 15);
                    var customImage = computeManager.VirtualMachineCustomImages.Define(imageName)
                                      .WithRegion(Location)
                                      .WithNewResourceGroup(rgName)
                                      .WithLinuxFromDisk(managedOsDisk, OperatingSystemStateTypes.Generalized)
                                      .DefineDataDiskImage()
                                      .WithLun(vmNativeDataDisk1.Lun)
                                      .FromManagedDisk(managedDataDisk1)
                                      .WithDiskCaching(vmNativeDataDisk1.CachingType)
                                      .WithDiskSizeInGB(vmNativeDataDisk1.Size + 10)
                                      .Attach()
                                      .DefineDataDiskImage()
                                      .WithLun(vmNativeDataDisk2.Lun)
                                      .FromManagedDisk(managedDataDisk2)
                                      .WithDiskSizeInGB(vmNativeDataDisk2.Size + 10)
                                      .Attach()
                                      .Create();

                    Assert.NotNull(customImage);
                    Assert.Equal(customImage.Name, imageName, ignoreCase: true);
                    Assert.NotNull(customImage.OSDiskImage);
                    Assert.Equal(OperatingSystemStateTypes.Generalized, customImage.OSDiskImage.OsState);
                    Assert.Equal(OperatingSystemTypes.Linux, customImage.OSDiskImage.OsType);
                    Assert.NotNull(customImage.DataDiskImages);
                    Assert.Equal(2, customImage.DataDiskImages.Count);
                    Assert.Equal(customImage.HyperVGeneration, HyperVGenerationTypes.V1);
                    Assert.Null(customImage.SourceVirtualMachineId);

                    Assert.True(customImage.DataDiskImages.ContainsKey(vmNativeDataDisk1.Lun));
                    Assert.Equal(customImage.DataDiskImages[vmNativeDataDisk1.Lun].Caching, vmNativeDataDisk1.CachingType);
                    Assert.True(customImage.DataDiskImages.ContainsKey(vmNativeDataDisk2.Lun));
                    Assert.Equal(CachingTypes.None, customImage.DataDiskImages[vmNativeDataDisk2.Lun].Caching);

                    foreach (var vmDisk in dataDisks.Values)
                    {
                        Assert.True(customImage.DataDiskImages.ContainsKey(vmDisk.Lun));
                        var diskImage = customImage.DataDiskImages[vmDisk.Lun];
                        Assert.Equal((long)diskImage.DiskSizeGB, vmDisk.Size + 10);
                        Assert.Null(diskImage.BlobUri);
                        Assert.NotNull(diskImage.ManagedDisk);
                        Assert.True(diskImage.ManagedDisk.Id.Equals(managedDataDisk1.Id, StringComparison.OrdinalIgnoreCase) ||
                                    diskImage.ManagedDisk.Id.Equals(managedDataDisk2.Id, StringComparison.OrdinalIgnoreCase));
                    }
                    computeManager.Disks.DeleteById(managedOsDisk.Id);
                    computeManager.Disks.DeleteById(managedDataDisk1.Id);
                    computeManager.Disks.DeleteById(managedDataDisk2.Id);
                    computeManager.VirtualMachineCustomImages.DeleteById(customImage.Id);
                }
                finally
                {
                    try
                    {
                        resourceManager.ResourceGroups.DeleteByName(rgName);
                    }
                    catch { }
                }
            }
        }
        /**
         * Azure DNS sample for managing DNS zones.
         *  - Create a root DNS zone (contoso.com)
         *  - Create a web application
         *  - Add a CNAME record (www) to root DNS zone and bind it to web application host name
         *  - Creates a virtual machine with public IP
         *  - Add a A record (employees) to root DNS zone that points to virtual machine public IPV4 address
         *  - Creates a child DNS zone (partners.contoso.com)
         *  - Creates a virtual machine with public IP
         *  - Add a A record (partners) to child DNS zone that points to virtual machine public IPV4 address
         *  - Delegate from root domain to child domain by adding NS records
         *  - Remove A record from the root DNS zone
         *  - Delete the child DNS zone
         */
        public static void RunSample(IAzure azure)
        {
            string rgName     = SdkContext.RandomResourceName("rgNEMV_", 24);
            string webAppName = SdkContext.RandomResourceName("webapp1-", 20);

            try
            {
                var resourceGroup = azure.ResourceGroups.Define(rgName)
                                    .WithRegion(Region.USWest)
                                    .Create();

                //============================================================
                // Creates root DNS Zone

                Utilities.Log("Creating root DNS zone " + CustomDomainName + "...");
                var rootDnsZone = azure.DnsZones.Define(CustomDomainName)
                                  .WithExistingResourceGroup(resourceGroup)
                                  .Create();
                Utilities.Log("Created root DNS zone " + rootDnsZone.Name);
                Utilities.Print(rootDnsZone);

                //============================================================
                // Sets NS records in the parent zone (hosting custom domain) to make Azure DNS the authoritative
                // source for name resolution for the zone

                Utilities.Log("Go to your registrar portal and configure your domain " + CustomDomainName
                              + " with following name server addresses");
                foreach (var nameServer in rootDnsZone.NameServers)
                {
                    Utilities.Log(" " + nameServer);
                }
                Utilities.Log("Press [ENTER] after finishing above step");
                Utilities.ReadLine();

                //============================================================
                // Creates a web App

                Utilities.Log("Creating Web App " + webAppName + "...");
                var webApp = azure.WebApps.Define(webAppName)
                             .WithRegion(Region.USEast2)
                             .WithExistingResourceGroup(rgName)
                             .WithNewWindowsPlan(PricingTier.BasicB1)
                             .DefineSourceControl()
                             .WithPublicGitRepository("https://github.com/jianghaolu/azure-site-test")
                             .WithBranch("master")
                             .Attach()
                             .Create();
                Utilities.Log("Created web app " + webAppName);
                Utilities.Print(webApp);

                //============================================================
                // Creates a CName record and bind it with the web app

                // Step 1: Adds CName DNS record to root DNS zone that specify web app host domain as an
                // alias for www.[customDomainName]

                Utilities.Log("Updating DNS zone by adding a CName record...");
                rootDnsZone = rootDnsZone.Update()
                              .WithCNameRecordSet("www", webApp.DefaultHostName)
                              .Apply();
                Utilities.Log("DNS zone updated");
                Utilities.Print(rootDnsZone);

                // Waiting for a minute for DNS CName entry to propagate
                Utilities.Log("Waiting a minute for CName record entry to propagate...");
                SdkContext.DelayProvider.Delay(60 * 1000);

                // Step 2: Adds a web app host name binding for www.[customDomainName]
                //         This binding action will fail if the CName record propagation is not yet completed

                Utilities.Log("Updating Web app with host name binding...");
                webApp.Update()
                .DefineHostnameBinding()
                .WithThirdPartyDomain(CustomDomainName)
                .WithSubDomain("www")
                .WithDnsRecordType(CustomHostNameDnsRecordType.CName)
                .Attach()
                .Apply();
                Utilities.Log("Web app updated");
                Utilities.Print(webApp);



                //============================================================
                // Creates a virtual machine with public IP

                Utilities.Log("Creating a virtual machine with public IP...");
                var virtualMachine1 = azure.VirtualMachines
                                      .Define(SdkContext.RandomResourceName("employeesvm-", 20))
                                      .WithRegion(Region.USEast)
                                      .WithExistingResourceGroup(resourceGroup)
                                      .WithNewPrimaryNetwork("10.0.0.0/28")
                                      .WithPrimaryPrivateIPAddressDynamic()
                                      .WithNewPrimaryPublicIPAddress(SdkContext.RandomResourceName("empip-", 20))
                                      .WithPopularWindowsImage(KnownWindowsVirtualMachineImage.WindowsServer2012R2Datacenter)
                                      .WithAdminUsername("testuser")
                                      .WithAdminPassword("12NewPA$$w0rd!")
                                      .WithSize(VirtualMachineSizeTypes.Parse("Standard_D2a_v4"))
                                      .Create();
                Utilities.Log("Virtual machine created");

                //============================================================
                // Update DNS zone by adding a A record in root DNS zone pointing to virtual machine IPv4 address

                var vm1PublicIpAddress = virtualMachine1.GetPrimaryPublicIPAddress();
                Utilities.Log("Updating root DNS zone " + CustomDomainName + "...");
                rootDnsZone = rootDnsZone.Update()
                              .DefineARecordSet("employees")
                              .WithIPv4Address(vm1PublicIpAddress.IPAddress)
                              .Attach()
                              .Apply();
                Utilities.Log("Updated root DNS zone " + rootDnsZone.Name);
                Utilities.Print(rootDnsZone);

                // Prints the CName and A Records in the root DNS zone
                //
                Utilities.Log("Getting CName record set in the root DNS zone " + CustomDomainName + "...");
                var cnameRecordSets = rootDnsZone
                                      .CNameRecordSets
                                      .List();

                foreach (var cnameRecordSet in cnameRecordSets)
                {
                    Utilities.Log("Name: " + cnameRecordSet.Name + " Canonical Name: " + cnameRecordSet.CanonicalName);
                }

                Utilities.Log("Getting ARecord record set in the root DNS zone " + CustomDomainName + "...");
                var aRecordSets = rootDnsZone
                                  .ARecordSets
                                  .List();

                foreach (var aRecordSet in aRecordSets)
                {
                    Utilities.Log("Name: " + aRecordSet.Name);
                    foreach (var ipv4Address in aRecordSet.IPv4Addresses)
                    {
                        Utilities.Log("  " + ipv4Address);
                    }
                }

                //============================================================
                // Creates a child DNS zone

                var partnerSubDomainName = "partners." + CustomDomainName;
                Utilities.Log("Creating child DNS zone " + partnerSubDomainName + "...");
                var partnersDnsZone = azure.DnsZones
                                      .Define(partnerSubDomainName)
                                      .WithExistingResourceGroup(resourceGroup)
                                      .Create();
                Utilities.Log("Created child DNS zone " + partnersDnsZone.Name);
                Utilities.Print(partnersDnsZone);

                //============================================================
                // Adds NS records in the root dns zone to delegate partners.[customDomainName] to child dns zone

                Utilities.Log("Updating root DNS zone " + rootDnsZone + "...");
                var nsRecordStage = rootDnsZone
                                    .Update()
                                    .DefineNSRecordSet("partners")
                                    .WithNameServer(partnersDnsZone.NameServers[0]);
                for (int i = 1; i < partnersDnsZone.NameServers.Count(); i++)
                {
                    nsRecordStage = nsRecordStage.WithNameServer(partnersDnsZone.NameServers[i]);
                }
                nsRecordStage
                .Attach()
                .Apply();
                Utilities.Log("Root DNS zone updated");
                Utilities.Print(rootDnsZone);

                //============================================================
                // Creates a virtual machine with public IP

                Utilities.Log("Creating a virtual machine with public IP...");
                var virtualMachine2 = azure.VirtualMachines
                                      .Define(SdkContext.RandomResourceName("partnersvm-", 20))
                                      .WithRegion(Region.USEast)
                                      .WithExistingResourceGroup(resourceGroup)
                                      .WithNewPrimaryNetwork("10.0.0.0/28")
                                      .WithPrimaryPrivateIPAddressDynamic()
                                      .WithNewPrimaryPublicIPAddress(SdkContext.RandomResourceName("ptnerpip-", 20))
                                      .WithPopularWindowsImage(KnownWindowsVirtualMachineImage.WindowsServer2012R2Datacenter)
                                      .WithAdminUsername("testuser")
                                      .WithAdminPassword("12NewPA$$w0rd!")
                                      .WithSize(VirtualMachineSizeTypes.Parse("Standard_D2a_v4"))
                                      .Create();
                Utilities.Log("Virtual machine created");

                //============================================================
                // Update child DNS zone by adding a A record pointing to virtual machine IPv4 address

                var vm2PublicIpAddress = virtualMachine2.GetPrimaryPublicIPAddress();
                Utilities.Log("Updating child DNS zone " + partnerSubDomainName + "...");
                partnersDnsZone = partnersDnsZone.Update()
                                  .DefineARecordSet("@")
                                  .WithIPv4Address(vm2PublicIpAddress.IPAddress)
                                  .Attach()
                                  .Apply();
                Utilities.Log("Updated child DNS zone " + partnersDnsZone.Name);
                Utilities.Print(partnersDnsZone);

                //============================================================
                // Removes A record entry from the root DNS zone

                Utilities.Log("Removing A Record from root DNS zone " + rootDnsZone.Name + "...");
                rootDnsZone = rootDnsZone.Update()
                              .WithoutARecordSet("employees")
                              .Apply();
                Utilities.Log("Removed A Record from root DNS zone");
                Utilities.Print(rootDnsZone);

                //============================================================
                // Deletes the DNS zone

                Utilities.Log("Deleting child DNS zone " + partnersDnsZone.Name + "...");
                azure.DnsZones.DeleteById(partnersDnsZone.Id);
                Utilities.Log("Deleted child DNS zone " + partnersDnsZone.Name);
            }
            finally
            {
                try
                {
                    Utilities.Log("Deleting Resource Group: " + rgName);
                    azure.ResourceGroups.DeleteByName(rgName);
                    Utilities.Log("Deleted Resource Group: " + rgName);
                }
                catch (Exception)
                {
                    Utilities.Log("Did not create any resources in Azure. No clean up is necessary");
                }
            }
        }
        public void CanUpdateExtensionPublicPrivateSettings()
        {
            using (var context = FluentMockContext.Start(GetType().FullName))
            {
                Region region  = Region.USEast2;
                string rgName  = TestUtilities.GenerateName("javacsmrg");
                string stgName = TestUtilities.GenerateName("stg");
                string vmName  = TestUtilities.GenerateName("extvm");

                var azure = TestHelper.CreateRollupClient();

                try
                {
                    var storageAccount = azure.StorageAccounts
                                         .Define(stgName)
                                         .WithRegion(Region.USEast2)
                                         .WithNewResourceGroup(rgName)
                                         .Create();

                    /*** CREATE VIRTUAL MACHINE WITH AN EXTENSION **/

                    var keys = storageAccount.GetKeys();
                    Assert.NotNull(keys);
                    Assert.True(keys.Count() > 0);
                    var    storageAccountKey = keys.First();
                    string uri = prepareCustomScriptStorageUri(storageAccount.Name, storageAccountKey.Value, "scripts");

                    List <string> fileUris = new List <string>();
                    fileUris.Add(uri);
                    string commandToExecute = "bash install_apache.sh";

                    var vm = azure.VirtualMachines
                             .Define(vmName)
                             .WithRegion(region)
                             .WithExistingResourceGroup(rgName)
                             .WithNewPrimaryNetwork("10.0.0.0/28")
                             .WithPrimaryPrivateIPAddressDynamic()
                             .WithoutPrimaryPublicIPAddress()
                             .WithPopularLinuxImage(KnownLinuxVirtualMachineImage.UbuntuServer14_04_Lts)
                             .WithRootUsername("Foo12")
                             .WithRootPassword("BaR@12abc!")
                             .WithSize(VirtualMachineSizeTypes.Parse("Standard_D2a_v4"))
                             .DefineNewExtension("CustomScriptForLinux")
                             .WithPublisher("Microsoft.OSTCExtensions")
                             .WithType("CustomScriptForLinux")
                             .WithVersion("1.4")
                             .WithMinorVersionAutoUpgrade()
                             .WithPublicSetting("fileUris", fileUris)
                             .WithProtectedSetting("commandToExecute", commandToExecute)
                             .WithProtectedSetting("storageAccountName", storageAccount.Name)
                             .WithProtectedSetting("storageAccountKey", storageAccountKey.Value)
                             .Attach()
                             .Create();

                    Assert.True(vm.ListExtensions().Count > 0);
                    Assert.True(vm.ListExtensions().ContainsKey("CustomScriptForLinux"));
                    IVirtualMachineExtension customScriptExtension;
                    Assert.True(vm.ListExtensions().TryGetValue("CustomScriptForLinux", out customScriptExtension));
                    Assert.NotNull(customScriptExtension);
                    Assert.Equal("Microsoft.OSTCExtensions", customScriptExtension.PublisherName, true);
                    Assert.Equal("CustomScriptForLinux", customScriptExtension.TypeName, true);
                    Assert.True(customScriptExtension.AutoUpgradeMinorVersionEnabled);

                    // Special check for C# implementation, seems runtime changed the actual type
                    // of public settings from dictionary to Newtonsoft.Json.Linq.JObject.
                    // In future such changes needs to be catched before attemptting inner conversion
                    // hence the below special validation (not applicable for Java)
                    //
                    Assert.NotNull(customScriptExtension.Inner);
                    Assert.NotNull(customScriptExtension.Inner.Settings);
                    bool isJObject    = customScriptExtension.Inner.Settings is JObject;
                    bool isDictionary = customScriptExtension.Inner.Settings is IDictionary <string, object>;
                    Assert.True(isJObject || isDictionary);

                    // Ensure the public settings are accessible, the protected settings won't be returned from the service.
                    //
                    var publicSettings = customScriptExtension.PublicSettings;
                    Assert.NotNull(publicSettings);
                    Assert.Equal(1, publicSettings.Count);
                    Assert.True(publicSettings.ContainsKey("fileUris"));
                    string fileUrisString = (publicSettings["fileUris"]).ToString();
                    if (HttpMockServer.Mode != HttpRecorderMode.Playback)
                    {
                        Assert.Contains(uri, fileUrisString);
                    }

                    /*** UPDATE THE EXTENSION WITH NEW PUBLIC AND PROTECTED SETTINGS **/

                    // Regenerate the storage account key
                    //
                    storageAccount.RegenerateKey(storageAccountKey.KeyName);
                    keys = storageAccount.GetKeys();
                    Assert.NotNull(keys);
                    Assert.True(keys.Count() > 0);
                    var updatedStorageAccountKey = keys.FirstOrDefault(key => key.KeyName.Equals(storageAccountKey.KeyName, StringComparison.OrdinalIgnoreCase));
                    Assert.NotNull(updatedStorageAccountKey);
                    if (HttpMockServer.Mode != HttpRecorderMode.Playback)
                    {
                        Assert.NotEqual(updatedStorageAccountKey.Value, storageAccountKey.Value);
                    }

                    // Upload the script to a different container ("scripts2") in the same storage account
                    //
                    var           uri2      = prepareCustomScriptStorageUri(storageAccount.Name, updatedStorageAccountKey.Value, "scripts2");
                    List <string> fileUris2 = new List <string>();
                    fileUris2.Add(uri2);
                    string commandToExecute2 = "bash install_apache.sh";

                    vm.Update()
                    .UpdateExtension("CustomScriptForLinux")
                    .WithPublicSetting("fileUris", fileUris2)
                    .WithProtectedSetting("commandToExecute", commandToExecute2)
                    .WithProtectedSetting("storageAccountName", storageAccount.Name)
                    .WithProtectedSetting("storageAccountKey", updatedStorageAccountKey.Value)
                    .Parent()
                    .Apply();

                    Assert.True(vm.ListExtensions().Count > 0);
                    Assert.True(vm.ListExtensions().ContainsKey("CustomScriptForLinux"));
                    IVirtualMachineExtension customScriptExtension2;
                    Assert.True(vm.ListExtensions().TryGetValue("CustomScriptForLinux", out customScriptExtension2));
                    Assert.NotNull(customScriptExtension2);
                    Assert.Equal("Microsoft.OSTCExtensions", customScriptExtension2.PublisherName, true);
                    Assert.Equal("CustomScriptForLinux", customScriptExtension2.TypeName, true);
                    Assert.True(customScriptExtension2.AutoUpgradeMinorVersionEnabled);

                    var publicSettings2 = customScriptExtension2.PublicSettings;
                    Assert.NotNull(publicSettings2);
                    Assert.Equal(1, publicSettings2.Count);
                    Assert.True(publicSettings2.ContainsKey("fileUris"));

                    string fileUris2String = (publicSettings2["fileUris"]).ToString();
                    if (HttpMockServer.Mode != HttpRecorderMode.Playback)
                    {
                        Assert.Contains(uri2, fileUris2String);
                    }
                }
                finally
                {
                    try
                    {
                        azure.ResourceGroups.DeleteByName(rgName);
                    }
                    catch { }
                }
            }
        }
示例#20
0
        /**
         * Azure Network sample for managing network security groups -
         *  - Create a network security group for the front end of a subnet
         *  - Create a network security group for the back end of a subnet
         *  - Create Linux virtual machines for the front end and back end
         *  -- Apply network security groups
         *  - List network security groups
         *  - Update a network security group.
         */
        public static void RunSample(IAzure azure)
        {
            string frontEndNSGName         = SdkContext.RandomResourceName("fensg", 24);
            string backEndNSGName          = SdkContext.RandomResourceName("bensg", 24);
            string rgName                  = SdkContext.RandomResourceName("rgNEMS", 24);
            string vnetName                = SdkContext.RandomResourceName("vnet", 24);
            string networkInterfaceName1   = SdkContext.RandomResourceName("nic1", 24);
            string networkInterfaceName2   = SdkContext.RandomResourceName("nic2", 24);
            string publicIPAddressLeafDNS1 = SdkContext.RandomResourceName("pip1", 24);
            string frontEndVMName          = SdkContext.RandomResourceName("fevm", 24);
            string backEndVMName           = SdkContext.RandomResourceName("bevm", 24);

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

                Utilities.Log("Creating a virtual network ...");

                var network = azure.Networks.Define(vnetName)
                              .WithRegion(Region.USEast)
                              .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();

                Utilities.Log("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

                Utilities.Log("Creating a security group for the front end - allows SSH and HTTP");
                var frontEndNSG = azure.NetworkSecurityGroups.Define(frontEndNSGName)
                                  .WithRegion(Region.USEast)
                                  .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();

                Utilities.Log("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

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

                var backEndNSG = azure.NetworkSecurityGroups.Define(backEndNSGName)
                                 .WithRegion(Region.USEast)
                                 .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();

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

                Utilities.Log("Creating multiple network interfaces");
                Utilities.Log("Creating network interface 1");

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

                Utilities.Log("Creating a network interface for the front end");

                var networkInterface1 = azure.NetworkInterfaces.Define(networkInterfaceName1)
                                        .WithRegion(Region.USEast)
                                        .WithExistingResourceGroup(rgName)
                                        .WithExistingPrimaryNetwork(network)
                                        .WithSubnet("Front-end")
                                        .WithPrimaryPrivateIPAddressDynamic()
                                        .WithNewPrimaryPublicIPAddress(publicIPAddressLeafDNS1)
                                        .WithIPForwarding()
                                        .WithExistingNetworkSecurityGroup(frontEndNSG)
                                        .Create();

                Utilities.Log("Created network interface for the front end");

                Utilities.PrintNetworkInterface(networkInterface1);

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

                Utilities.Log("Creating a network interface for the back end");

                var networkInterface2 = azure.NetworkInterfaces.Define(networkInterfaceName2)
                                        .WithRegion(Region.USEast)
                                        .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

                Utilities.Log("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.USEast)
                                 .WithExistingResourceGroup(rgName)
                                 .WithExistingPrimaryNetworkInterface(networkInterface1)
                                 .WithPopularLinuxImage(KnownLinuxVirtualMachineImage.UbuntuServer16_04_Lts)
                                 .WithRootUsername(UserName)
                                 .WithSsh(SshKey)
                                 .WithSize(VirtualMachineSizeTypes.Parse("Standard_D2a_v4"))
                                 .Create();

                var t2 = DateTime.UtcNow;
                Utilities.Log("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

                Utilities.Log("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.USEast)
                                .WithExistingResourceGroup(rgName)
                                .WithExistingPrimaryNetworkInterface(networkInterface2)
                                .WithPopularLinuxImage(KnownLinuxVirtualMachineImage.UbuntuServer16_04_Lts)
                                .WithRootUsername(UserName)
                                .WithSsh(SshKey)
                                .WithSize(VirtualMachineSizeTypes.Parse("Standard_D2a_v4"))
                                .Create();

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

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

                Utilities.Log("Walking through network security groups");
                var networkSecurityGroups = azure.NetworkSecurityGroups.ListByResourceGroup(rgName);

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

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

                Utilities.Log("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();

                Utilities.Log("Updated the front end network security group");
                Utilities.PrintNetworkSecurityGroup(frontEndNSG);
            }
            finally
            {
                try
                {
                    Utilities.Log("Deleting Resource Group: " + rgName);
                    azure.ResourceGroups.DeleteByName(rgName);
                    Utilities.Log("Deleted Resource Group: " + rgName);
                }
                catch (NullReferenceException)
                {
                    Utilities.Log("Did not create any resources in Azure. No clean up is necessary");
                }
                catch (Exception ex)
                {
                    Utilities.Log(ex);
                }
            }
        }