/**
         * It creates a new Azure virtual machine and it instantiate a Java Docker client.
         * @param azure - instance of Azure
         * @param rgName - name of the Azure resource group to be used when creating a virtual machine
         * @param region - region to be used when creating a virtual machine
         * @return an instance of DockerClient
         */
        public static DockerClient FromNewDockerVM(IAzure azure, String rgName, Region region)
        {
            string dockerVMName     = SdkContext.RandomResourceName("dockervm", 15);
            string publicIPDnsLabel = SdkContext.RandomResourceName("pip", 10);
            string vmUserName       = "******";
            string vmPassword       = Utilities.CreatePassword();

            // Could not find a Docker environment; presume that there is no local Docker engine running and
            //    attempt to configure a Docker engine running inside a new Azure virtual machine
            Utilities.Log("Creating an Azure virtual machine running Docker");

            IVirtualMachine dockerVM = azure.VirtualMachines.Define(dockerVMName)
                                       .WithRegion(region)
                                       .WithExistingResourceGroup(rgName)
                                       .WithNewPrimaryNetwork("10.0.0.0/28")
                                       .WithPrimaryPrivateIPAddressDynamic()
                                       .WithNewPrimaryPublicIPAddress(publicIPDnsLabel)
                                       .WithPopularLinuxImage(KnownLinuxVirtualMachineImage.UbuntuServer16_04_Lts)
                                       .WithRootUsername(vmUserName)
                                       .WithRootPassword(vmPassword)
                                       .WithSize(VirtualMachineSizeTypes.Parse("Standard_D2a_v4"))
                                       .Create();

            Utilities.Log("Created Azure Virtual Machine: " + dockerVM.Id);

            // Get the IP of the Docker host
            INicIPConfiguration nicIPConfiguration = dockerVM.GetPrimaryNetworkInterface().PrimaryIPConfiguration;
            IPublicIPAddress    publicIp           = nicIPConfiguration.GetPublicIPAddress();
            string dockerHostIP = publicIp.IPAddress;

            DockerClient dockerClient = InstallDocker(dockerHostIP, vmUserName, vmPassword);

            return(dockerClient);
        }
Пример #2
0
        public async Task GetVmVn()
        {
            var allvms = await azure.VirtualMachines.ListAsync();

            IVirtualMachine targetvm = allvms
                                       .Where(vm => vm.Name == "Annvm")
                                       .SingleOrDefault();

            Console.WriteLine(targetvm?.Id);

            INetworkInterface targetnic = targetvm.GetPrimaryNetworkInterface();

            INicIPConfiguration targetipconfig = targetnic.PrimaryIPConfiguration;

            IPublicIPAddress targetipaddress = targetipconfig.GetPublicIPAddress();

            Console.WriteLine($"IP Address:\t{targetipaddress.IPAddress}");
            Console.WriteLine("Press any key to exit.");
            Console.ReadLine();
        }
        /// <summary>
        /// Deletes virtual machine.
        /// </summary>
        /// <param name="name">Name of the virtual machine</param>
        /// <param name="resourceGroup">Name of the resource group.</param>
        /// <param name="deleteAll">true to remove all the resources associated with the virtual machine.</param>
        /// <returns></returns>
        public async Task Del(string name, string resourceGroup, bool deleteAll = false)
        {
            IVirtualMachine vmInstance = this.Get(name, resourceGroup);

            string        osDiskId            = vmInstance.OSDiskId;
            string        priNetworkInterface = vmInstance.GetPrimaryNetworkInterface().Id;
            string        publicIPAddress     = vmInstance.GetPrimaryPublicIPAddressId();
            List <string> virtualNetworkNames = new List <string>();

            var networkInterface          = new NetworkInterfaces(this.credentials, this.subscriptionId);
            INetworkInterface nwInterface = networkInterface.Get(priNetworkInterface);
            var ipConfigs = nwInterface.IPConfigurations;

            foreach (var k in ipConfigs.Keys)
            {
                virtualNetworkNames.Add(ipConfigs[k].GetNetwork().Name);
            }

            azure.VirtualMachines.DeleteById(this.getId(name, resourceGroup));

            if (deleteAll)
            {
                Disks disks = new Disks(this.credentials, this.subscriptionId);
                disks.Del(osDiskId);

                var oNetworkInterface = new NetworkInterfaces(this.credentials, this.subscriptionId);
                oNetworkInterface.Del(priNetworkInterface);

                var oPublicIPAddress = new PublicIPAddresses(this.credentials, this.subscriptionId);
                oPublicIPAddress.Del(publicIPAddress);

                var virtualNetworks = new VirtualNetworks(this.credentials, this.subscriptionId);

                foreach (var n in virtualNetworkNames)
                {
                    await virtualNetworks.Del(n, resourceGroup);
                }
            }
        }
Пример #4
0
        public void CanCRUDLocks()
        {
            using (var context = FluentMockContext.Start(GetType().FullName))
            {
                IAuthorizationManager authorizationManager = TestHelper.CreateAuthorizationManager();
                IComputeManager       computeManager       = TestHelper.CreateComputeManager();
                IResourceManager      managerResources     = computeManager.ResourceManager;
                INetworkManager       networkManager       = TestHelper.CreateNetworkManager();
                IStorageManager       storageManager       = TestHelper.CreateStorageManager();

                // Prepare a VM
                string password    = SdkContext.RandomResourceName("P@s", 14);
                string rgName      = SdkContext.RandomResourceName("rg", 15);
                string vmName      = SdkContext.RandomResourceName("vm", 15);
                string storageName = SdkContext.RandomResourceName("st", 15);
                string diskName    = SdkContext.RandomResourceName("dsk", 15);
                string netName     = SdkContext.RandomResourceName("net", 15);
                Region region      = Region.USEast;

                IResourceGroup  resourceGroup = null;
                IManagementLock lockGroup     = null,
                                lockVM        = null,
                                lockStorage   = null,
                                lockDiskRO    = null,
                                lockDiskDel   = null,
                                lockSubnet    = null;

                try
                {
                    resourceGroup = managerResources.ResourceGroups.Define(rgName)
                                    .WithRegion(region)
                                    .Create();
                    Assert.NotNull(resourceGroup);

                    ICreatable <INetwork> netDefinition = networkManager.Networks.Define(netName)
                                                          .WithRegion(region)
                                                          .WithExistingResourceGroup(resourceGroup)
                                                          .WithAddressSpace("10.0.0.0/28");

                    // Define a VM for testing VM locks
                    ICreatable <IVirtualMachine> vmDefinition = computeManager.VirtualMachines.Define(vmName)
                                                                .WithRegion(region)
                                                                .WithExistingResourceGroup(resourceGroup)
                                                                .WithNewPrimaryNetwork(netDefinition)
                                                                .WithPrimaryPrivateIPAddressDynamic()
                                                                .WithoutPrimaryPublicIPAddress()
                                                                .WithPopularWindowsImage(KnownWindowsVirtualMachineImage.WindowsServer2012R2Datacenter)
                                                                .WithAdminUsername("tester")
                                                                .WithAdminPassword(password)
                                                                .WithSize(VirtualMachineSizeTypes.BasicA1);

                    // Define a managed disk for testing locks on that
                    ICreatable <IDisk> diskDefinition = computeManager.Disks.Define(diskName)
                                                        .WithRegion(region)
                                                        .WithExistingResourceGroup(resourceGroup)
                                                        .WithData()
                                                        .WithSizeInGB(100);

                    // Define a storage account for testing locks on that
                    ICreatable <IStorageAccount> storageDefinition = storageManager.StorageAccounts.Define(storageName)
                                                                     .WithRegion(region)
                                                                     .WithExistingResourceGroup(resourceGroup);

                    // Create resources in parallel to save time and money
                    Extensions.Synchronize(() => Task.WhenAll(
                                               storageDefinition.CreateAsync(),
                                               vmDefinition.CreateAsync(),
                                               diskDefinition.CreateAsync()));

                    IVirtualMachine vm      = (IVirtualMachine)vmDefinition;
                    IStorageAccount storage = (IStorageAccount)storageDefinition;
                    IDisk           disk    = (IDisk)diskDefinition;
                    INetwork        network = vm.GetPrimaryNetworkInterface().PrimaryIPConfiguration.GetNetwork();
                    ISubnet         subnet  = network.Subnets.Values.FirstOrDefault();

                    // Lock subnet
                    ICreatable <IManagementLock> lockSubnetDef = authorizationManager.ManagementLocks.Define("subnetLock")
                                                                 .WithLockedResource(subnet.Inner.Id)
                                                                 .WithLevel(LockLevel.ReadOnly);

                    // Lock VM
                    ICreatable <IManagementLock> lockVMDef = authorizationManager.ManagementLocks.Define("vmlock")
                                                             .WithLockedResource(vm)
                                                             .WithLevel(LockLevel.ReadOnly)
                                                             .WithNotes("vm readonly lock");

                    // Lock resource group
                    ICreatable <IManagementLock> lockGroupDef = authorizationManager.ManagementLocks.Define("rglock")
                                                                .WithLockedResource(resourceGroup.Id)
                                                                .WithLevel(LockLevel.CanNotDelete);

                    // Lock storage
                    ICreatable <IManagementLock> lockStorageDef = authorizationManager.ManagementLocks.Define("stLock")
                                                                  .WithLockedResource(storage)
                                                                  .WithLevel(LockLevel.CanNotDelete);

                    // Create locks in parallel
                    ICreatedResources <IManagementLock> created = authorizationManager.ManagementLocks.Create(lockVMDef, lockGroupDef, lockStorageDef, lockSubnetDef);

                    lockVM      = created.FirstOrDefault(o => o.Key.Equals(lockVMDef.Key));
                    lockStorage = created.FirstOrDefault(o => o.Key.Equals(lockStorageDef.Key));
                    lockGroup   = created.FirstOrDefault(o => o.Key.Equals(lockGroupDef.Key));
                    lockSubnet  = created.FirstOrDefault(o => o.Key.Equals(lockSubnetDef.Key));

                    // Lock disk synchronously
                    lockDiskRO = authorizationManager.ManagementLocks.Define("diskLockRO")
                                 .WithLockedResource(disk)
                                 .WithLevel(LockLevel.ReadOnly)
                                 .Create();

                    lockDiskDel = authorizationManager.ManagementLocks.Define("diskLockDel")
                                  .WithLockedResource(disk)
                                  .WithLevel(LockLevel.CanNotDelete)
                                  .Create();

                    // Verify VM lock
                    Assert.Equal(2, authorizationManager.ManagementLocks.ListForResource(vm.Id).Count());

                    Assert.NotNull(lockVM);
                    lockVM = authorizationManager.ManagementLocks.GetById(lockVM.Id);
                    Assert.NotNull(lockVM);
                    Assert.Equal(LockLevel.ReadOnly, lockVM.Level);
                    Assert.Equal(vm.Id, lockVM.LockedResourceId, true);

                    // Verify resource group lock
                    Assert.NotNull(lockGroup);
                    lockGroup = authorizationManager.ManagementLocks.GetByResourceGroup(resourceGroup.Name, "rglock");
                    Assert.NotNull(lockGroup);
                    Assert.Equal(LockLevel.CanNotDelete, lockGroup.Level);
                    Assert.Equal(resourceGroup.Id, lockGroup.LockedResourceId, true);

                    // Verify storage account lock
                    Assert.Equal(2, authorizationManager.ManagementLocks.ListForResource(storage.Id).Count());

                    Assert.NotNull(lockStorage);
                    lockStorage = authorizationManager.ManagementLocks.GetById(lockStorage.Id);
                    Assert.NotNull(lockStorage);
                    Assert.Equal(LockLevel.CanNotDelete, lockStorage.Level);
                    Assert.Equal(storage.Id, lockStorage.LockedResourceId, true);

                    // Verify disk lock
                    Assert.Equal(3, authorizationManager.ManagementLocks.ListForResource(disk.Id).Count());

                    Assert.NotNull(lockDiskRO);
                    lockDiskRO = authorizationManager.ManagementLocks.GetById(lockDiskRO.Id);
                    Assert.NotNull(lockDiskRO);
                    Assert.Equal(LockLevel.ReadOnly, lockDiskRO.Level);
                    Assert.Equal(disk.Id, lockDiskRO.LockedResourceId, true);

                    Assert.NotNull(lockDiskDel);
                    lockDiskDel = authorizationManager.ManagementLocks.GetById(lockDiskDel.Id);
                    Assert.NotNull(lockDiskDel);
                    Assert.Equal(LockLevel.CanNotDelete, lockDiskDel.Level);
                    Assert.Equal(disk.Id, lockDiskDel.LockedResourceId, true);

                    // Verify subnet lock
                    Assert.Equal(2, authorizationManager.ManagementLocks.ListForResource(network.Id).Count());

                    lockSubnet = authorizationManager.ManagementLocks.GetById(lockSubnet.Id);
                    Assert.NotNull(lockSubnet);
                    Assert.Equal(LockLevel.ReadOnly, lockSubnet.Level);
                    Assert.Equal(subnet.Inner.Id, lockSubnet.LockedResourceId, true);

                    // Verify lock collection
                    var locksSubscription = authorizationManager.ManagementLocks.List();
                    var locksGroup        = authorizationManager.ManagementLocks.ListByResourceGroup(vm.ResourceGroupName);
                    Assert.NotNull(locksSubscription);
                    Assert.NotNull(locksGroup);

                    int locksAllCount = locksSubscription.Count();
                    Assert.True(6 <= locksAllCount);

                    int locksGroupCount = locksGroup.Count();
                    Assert.Equal(6, locksGroup.Count());
                }
                finally
                {
                    try
                    {
                        if (resourceGroup != null)
                        {
                            if (lockGroup != null)
                            {
                                authorizationManager.ManagementLocks.DeleteById(lockGroup.Id);
                            }
                            if (lockVM != null)
                            {
                                authorizationManager.ManagementLocks.DeleteById(lockVM.Id);
                            }
                            if (lockDiskRO != null)
                            {
                                authorizationManager.ManagementLocks.DeleteById(lockDiskRO.Id);
                            }
                            if (lockDiskDel != null)
                            {
                                authorizationManager.ManagementLocks.DeleteById(lockDiskDel.Id);
                            }
                            if (lockStorage != null)
                            {
                                authorizationManager.ManagementLocks.DeleteById(lockStorage.Id);
                            }
                            if (lockSubnet != null)
                            {
                                authorizationManager.ManagementLocks.DeleteById(lockSubnet.Id);
                            }

                            managerResources.ResourceGroups.BeginDeleteByName(rgName);
                        }
                    }
                    catch { }
                }
            }
        }
        public void CanCreateWithNetworking()
        {
            using (var context = FluentMockContext.Start(GetType().FullName))
            {
                var GroupName       = TestUtilities.GenerateName("rgfluentchash-");
                var NsgName         = TestUtilities.GenerateName("nsg");
                var NetworkName     = TestUtilities.GenerateName("net");
                var VMName          = TestUtilities.GenerateName("vm");
                var computeManager  = TestHelper.CreateComputeManager();
                var resourceManager = TestHelper.CreateResourceManager();
                var networkManager  = TestHelper.CreateNetworkManager();

                try
                {
                    var nsg = networkManager.NetworkSecurityGroups.Define(NsgName)
                              .WithRegion(Location)
                              .WithNewResourceGroup(GroupName)
                              .DefineRule("rule1")
                              .AllowInbound()
                              .FromAnyAddress()
                              .FromPort(80)
                              .ToAnyAddress()
                              .ToPort(80)
                              .WithProtocol(SecurityRuleProtocol.Tcp)
                              .Attach()
                              .Create();

                    ICreatable <INetwork> networkDefinition = networkManager.Networks.Define(NetworkName)
                                                              .WithRegion(Location)
                                                              .WithExistingResourceGroup(GroupName)
                                                              .WithAddressSpace("10.0.0.0/28")
                                                              .DefineSubnet("subnet1")
                                                              .WithAddressPrefix("10.0.0.0/29")
                                                              .WithExistingNetworkSecurityGroup(nsg)
                                                              .Attach();

                    // Create
                    IVirtualMachine vm = computeManager.VirtualMachines.Define(VMName)
                                         .WithRegion(Location)
                                         .WithExistingResourceGroup(GroupName)
                                         .WithNewPrimaryNetwork(networkDefinition)
                                         .WithPrimaryPrivateIPAddressDynamic()
                                         .WithoutPrimaryPublicIPAddress()
                                         .WithPopularLinuxImage(KnownLinuxVirtualMachineImage.UbuntuServer16_04_Lts)
                                         .WithRootUsername("Foo12")
                                         .WithRootPassword("abc!@#F0orL")
                                         .Create();

                    var primaryNic = vm.GetPrimaryNetworkInterface();
                    Assert.NotNull(primaryNic);
                    var primaryIpConfig = primaryNic.PrimaryIPConfiguration;
                    Assert.NotNull(primaryIpConfig);

                    // Fetch the NSG the way before v1.2
                    Assert.NotNull(primaryIpConfig.NetworkId);
                    var network = primaryIpConfig.GetNetwork();
                    Assert.NotNull(primaryIpConfig.SubnetName);
                    ISubnet subnet = null;
                    network.Subnets.TryGetValue(primaryIpConfig.SubnetName, out subnet);
                    Assert.NotNull(subnet);
                    nsg = subnet.GetNetworkSecurityGroup();
                    Assert.NotNull(nsg);
                    Assert.Equal(NsgName, nsg.Name);
                    Assert.Equal(1, nsg.SecurityRules.Count);

                    // Fetch the NSG the v1.2 way
                    nsg = primaryIpConfig.GetNetworkSecurityGroup();
                    Assert.Equal(NsgName, nsg.Name);
                }
                finally
                {
                    try
                    {
                        resourceManager.ResourceGroups.BeginDeleteByName(GroupName);
                    }
                    catch { }
                }
            }
        }
        /**
         * Azure sample for applying locks to resources
         *
         * Summary ...
         *
         * This sample shows examples of management locks usage on various resources.
         *
         * Details ...
         *
         * 1. Create a number of various resources to apply locks to...
         * 2. Apply various locks to the resources
         * 3. Retrieve and show lock information
         * 4. Remove the locks and clean up
         */

        public static void RunSample(IAzure azure)
        {
            string password    = SdkContext.RandomResourceName("P@s", 14);
            string rgName      = SdkContext.RandomResourceName("rg", 15);
            string vmName      = SdkContext.RandomResourceName("vm", 15);
            string storageName = SdkContext.RandomResourceName("st", 15);
            string diskName    = SdkContext.RandomResourceName("dsk", 15);
            string netName     = SdkContext.RandomResourceName("net", 15);
            Region region      = Region.USEast;

            IResourceGroup  resourceGroup = null;
            IManagementLock lockGroup     = null,
                            lockVM        = null,
                            lockStorage   = null,
                            lockDiskRO    = null,
                            lockDiskDel   = null,
                            lockSubnet    = null;

            try
            {
                //=============================================================
                // Create a shared resource group for all the resources so they can all be deleted together
                //
                resourceGroup = azure.ResourceGroups.Define(rgName)
                                .WithRegion(region)
                                .Create();
                Utilities.Log("Created a new resource group - " + resourceGroup.Id);

                //============================================================
                // Create various resources for demonstrating locks
                //

                // Define a network to apply a lock to
                ICreatable <INetwork> netDefinition = azure.Networks.Define(netName)
                                                      .WithRegion(region)
                                                      .WithExistingResourceGroup(resourceGroup)
                                                      .WithAddressSpace("10.0.0.0/28");

                // Define a managed disk for testing locks on that
                ICreatable <IDisk> diskDefinition = azure.Disks.Define(diskName)
                                                    .WithRegion(region)
                                                    .WithExistingResourceGroup(resourceGroup)
                                                    .WithData()
                                                    .WithSizeInGB(100);

                // Define a VM to apply a lock to
                ICreatable <IVirtualMachine> vmDefinition = azure.VirtualMachines.Define(vmName)
                                                            .WithRegion(region)
                                                            .WithExistingResourceGroup(resourceGroup)
                                                            .WithNewPrimaryNetwork(netDefinition)
                                                            .WithPrimaryPrivateIPAddressDynamic()
                                                            .WithoutPrimaryPublicIPAddress()
                                                            .WithPopularWindowsImage(KnownWindowsVirtualMachineImage.WindowsServer2012Datacenter)
                                                            .WithAdminUsername("tester")
                                                            .WithAdminPassword(password)
                                                            .WithNewDataDisk(diskDefinition, 1, CachingTypes.None)
                                                            .WithSize(VirtualMachineSizeTypes.Parse("Standard_D2a_v4"));

                // Define a storage account to apply a lock to
                ICreatable <IStorageAccount> storageDefinition = azure.StorageAccounts.Define(storageName)
                                                                 .WithRegion(region)
                                                                 .WithExistingResourceGroup(resourceGroup);

                // Create resources in parallel to save time
                Utilities.Log("Creating the needed resources...");
                Task.WaitAll(
                    storageDefinition.CreateAsync(),
                    vmDefinition.CreateAsync());
                Utilities.Log("Resources created.");

                IVirtualMachine vm      = (IVirtualMachine)vmDefinition;
                IStorageAccount storage = (IStorageAccount)storageDefinition;
                IDisk           disk    = (IDisk)diskDefinition;
                INetwork        network = vm.GetPrimaryNetworkInterface().PrimaryIPConfiguration.GetNetwork();
                ISubnet         subnet  = network.Subnets.Values.FirstOrDefault();

                //============================================================
                // Create various locks for the created resources
                //

                // Locks can be created serially, and multiple can be applied to the same resource:
                Utilities.Log("Creating locks sequentially...");

                // Apply a ReadOnly lock to the disk
                lockDiskRO = azure.ManagementLocks.Define("diskLockRO")
                             .WithLockedResource(disk)
                             .WithLevel(LockLevel.ReadOnly)
                             .Create();

                // Apply a lock preventing the disk from being deleted
                lockDiskDel = azure.ManagementLocks.Define("diskLockDel")
                              .WithLockedResource(disk)
                              .WithLevel(LockLevel.CanNotDelete)
                              .Create();

                // Locks can also be created in parallel, for better overall performance:
                Utilities.Log("Creating locks in parallel...");

                // Define a subnet lock
                ICreatable <IManagementLock> lockSubnetDef = azure.ManagementLocks.Define("subnetLock")
                                                             .WithLockedResource(subnet.Inner.Id)
                                                             .WithLevel(LockLevel.ReadOnly);

                // Define a VM lock
                ICreatable <IManagementLock> lockVMDef = azure.ManagementLocks.Define("vmlock")
                                                         .WithLockedResource(vm)
                                                         .WithLevel(LockLevel.ReadOnly)
                                                         .WithNotes("vm readonly lock");

                // Define a resource group lock
                ICreatable <IManagementLock> lockGroupDef = azure.ManagementLocks.Define("rglock")
                                                            .WithLockedResource(resourceGroup.Id)
                                                            .WithLevel(LockLevel.CanNotDelete);

                // Define a storage lock
                ICreatable <IManagementLock> lockStorageDef = azure.ManagementLocks.Define("stLock")
                                                              .WithLockedResource(storage)
                                                              .WithLevel(LockLevel.CanNotDelete);

                var created = azure.ManagementLocks.Create(
                    lockVMDef,
                    lockGroupDef,
                    lockStorageDef,
                    lockSubnetDef);

                lockVM      = created.FirstOrDefault(o => o.Key.Equals(lockVMDef.Key, StringComparison.OrdinalIgnoreCase));
                lockStorage = created.FirstOrDefault(o => o.Key.Equals(lockStorageDef.Key, StringComparison.OrdinalIgnoreCase));
                lockGroup   = created.FirstOrDefault(o => o.Key.Equals(lockGroupDef.Key, StringComparison.OrdinalIgnoreCase));
                lockSubnet  = created.FirstOrDefault(o => o.Key.Equals(lockSubnetDef.Key, StringComparison.OrdinalIgnoreCase));

                Utilities.Log("Locks created.");

                //============================================================
                // Retrieve and show lock information
                //

                // Count and show locks (Note: locks returned for a resource include the locks for its resource group and child resources)
                int lockCount = azure.ManagementLocks.ListForResource(vm.Id).Count();
                Utilities.Log("Number of locks applied to the virtual machine: " + lockCount);
                lockCount = azure.ManagementLocks.ListByResourceGroup(resourceGroup.Name).Count();
                Utilities.Log("Number of locks applied to the resource group (includes locks on resources in the group): " + lockCount);
                lockCount = azure.ManagementLocks.ListForResource(storage.Id).Count();
                Utilities.Log("Number of locks applied to the storage account: " + lockCount);
                lockCount = azure.ManagementLocks.ListForResource(disk.Id).Count();
                Utilities.Log("Number of locks applied to the managed disk: " + lockCount);
                lockCount = azure.ManagementLocks.ListForResource(network.Id).Count();
                Utilities.Log("Number of locks applied to the network (including its subnets): " + lockCount);

                // Locks can be retrieved using their ID
                lockVM      = azure.ManagementLocks.GetById(lockVM.Id);
                lockGroup   = azure.ManagementLocks.GetByResourceGroup(resourceGroup.Name, "rglock");
                lockStorage = azure.ManagementLocks.GetById(lockStorage.Id);
                lockDiskRO  = azure.ManagementLocks.GetById(lockDiskRO.Id);
                lockDiskDel = azure.ManagementLocks.GetById(lockDiskDel.Id);
                lockSubnet  = azure.ManagementLocks.GetById(lockSubnet.Id);

                // Show the locks
                Utilities.Print(lockGroup);
                Utilities.Print(lockVM);
                Utilities.Print(lockDiskDel);
                Utilities.Print(lockDiskRO);
                Utilities.Print(lockStorage);
                Utilities.Print(lockSubnet);

                // List all locks within a subscription
                var locksSubscription = azure.ManagementLocks.List();
                Utilities.Log("Total number of locks within this subscription: " + locksSubscription.Count());
            }
            finally
            {
                try
                {
                    // Clean up (remember to unlock resources before deleting the resource group)
                    azure.ManagementLocks.DeleteByIds(
                        lockGroup.Id,
                        lockVM.Id,
                        lockDiskRO.Id,
                        lockDiskDel.Id,
                        lockStorage.Id,
                        lockSubnet.Id);
                    Utilities.Log("Starting the deletion of the resource group: " + rgName);
                    azure.ResourceGroups.BeginDeleteByName(rgName);
                }
                catch (NullReferenceException)
                {
                    Utilities.Log("Did not create any resources in Azure. No clean up is necessary");
                }
                catch (Exception ex)
                {
                    Utilities.Log(ex);
                }
            }
        }
Пример #7
0
        /**
         * Azure Network sample for managing network watcher -
         *  - Create Network Watcher
         *	- Manage packet capture – track traffic to and from a virtual machine
         *      Create a VM
         *      Start a packet capture
         *      Stop a packet capture
         *      Get a packet capture
         *      Delete a packet capture
         *  - Verify IP flow – verify if traffic is allowed to or from a virtual machine
         *      Get the IP address of a NIC on a virtual machine
         *      Test IP flow on the NIC
         *  - Analyze next hop – get the next hop type and IP address for a virtual machine
         *  - Retrieve network topology for a resource group
         *  - Analyze Virtual Machine Security by examining effective network security rules applied to a VM
         *      Get security group view for the VM
         *  - Configure Network Security Group Flow Logs
         *      Get flow log settings
         *      Enable NSG flow log
         *      Disable NSG flow log
         *  - Delete network watcher
         */
        public static void RunSample(IAzure azure)
        {
            string nwName = SdkContext.RandomResourceName("nw", 8);

            string          userName          = "******";
            string          vnetName          = SdkContext.RandomResourceName("vnet", 20);
            string          subnetName        = "subnet1";
            string          nsgName           = SdkContext.RandomResourceName("nsg", 20);
            string          dnsLabel          = SdkContext.RandomResourceName("pipdns", 20);
            string          rgName            = SdkContext.RandomResourceName("rg", 24);
            string          saName            = SdkContext.RandomResourceName("sa", 24);
            string          vmName            = SdkContext.RandomResourceName("vm", 24);
            string          packetCaptureName = SdkContext.RandomResourceName("pc", 8);
            INetworkWatcher nw = null;

            try
            {
                //============================================================
                // Create network watcher
                Utilities.Log("Creating network watcher...");
                nw = azure.NetworkWatchers.Define(nwName)
                     .WithRegion(region)
                     .WithNewResourceGroup()
                     .Create();

                Utilities.Log("Created network watcher");
                // Print the network watcher
                Utilities.Print(nw);

                //============================================================
                // Manage packet capture – track traffic to and from a virtual machine

                // Create network security group, virtual network and VM; add packetCapture extension to enable packet capture
                Utilities.Log("Creating network security group...");
                INetworkSecurityGroup nsg = azure.NetworkSecurityGroups.Define(nsgName)
                                            .WithRegion(region)
                                            .WithNewResourceGroup(rgName)
                                            .DefineRule("DenyInternetInComing")
                                            .DenyInbound()
                                            .FromAddress("INTERNET")
                                            .FromAnyPort()
                                            .ToAnyAddress()
                                            .ToPort(443)
                                            .WithAnyProtocol()
                                            .Attach()
                                            .Create();
                Utilities.Log("Creating virtual network...");
                ICreatable <INetwork> virtualNetwork = azure.Networks.Define(vnetName)
                                                       .WithRegion(region)
                                                       .WithExistingResourceGroup(rgName)
                                                       .WithAddressSpace("192.168.0.0/16")
                                                       .DefineSubnet(subnetName)
                                                       .WithAddressPrefix("192.168.2.0/24")
                                                       .WithExistingNetworkSecurityGroup(nsg)
                                                       .Attach();
                Utilities.Log("Creating virtual machine...");
                IVirtualMachine vm = azure.VirtualMachines.Define(vmName)
                                     .WithRegion(region)
                                     .WithExistingResourceGroup(rgName)
                                     .WithNewPrimaryNetwork(virtualNetwork)
                                     .WithPrimaryPrivateIPAddressDynamic()
                                     .WithNewPrimaryPublicIPAddress(dnsLabel)
                                     .WithPopularLinuxImage(KnownLinuxVirtualMachineImage.UbuntuServer14_04_Lts)
                                     .WithRootUsername(userName)
                                     .WithRootPassword("Abcdef.123456")
                                     .WithSize(VirtualMachineSizeTypes.Parse("Standard_D2a_v4"))
                                     .DefineNewExtension("packetCapture")
                                     .WithPublisher("Microsoft.Azure.NetworkWatcher")
                                     .WithType("NetworkWatcherAgentLinux")
                                     .WithVersion("1.4")
                                     .WithMinorVersionAutoUpgrade()
                                     .Attach()
                                     .Create();

                // Create storage account
                Utilities.Log("Creating storage account...");
                IStorageAccount storageAccount = azure.StorageAccounts.Define(saName)
                                                 .WithRegion(region)
                                                 .WithExistingResourceGroup(rgName)
                                                 .Create();

                // Start a packet capture
                Utilities.Log("Creating packet capture...");
                IPacketCapture packetCapture = nw.PacketCaptures
                                               .Define(packetCaptureName)
                                               .WithTarget(vm.Id)
                                               .WithStorageAccountId(storageAccount.Id)
                                               .WithTimeLimitInSeconds(1500)
                                               .DefinePacketCaptureFilter()
                                               .WithProtocol(PcProtocol.TCP)
                                               .Attach()
                                               .Create();
                Utilities.Log("Created packet capture");
                Utilities.Print(packetCapture);

                // Stop a packet capture
                Utilities.Log("Stopping packet capture...");
                packetCapture.Stop();
                Utilities.Print(packetCapture);

                // Get a packet capture
                Utilities.Log("Getting packet capture...");
                IPacketCapture packetCapture1 = nw.PacketCaptures.GetByName(packetCaptureName);
                Utilities.Print(packetCapture1);

                // Delete a packet capture
                Utilities.Log("Deleting packet capture");
                nw.PacketCaptures.DeleteByName(packetCapture.Name);

                //============================================================
                // Verify IP flow – verify if traffic is allowed to or from a virtual machine
                // Get the IP address of a NIC on a virtual machine
                String ipAddress = vm.GetPrimaryNetworkInterface().PrimaryPrivateIP;
                // Test IP flow on the NIC
                Utilities.Log("Verifying IP flow for vm id " + vm.Id + "...");
                IVerificationIPFlow verificationIPFlow = nw.VerifyIPFlow()
                                                         .WithTargetResourceId(vm.Id)
                                                         .WithDirection(Direction.Outbound)
                                                         .WithProtocol(IpFlowProtocol.TCP)
                                                         .WithLocalIPAddress(ipAddress)
                                                         .WithRemoteIPAddress("8.8.8.8")
                                                         .WithLocalPort("443")
                                                         .WithRemotePort("443")
                                                         .Execute();
                Utilities.Print(verificationIPFlow);

                //============================================================
                // Analyze next hop – get the next hop type and IP address for a virtual machine
                Utilities.Log("Calculating next hop...");
                INextHop nextHop = nw.NextHop().WithTargetResourceId(vm.Id)
                                   .WithSourceIPAddress(ipAddress)
                                   .WithDestinationIPAddress("8.8.8.8")
                                   .Execute();
                Utilities.Print(nextHop);

                //============================================================
                // Retrieve network topology for a resource group
                Utilities.Log("Getting topology...");
                ITopology topology = nw.Topology()
                                     .WithTargetResourceGroup(rgName)
                                     .Execute();
                Utilities.Print(topology);

                //============================================================
                // Analyze Virtual Machine Security by examining effective network security rules applied to a VM
                // Get security group view for the VM
                Utilities.Log("Getting security group view for a vm");
                ISecurityGroupView sgViewResult = nw.GetSecurityGroupView(vm.Id);
                Utilities.Print(sgViewResult);

                //============================================================
                // Configure Network Security Group Flow Logs

                // Get flow log settings
                IFlowLogSettings flowLogSettings = nw.GetFlowLogSettings(nsg.Id);
                Utilities.Print(flowLogSettings);

                // Enable NSG flow log
                flowLogSettings.Update()
                .WithLogging()
                .WithStorageAccount(storageAccount.Id)
                .WithRetentionPolicyDays(5)
                .WithRetentionPolicyEnabled()
                .Apply();
                Utilities.Print(flowLogSettings);

                // Disable NSG flow log
                flowLogSettings.Update()
                .WithoutLogging()
                .Apply();
                Utilities.Print(flowLogSettings);

                //============================================================
                // Delete network watcher
                Utilities.Log("Deleting network watcher");
                azure.NetworkWatchers.DeleteById(nw.Id);
                Utilities.Log("Deleted network watcher");
            }
            finally
            {
                try
                {
                    Utilities.Log("Deleting Resource Group: " + rgName);
                    azure.ResourceGroups.BeginDeleteByName(rgName);
                    if (nw != null)
                    {
                        Utilities.Log("Deleting network watcher resource group: " + nw.ResourceGroupName);
                        azure.ResourceGroups.BeginDeleteByName(nw.ResourceGroupName);
                    }
                }
                catch (NullReferenceException)
                {
                    Utilities.Log("Did not create any resources in Azure. No clean up is necessary");
                }
                catch (Exception ex)
                {
                    Utilities.Log(ex);
                }
            }
        }
        /**
         * Azure Network sample for enabling and updating network peering between two virtual networks
         *
         * Summary ...
         *
         * - This sample uses Azure Network Watcher's connectivity check to verify connectivity between
         *   two peered virtual networks.
         *
         * Details ...
         *
         * 1. Define two virtual networks network "A" and network "B" with one subnet each
         *
         * 2. Create two virtual machines, each within a separate network
         *   - The virtual machines currently must use a special extension to support Network Watcher
         *
         * 3. Peer the networks...
         *   - the peering will initially have default settings:
         *   - each network's IP address spaces will be accessible from the other network
         *   - no traffic forwarding will be enabled between the networks
         *   - no gateway transit between one network and the other will be enabled
         *
         * 4. Use Network Watcher to check connectivity between the virtual machines in different peering scenarios:
         *   - both virtual machines accessible to each other (bi-directional)
         *   - virtual machine A accessible to virtual machine B, but not the other way
         */

        public static void RunSample(IAzure azure)
        {
            Region region            = Region.USEast;
            string resourceGroupName = SdkContext.RandomResourceName("rg", 15);
            string vnetAName         = SdkContext.RandomResourceName("net", 15);
            string vnetBName         = SdkContext.RandomResourceName("net", 15);

            string[] vmNames       = SdkContext.RandomResourceNames("vm", 15, 2);
            string[] vmIPAddresses = new String[] {
                /* within subnetA */ "10.0.0.8",
                /* within subnetB */ "10.1.0.8"
            };

            string peeringABName      = SdkContext.RandomResourceName("peer", 15);
            string rootname           = "tirekicker";
            string password           = SdkContext.RandomResourceName("pWd!", 15);
            string networkWatcherName = SdkContext.RandomResourceName("netwch", 20);

            try
            {
                //=============================================================
                // Define two virtual networks to peer and put the virtual machines in, at specific IP addresses

                List <ICreatable <INetwork> > networkDefinitions = new List <ICreatable <INetwork> >();
                networkDefinitions.Add(azure.Networks.Define(vnetAName)
                                       .WithRegion(region)
                                       .WithNewResourceGroup(resourceGroupName)
                                       .WithAddressSpace("10.0.0.0/27")
                                       .WithSubnet("subnetA", "10.0.0.0/27"));

                networkDefinitions.Add(azure.Networks.Define(vnetBName)
                                       .WithRegion(region)
                                       .WithNewResourceGroup(resourceGroupName)
                                       .WithAddressSpace("10.1.0.0/27")
                                       .WithSubnet("subnetB", "10.1.0.0/27"));

                //=============================================================
                // Define a couple of Windows VMs and place them in each of the networks

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

                for (int i = 0; i < networkDefinitions.Count; i++)
                {
                    vmDefinitions.Add(azure.VirtualMachines.Define(vmNames[i])
                                      .WithRegion(region)
                                      .WithExistingResourceGroup(resourceGroupName)
                                      .WithNewPrimaryNetwork(networkDefinitions[i])
                                      .WithPrimaryPrivateIPAddressStatic(vmIPAddresses[i])
                                      .WithoutPrimaryPublicIPAddress()
                                      .WithPopularWindowsImage(KnownWindowsVirtualMachineImage.WindowsServer2012R2Datacenter)
                                      .WithAdminUsername(rootname)
                                      .WithAdminPassword(password)

                                      // Extension currently needed for network watcher support
                                      .DefineNewExtension("packetCapture")
                                      .WithPublisher("Microsoft.Azure.NetworkWatcher")
                                      .WithType("NetworkWatcherAgentWindows")
                                      .WithVersion("1.4")
                                      .Attach());
                }

                // Create the VMs in parallel for better performance
                Utilities.Log("Creating virtual machines and virtual networks...");
                var             createdVMs = azure.VirtualMachines.Create(vmDefinitions);
                IVirtualMachine vmA        = createdVMs.FirstOrDefault(vm => vm.Key == vmDefinitions[0].Key);
                IVirtualMachine vmB        = createdVMs.FirstOrDefault(vm => vm.Key == vmDefinitions[1].Key);
                Utilities.Log("Created the virtual machines and networks.");

                //=============================================================
                // Peer the two networks using default settings

                INetwork networkA = vmA.GetPrimaryNetworkInterface().PrimaryIPConfiguration.GetNetwork();
                INetwork networkB = vmB.GetPrimaryNetworkInterface().PrimaryIPConfiguration.GetNetwork();

                Utilities.PrintVirtualNetwork(networkA);
                Utilities.PrintVirtualNetwork(networkB);

                Utilities.Log(
                    "Peering the networks using default settings...\n"
                    + "- Network access enabled\n"
                    + "- Traffic forwarding disabled\n"
                    + "- Gateway use (transit) by the remote network disabled");

                INetworkPeering peeringAB = networkA.Peerings.Define(peeringABName)
                                            .WithRemoteNetwork(networkB)
                                            .Create();

                Utilities.PrintVirtualNetwork(networkA);
                Utilities.PrintVirtualNetwork(networkB);

                //=============================================================
                // Check connectivity between the two VMs/networks using Network Watcher
                INetworkWatcher networkWatcher = azure.NetworkWatchers.Define(networkWatcherName)
                                                 .WithRegion(region)
                                                 .WithExistingResourceGroup(resourceGroupName)
                                                 .Create();

                // Verify bi-directional connectivity between the VMs on port 22 (SSH enabled by default on Linux VMs)
                IExecutable <IConnectivityCheck> connectivityAtoB = networkWatcher.CheckConnectivity()
                                                                    .ToDestinationAddress(vmIPAddresses[1])
                                                                    .ToDestinationPort(22)
                                                                    .FromSourceVirtualMachine(vmA);
                Utilities.Log("Connectivity from A to B: " + connectivityAtoB.Execute().ConnectionStatus);

                IExecutable <IConnectivityCheck> connectivityBtoA = networkWatcher.CheckConnectivity()
                                                                    .ToDestinationAddress(vmIPAddresses[0])
                                                                    .ToDestinationPort(22)
                                                                    .FromSourceVirtualMachine(vmB);
                Utilities.Log("Connectivity from B to A: " + connectivityBtoA.Execute().ConnectionStatus);

                // Change the peering to allow access between A and B
                Utilities.Log("Changing the peering to disable access between A and B...");
                peeringAB.Update()
                .WithoutAccessFromEitherNetwork()
                .Apply();

                Utilities.PrintVirtualNetwork(networkA);
                Utilities.PrintVirtualNetwork(networkB);

                // Verify connectivity no longer possible between A and B
                Utilities.Log("Peering configuration changed.\nNow, A should be unreachable from B, and B should be unreachable from A...");
                Utilities.Log("Connectivity from A to B: " + connectivityAtoB.Execute().ConnectionStatus);
                Utilities.Log("Connectivity from B to A: " + connectivityBtoA.Execute().ConnectionStatus);
            }
            finally
            {
                try
                {
                    Utilities.Log("Deleting Resource Group: " + resourceGroupName);
                    azure.ResourceGroups.BeginDeleteByName(resourceGroupName);
                }
                catch (NullReferenceException)
                {
                    Utilities.Log("Did not create any resources in Azure. No clean up is necessary");
                }
                catch (Exception ex)
                {
                    Utilities.Log(ex);
                }
            }
        }