예제 #1
0
        public async Task SslStream_StreamToStream_Successive_ClientWrite_Success()
        {
            byte[]         recvBuf = new byte[_sampleMsg.Length];
            VirtualNetwork network = new VirtualNetwork();

            using (var clientStream = new VirtualNetworkStream(network, isServer: false))
                using (var serverStream = new VirtualNetworkStream(network, isServer: true))
                    using (var clientSslStream = new SslStream(clientStream, false, AllowAnyServerCertificate))
                        using (var serverSslStream = new SslStream(serverStream))
                        {
                            await DoHandshake(clientSslStream, serverSslStream);

                            await WriteAsync(clientSslStream, _sampleMsg, 0, _sampleMsg.Length)
                            .TimeoutAfter(TestConfiguration.PassingTestTimeoutMilliseconds);

                            int bytesRead = 0;
                            while (bytesRead < _sampleMsg.Length)
                            {
                                bytesRead += await ReadAsync(serverSslStream, recvBuf, bytesRead, _sampleMsg.Length - bytesRead)
                                             .TimeoutAfter(TestConfiguration.PassingTestTimeoutMilliseconds);
                            }

                            Assert.True(VerifyOutput(recvBuf, _sampleMsg), "verify first read data is as expected.");

                            await WriteAsync(clientSslStream, _sampleMsg, 0, _sampleMsg.Length)
                            .TimeoutAfter(TestConfiguration.PassingTestTimeoutMilliseconds);

                            bytesRead = 0;
                            while (bytesRead < _sampleMsg.Length)
                            {
                                bytesRead += await ReadAsync(serverSslStream, recvBuf, bytesRead, _sampleMsg.Length - bytesRead)
                                             .TimeoutAfter(TestConfiguration.PassingTestTimeoutMilliseconds);
                            }

                            Assert.True(VerifyOutput(recvBuf, _sampleMsg), "verify second read data is as expected.");
                        }
        }
        private (List <string> Log, bool Succeeded, Exception Error) Inspect(string where)
        {
            var command = $"lighthouse inspect --where {where}";

            var virtualNetwork = new VirtualNetwork();

            var typeFactory = new TypeFactory();

            typeFactory.Register <INetworkProvider>(() => virtualNetwork);

            var pingContainer = Substitute.For <ILighthouseServiceContainer>();

            virtualNetwork.Register(pingContainer);

            RemoteAppRunRequest receivedRequest = null;
            var returnValue = new RemoteAppRunHandle(Guid.NewGuid().ToString());

            pingContainer.HandleRequest <RemoteAppRunRequest, RemoteAppRunHandle>(Arg.Do <RemoteAppRunRequest>(r => receivedRequest = r)).Returns(returnValue);

            var consoleWrites = new List <string>();
            var runner        = new CommandLineRunner((log) => {
                consoleWrites.Add(log);
                Output.WriteLine(log);
            }, () => "no_console_reads", typeFactory);

            try
            {
                var returnCode = runner.Run(command.Split(" ").Skip(1));
                receivedRequest.Should().NotBeNull();

                return(consoleWrites, true, null);
            }
            catch (Exception e)
            {
                return(consoleWrites, false, e);
            }
        }
예제 #3
0
        public async Task NegotiateStream_StreamToStream_Successive_ClientWrite_Sync_Success()
        {
            byte[]         recvBuf   = new byte[s_sampleMsg.Length];
            VirtualNetwork network   = new VirtualNetwork();
            int            bytesRead = 0;

            using (var clientStream = new VirtualNetworkStream(network, isServer: false))
                using (var serverStream = new VirtualNetworkStream(network, isServer: true))
                    using (var client = new NegotiateStream(clientStream))
                        using (var server = new NegotiateStream(serverStream))
                        {
                            Assert.False(client.IsAuthenticated);
                            Assert.False(server.IsAuthenticated);

                            Task[] auth = new Task[2];
                            auth[0] = AuthenticateAsClientAsync(client, CredentialCache.DefaultNetworkCredentials, string.Empty);
                            auth[1] = AuthenticateAsServerAsync(server);

                            await TestConfiguration.WhenAllOrAnyFailedWithTimeout(auth);

                            client.Write(s_sampleMsg, 0, s_sampleMsg.Length);
                            server.Read(recvBuf, 0, s_sampleMsg.Length);

                            Assert.True(s_sampleMsg.SequenceEqual(recvBuf));

                            client.Write(s_sampleMsg, 0, s_sampleMsg.Length);

                            // Test partial sync read.
                            bytesRead = server.Read(recvBuf, 0, PartialBytesToRead);
                            Assert.Equal(PartialBytesToRead, bytesRead);

                            bytesRead = server.Read(recvBuf, PartialBytesToRead, s_sampleMsg.Length - PartialBytesToRead);
                            Assert.Equal(s_sampleMsg.Length - PartialBytesToRead, bytesRead);

                            Assert.True(s_sampleMsg.SequenceEqual(recvBuf));
                        }
        }
        public async Task NegotiateStream_EndReadEndWriteInvalidParameter_Throws()
        {
            byte[] recvBuf = new byte[s_sampleMsg.Length];
            var    network = new VirtualNetwork();

            using (var clientStream = new VirtualNetworkStream(network, isServer: false))
                using (var serverStream = new VirtualNetworkStream(network, isServer: true))
                    using (var client = new NegotiateStream(clientStream))
                        using (var server = new NegotiateStream(serverStream))
                        {
                            await TestConfiguration.WhenAllOrAnyFailedWithTimeout(
                                client.AuthenticateAsClientAsync(CredentialCache.DefaultNetworkCredentials, string.Empty),
                                server.AuthenticateAsServerAsync());

                            await TestConfiguration.WhenAllOrAnyFailedWithTimeout(
                                Task.Factory.FromAsync(client.BeginWrite,
                                                       (asyncResult) =>
                            {
                                NegotiateStream authStream = (NegotiateStream)asyncResult.AsyncState;
                                AssertExtensions.Throws <ArgumentNullException>(nameof(asyncResult), () => authStream.EndWrite(null));

                                IAsyncResult result = new MyAsyncResult();
                                AssertExtensions.Throws <ArgumentException>(nameof(asyncResult), () => authStream.EndWrite(result));
                            },
                                                       s_sampleMsg, 0, s_sampleMsg.Length, client),
                                Task.Factory.FromAsync(server.BeginRead,
                                                       (asyncResult) =>
                            {
                                NegotiateStream authStream = (NegotiateStream)asyncResult.AsyncState;
                                AssertExtensions.Throws <ArgumentNullException>(nameof(asyncResult), () => authStream.EndRead(null));

                                IAsyncResult result = new MyAsyncResult();
                                AssertExtensions.Throws <ArgumentException>(nameof(asyncResult), () => authStream.EndRead(result));
                            },
                                                       recvBuf, 0, s_sampleMsg.Length, server));
                        }
        }
예제 #5
0
        public async Task NewCode()
        {
#endif
            ArmClient armClient = new ArmClient(new DefaultAzureCredential());
            Subscription subscription = await armClient.GetDefaultSubscriptionAsync();
            ResourceGroup resourceGroup = await subscription.GetResourceGroups().GetAsync("abc");
            VirtualNetworkCollection virtualNetworkContainer = resourceGroup.GetVirtualNetworks();

            // Create VNet
            VirtualNetworkData vnet = new VirtualNetworkData()
            {
                Location = "westus",
            };
            vnet.AddressSpace.AddressPrefixes.Add("10.0.0.0/16");
            vnet.Subnets.Add(new SubnetData
            {
                Name = "mySubnet",
                AddressPrefix = "10.0.0.0/24",
            });

            ArmOperation<VirtualNetwork> vnetOperation = await virtualNetworkContainer.CreateOrUpdateAsync(true, "_vent", vnet);
            VirtualNetwork virtualNetwork = vnetOperation.Value;
            #endregion
        }
예제 #6
0
        public void NegotiateStream_StreamToStream_KerberosAuthInvalidUser_Failure()
        {
            if (!_isKrbAvailable)
            {
                _output.WriteLine("skipping NegotiateStream_StreamToStream_KerberosAuthInvalidUser_Failure");
                return;
            }

            VirtualNetwork network = new VirtualNetwork();

            using (var clientStream = new VirtualNetworkStream(network, isServer: false))
                using (var serverStream = new VirtualNetworkStream(network, isServer: true))
                    using (var client = new NegotiateStream(clientStream))
                        using (var server = new UnixGssFakeNegotiateStream(serverStream))
                        {
                            Assert.False(client.IsAuthenticated, "client is not authenticated by default");

                            string            user       = string.Format("{0}@{1}", TestConfiguration.KerberosUser, TestConfiguration.Realm);
                            string            target     = string.Format("{0}@{1}", TestConfiguration.HostTarget, TestConfiguration.Realm);
                            NetworkCredential credential = new NetworkCredential(user.Substring(1), _fixture.password);
                            Assert.ThrowsAsync <AuthenticationException>(() => client.AuthenticateAsClientAsync(credential, target));
                            Assert.ThrowsAsync <AuthenticationException>(() => server.AuthenticateAsServerAsync());
                        }
        }
예제 #7
0
        public async Task StreamToStream_ValidAuthentication_Success(NetworkCredential creds, string target)
        {
            var network = new VirtualNetwork();

            using (var clientStream = new VirtualNetworkStream(network, isServer: false))
                using (var serverStream = new VirtualNetworkStream(network, isServer: true))
                    using (var client = new NegotiateStream(clientStream))
                        using (var server = new NegotiateStream(serverStream))
                        {
                            Assert.False(client.IsAuthenticated);
                            Assert.False(server.IsAuthenticated);

                            Task[] auth = new Task[2];
                            auth[0] = client.AuthenticateAsClientAsync(creds, target);
                            auth[1] = server.AuthenticateAsServerAsync();

                            await WhenAllOrAnyFailedWithTimeout(auth);

                            VerifyStreamProperties(client, isServer: false, target);

                            string remoteName = creds.UserName + "@" + EnterpriseTestConfiguration.Realm;
                            VerifyStreamProperties(server, isServer: true, remoteName);
                        }
        }
        public async Task Read_InvokedSynchronously()
        {
            var network      = new VirtualNetwork();
            var clientStream = new PreReadWriteActionDelegatingStream(new VirtualNetworkStream(network, isServer: false));

            using (var clientSslStream = new SslStream(clientStream, false, AllowAnyServerCertificate))
                using (var serverSslStream = new SslStream(new VirtualNetworkStream(network, isServer: true)))
                {
                    await DoHandshake(clientSslStream, serverSslStream);

                    // Validate that the read call to the underlying stream is made as part of the
                    // synchronous call to the read method on SslStream, even if the method is async.
                    using (var tl = new ThreadLocal <int>())
                    {
                        await WriteAsync(serverSslStream, new byte[1], 0, 1);

                        tl.Value = 42;
                        clientStream.PreReadWriteAction = () => Assert.Equal(42, tl.Value);
                        Task t = ReadAsync(clientSslStream, new byte[1], 0, 1);
                        tl.Value = 0;
                        await t;
                    }
                }
        }
        public async Task GlobalSetUp()
        {
            var rgLro = await GlobalClient.GetDefaultSubscriptionAsync().Result.GetResourceGroups().CreateOrUpdateAsync(true, SessionRecording.GenerateAssetName("WebPubSubRG-"), new ResourceGroupData(AzureLocation.WestUS2));

            ResourceGroup rg = rgLro.Value;

            _resourceGroupIdentifier = rg.Id;
            _vnetName            = SessionRecording.GenerateAssetName("Vnet-");
            _privateEndPointName = SessionRecording.GenerateAssetName("PrivateEndPoint-");

            //create vnet
            var vnetData = new VirtualNetworkData()
            {
                Location     = "westus2",
                AddressSpace = new AddressSpace()
                {
                    AddressPrefixes = { "10.10.0.0/16", }
                },
                Subnets =
                {
                    new SubnetData()
                    {
                        Name = "subnet01", AddressPrefix = "10.10.1.0/24",
                    },
                    new SubnetData()
                    {
                        Name = "subnet02", AddressPrefix = "10.10.2.0/24", PrivateEndpointNetworkPolicies = "Disabled",
                    }
                },
            };
            var vnetLro = await rg.GetVirtualNetworks().CreateOrUpdateAsync(true, _vnetName, vnetData);

            _vnet = vnetLro.Value;

            await StopSessionRecordingAsync();
        }
예제 #10
0
        public static VirtualNetwork CreateVirtualNetwork(string vnetName, string subnetName, string resourceGroupName, string location, NetworkManagementClient client)
        {
            var vnet = new VirtualNetwork()
            {
                Location = location,

                AddressSpace = new AddressSpace()
                {
                    AddressPrefixes = new List <string>()
                    {
                        "10.0.0.0/16",
                    }
                },
                DhcpOptions = new DhcpOptions()
                {
                    DnsServers = new List <string>()
                    {
                        "10.1.1.1",
                        "10.1.2.4"
                    }
                },
                Subnets = new List <Subnet>()
                {
                    new Subnet()
                    {
                        Name          = subnetName,
                        AddressPrefix = "10.0.0.0/24",
                    }
                }
            };

            client.VirtualNetworks.CreateOrUpdate(resourceGroupName, vnetName, vnet);
            var getVnetResponse = client.VirtualNetworks.Get(resourceGroupName, vnetName);

            return(getVnetResponse);
        }
        private string CreateDefaultVNetWithSubnet(string virtualNetworkName, string subnetName, ApiManagementTestBase testBase)
        {
            var vnet = new VirtualNetwork()
            {
                Location = testBase.location,

                AddressSpace = new AddressSpace()
                {
                    AddressPrefixes = new List <string>()
                    {
                        "10.0.0.0/16",
                    }
                },
                Subnets = new List <Subnet>()
                {
                    new Subnet()
                    {
                        Name          = subnetName,
                        AddressPrefix = "10.0.1.0/24",
                        PrivateEndpointNetworkPolicies = "Disabled"
                    },
                }
            };

            // Put Vnet
            var putVnetResponse = testBase.networkClient.VirtualNetworks.CreateOrUpdate(testBase.rgName, virtualNetworkName, vnet);

            Assert.Equal("Succeeded", putVnetResponse.ProvisioningState);

            var getSubnetResponse = testBase.networkClient.Subnets.Get(testBase.rgName, virtualNetworkName, subnetName);

            Assert.NotNull(getSubnetResponse);
            Assert.NotNull(getSubnetResponse.Id);

            return(getSubnetResponse.Id);
        }
예제 #12
0
 protected VirtualNetwork CreateVirtualNetwork(string resourceGroupName, string vnetName, string subnetName)
 {
     try
     {
         // Create the resource Group.
         var resourceGroup = m_ResourcesClient.ResourceGroups.CreateOrUpdate(
             resourceGroupName,
             new ResourceGroup
         {
             Location = m_location,
             Tags     = new Dictionary <string, string>()
             {
                 { resourceGroupName, DateTime.UtcNow.ToString("u") }
             }
         });
         VirtualNetwork vnetParams = GenerateVnetModel(vnetName, subnetName);
         return(m_NrpClient.VirtualNetworks.CreateOrUpdate(resourceGroupName, vnetName, vnetParams));
     }
     catch
     {
         m_ResourcesClient.ResourceGroups.Delete(resourceGroupName);
         throw;
     }
 }
예제 #13
0
    public MyStack()
    {
        _Subnets    = new Dictionary <string, Subnet>();
        _foodVmNics = new List <NetworkInterface>();

        // Create an Azure Resource Group
        _ResourceGroup = new ResourceGroup("rsgMarketPlace", new ResourceGroupArgs
        {
            Location = Location,
            Name     = "rsgMarketPlace"
        }, new CustomResourceOptions
        {
            Protect = true
        });

        _vnet = BuildVNet();

        _stgPrimaryEndpoint = BuildBootDiagStorageAccount();

        BuildNSG();

        BuildSupplierVMs(3);

        BuildFoodVMs(2);
        BuildClothingVMs(1);
        BuildFarmingVMs(1);
        BuildGardenVMs(1);
        BuildFoodLoadBalancer();
        //BuildFirewall();
        //BuildRouteTable();
        //BuildAppGateway();

        //new CosmosDB(_ResourceGroup).BuildCosmosDb();

        new SecondRegion(_vnet);
    }
예제 #14
0
        public async Task GlobalSetUp()
        {
            Subscription subscription = await GlobalClient.GetDefaultSubscriptionAsync();
            var rgLro = await subscription.GetResourceGroups().CreateOrUpdateAsync(SessionRecording.GenerateAssetName("FirewallRG-"), new ResourceGroupData(Location.WestUS2));
            ResourceGroup rg = rgLro.Value;
            _resourceGroupIdentifier = rg.Id;

            VirtualNetworkData vnetData = new VirtualNetworkData()
            {
                Location = Location.WestUS2,
                AddressSpace = new AddressSpace()
                {
                    AddressPrefixes = { "10.20.0.0/16", }
                },
                Subnets = {
                    new SubnetData() { Name = "Default", AddressPrefix = "10.20.1.0/26", },
                    new SubnetData() { Name = "AzureFirewallSubnet", AddressPrefix = "10.20.2.0/26", },
                },
            };
            var vnetLro = await rg.GetVirtualNetworks().CreateOrUpdateAsync(SessionRecording.GenerateAssetName("vnet-"), vnetData);
            _network = vnetLro.Value;
            _networkIdentifier = _network.Id;

            PublicIPAddressData ipData = new PublicIPAddressData()
            {
                Location = Location.WestUS2,
                PublicIPAllocationMethod = IPAllocationMethod.Static,
                Sku = new PublicIPAddressSku() { Name = PublicIPAddressSkuName.Standard },
            };
            var ipLro = await rg.GetPublicIPAddresses().CreateOrUpdateAsync(SessionRecording.GenerateAssetName("publicIp-"), ipData);
            _publicIPAddress = ipLro.Value;
            _publicIPAddressIdentifier = _publicIPAddress.Id;

            _firewallName = SessionRecording.GenerateAssetName("firewall-");
            await StopSessionRecordingAsync();
        }
        public async Task <Response <VirtualNetwork> > GetAsync(string resourceGroupName, string virtualNetworkName, string expand = null, CancellationToken cancellationToken = default)
        {
            if (resourceGroupName == null)
            {
                throw new ArgumentNullException(nameof(resourceGroupName));
            }
            if (virtualNetworkName == null)
            {
                throw new ArgumentNullException(nameof(virtualNetworkName));
            }

            using var message = CreateGetRequest(resourceGroupName, virtualNetworkName, expand);
            await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);

            switch (message.Response.Status)
            {
            case 200:
            {
                VirtualNetwork value = default;
                using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false);

                value = VirtualNetwork.DeserializeVirtualNetwork(document.RootElement);
                return(Response.FromValue(value, message.Response));
            }
예제 #16
0
        public async Task VirtualNetworkPeeringTest()
        {
            string resourceGroupName = Recording.GenerateAssetName("csmrg");

            string location      = TestEnvironment.Location;
            var    resourceGroup = await CreateResourceGroup(resourceGroupName);

            string vnet1Name   = Recording.GenerateAssetName("azsmnet");
            string vnet2Name   = Recording.GenerateAssetName("azsmnet");
            string subnet1Name = Recording.GenerateAssetName("azsmnet");
            string subnet2Name = Recording.GenerateAssetName("azsmnet");

            var vnet = new VirtualNetworkData()
            {
                Location = location,

                AddressSpace = new AddressSpace()
                {
                    AddressPrefixes = { "10.0.0.0/16", }
                },
                DhcpOptions = new DhcpOptions()
                {
                    DnsServers = { "10.1.1.1", "10.1.2.4" }
                },
                Subnets = { new SubnetData()
                            {
                                Name = subnet1Name, AddressPrefix = "10.0.1.0/24",
                            }, new SubnetData()
                            {
                                Name = subnet2Name, AddressPrefix = "10.0.2.0/24"
                            } }
            };

            // Put Vnet
            var virtualNetworkCollection = resourceGroup.GetVirtualNetworks();
            var putVnetResponseOperation = await virtualNetworkCollection.CreateOrUpdateAsync(true, vnet1Name, vnet);

            Response <VirtualNetwork> putVnetResponse = await putVnetResponseOperation.WaitForCompletionAsync();;

            Assert.AreEqual("Succeeded", putVnetResponse.Value.Data.ProvisioningState.ToString());

            // Get Vnet
            Response <VirtualNetwork> getVnetResponse = await virtualNetworkCollection.GetAsync(vnet1Name);

            Assert.AreEqual(vnet1Name, getVnetResponse.Value.Data.Name);
            Assert.NotNull(getVnetResponse.Value.Data.ResourceGuid);
            Assert.AreEqual("Succeeded", getVnetResponse.Value.Data.ProvisioningState.ToString());

            // Create vnet2
            var vnet2 = new VirtualNetworkData()
            {
                Location     = location,
                AddressSpace = new AddressSpace()
                {
                    AddressPrefixes = { "10.1.0.0/16", }
                },
                Subnets = { new SubnetData()
                            {
                                Name = subnet1Name, AddressPrefix = "10.1.1.0/24"
                            } }
            };

            // Put Vnet2
            var putVnet2Operation = await virtualNetworkCollection.CreateOrUpdateAsync(true, vnet2Name, vnet2);

            Response <VirtualNetwork> putVnet2 = await putVnet2Operation.WaitForCompletionAsync();;

            Assert.AreEqual("Succeeded", putVnet2.Value.Data.ProvisioningState.ToString());

            // Create peering object
            var peering = new VirtualNetworkPeeringData()
            {
                AllowForwardedTraffic = true,
                RemoteVirtualNetwork  = new WritableSubResource {
                    Id = putVnet2.Value.Id
                }
            };

            // Create Peering
            var virtualNetworkPeeringCollection = getVnetResponse.Value.GetVirtualNetworkPeerings();
            await virtualNetworkPeeringCollection.CreateOrUpdateAsync(true, "peer1", peering);

            // Get Peering
            VirtualNetworkPeering getPeer = await virtualNetworkPeeringCollection.GetAsync("peer1");

            Assert.AreEqual("peer1", getPeer.Data.Name);
            Assert.True(getPeer.Data.AllowForwardedTraffic);
            Assert.True(getPeer.Data.AllowVirtualNetworkAccess);
            Assert.False(getPeer.Data.AllowGatewayTransit);
            Assert.NotNull(getPeer.Data.RemoteVirtualNetwork);
            Assert.AreEqual(putVnet2.Value.Id, getPeer.Data.RemoteVirtualNetwork.Id);

            // List Peering
            AsyncPageable <VirtualNetworkPeering> listPeerAP = virtualNetworkPeeringCollection.GetAllAsync();
            List <VirtualNetworkPeering>          listPeer   = await listPeerAP.ToEnumerableAsync();

            Has.One.EqualTo(listPeer);
            Assert.AreEqual("peer1", listPeer[0].Data.Name);
            Assert.True(listPeer[0].Data.AllowForwardedTraffic);
            Assert.True(listPeer[0].Data.AllowVirtualNetworkAccess);
            Assert.False(listPeer[0].Data.AllowGatewayTransit);
            Assert.NotNull(listPeer[0].Data.RemoteVirtualNetwork);
            Assert.AreEqual(putVnet2.Value.Id, listPeer[0].Data.RemoteVirtualNetwork.Id);

            // Get peering from GET vnet
            VirtualNetwork peeringVnet = await virtualNetworkCollection.GetAsync(vnet1Name);

            Assert.AreEqual(vnet1Name, peeringVnet.Data.Name);
            Has.One.EqualTo(peeringVnet.Data.VirtualNetworkPeerings);
            Assert.AreEqual("peer1", peeringVnet.Data.VirtualNetworkPeerings[0].Name);
            Assert.True(peeringVnet.Data.VirtualNetworkPeerings[0].AllowForwardedTraffic);
            Assert.True(peeringVnet.Data.VirtualNetworkPeerings[0].AllowVirtualNetworkAccess);
            Assert.False(peeringVnet.Data.VirtualNetworkPeerings[0].AllowGatewayTransit);
            Assert.NotNull(peeringVnet.Data.VirtualNetworkPeerings[0].RemoteVirtualNetwork);
            Assert.AreEqual(putVnet2.Value.Id, peeringVnet.Data.VirtualNetworkPeerings[0].RemoteVirtualNetwork.Id);

            // Delete Peering
            var deleteOperation = await getPeer.DeleteAsync(true);

            await deleteOperation.WaitForCompletionResponseAsync();;

            listPeerAP = virtualNetworkPeeringCollection.GetAllAsync();
            listPeer   = await listPeerAP.ToEnumerableAsync();

            Assert.IsEmpty(listPeer);

            peeringVnet = await virtualNetworkCollection.GetAsync(vnet1Name);

            Assert.AreEqual(vnet1Name, peeringVnet.Data.Name);
            Assert.IsEmpty(peeringVnet.Data.VirtualNetworkPeerings);

            // Delete Vnets
            await putVnet2.Value.DeleteAsync(true);

            await putVnetResponse.Value.DeleteAsync(true);
        }
        public async Task CreateOrUpdate()
        {
            VirtualNetworkCollection virtualNetworkCollection = resourceGroup.GetVirtualNetworks();
            string vnetName = "myVnet";
            // Use the same location as the resource group
            VirtualNetworkData vnetInput = new VirtualNetworkData()
            {
                Location     = resourceGroup.Data.Location,
                AddressSpace = new AddressSpace()
                {
                    AddressPrefixes = { "10.0.0.0/16", }
                },
                DhcpOptions = new DhcpOptions()
                {
                    DnsServers = { "10.1.1.1", "10.1.2.4" }
                },
                Subnets = { new SubnetData()
                            {
                                Name = "mySubnet", AddressPrefix = "10.0.1.0/24"
                            } }
            };
            VirtualNetwork virtualNetwork = await virtualNetworkCollection.CreateOrUpdate(vnetName, vnetInput).WaitForCompletionAsync();

            #region Snippet:Managing_Networks_CreateANetworkInterface
            PublicIPAddressCollection publicIPAddressCollection = resourceGroup.GetPublicIPAddresses();
            string publicIPAddressName        = "myIPAddress";
            PublicIPAddressData publicIPInput = new PublicIPAddressData()
            {
                Location = resourceGroup.Data.Location,
                PublicIPAllocationMethod = IPAllocationMethod.Dynamic,
                DnsSettings = new PublicIPAddressDnsSettings()
                {
                    DomainNameLabel = "myDomain"
                }
            };
            PublicIPAddress publicIPAddress = await publicIPAddressCollection.CreateOrUpdate(publicIPAddressName, publicIPInput).WaitForCompletionAsync();

            NetworkInterfaceCollection networkInterfaceCollection = resourceGroup.GetNetworkInterfaces();
            string networkInterfaceName = "myNetworkInterface";
            NetworkInterfaceData networkInterfaceInput = new NetworkInterfaceData()
            {
                Location         = resourceGroup.Data.Location,
                IpConfigurations =
                {
                    new NetworkInterfaceIPConfiguration()
                    {
                        Name = "ipConfig",
                        PrivateIPAllocationMethod = IPAllocationMethod.Dynamic,
                        PublicIPAddress           = new PublicIPAddressData()
                        {
                            Id = publicIPAddress.Id
                        },
                        Subnet = new SubnetData()
                        {
                            // use the virtual network just created
                            Id = virtualNetwork.Data.Subnets[0].Id
                        }
                    }
                }
            };
            NetworkInterface networkInterface = await networkInterfaceCollection.CreateOrUpdate(networkInterfaceName, networkInterfaceInput).WaitForCompletionAsync();

            #endregion
        }
예제 #18
0
        public void DiskPoolCrud()
        {
            using var context = MockContext.Start(this.GetType());
            string resourceGroupName = TestUtilities.GenerateName("sdk-dcrud-rg");
            string diskPoolName      = TestUtilities.GenerateName("sdk-diskpool");
            string diskName          = TestUtilities.GenerateName("sdk-test-disk");
            string location          = "eastus";

            CreateResourceGroup(context, location, resourceGroupName);

            try
            {
                using var testBase = new StoragePoolTestBase(context);
                var client = testBase.StoragePoolClient;

                var vnetName         = "sdk-vnet";
                var subnetName       = "sdk-subnet";
                var diskName1        = "sdk-disk";
                var diskName2        = "sdk-disk-2";
                var availabilityZone = "2";

                // create vnet and subnet
                var networkClient = context.GetServiceClient <NetworkManagementClient>();
                var vnet          = new VirtualNetwork()
                {
                    Location     = location,
                    AddressSpace = new AddressSpace()
                    {
                        AddressPrefixes = new[] { "10.0.0.0/16" }
                    },
                    Subnets = new[]
                    {
                        new Subnet()
                        {
                            Name          = subnetName,
                            AddressPrefix = "10.0.0.0/24",
                            Delegations   = new Delegation[1]
                            {
                                new Delegation()
                                {
                                    Name        = "diskpool-delegation",
                                    ServiceName = "Microsoft.StoragePool/diskPools",
                                },
                            },
                        },
                    },
                };
                networkClient.VirtualNetworks.CreateOrUpdate(resourceGroupName, vnetName, vnet);
                var subnet = networkClient.Subnets.Get(resourceGroupName, vnetName, subnetName);

                var computeClient = context.GetServiceClient <ComputeManagementClient>();

                // create disk 1
                var sku = new DiskSku();
                sku.Name = DiskStorageAccountTypes.PremiumLRS;
                var disk1 = new ManagedDisk()
                {
                    Location     = location,
                    Sku          = sku,
                    Zones        = new[] { availabilityZone },
                    DiskSizeGB   = 256,
                    CreationData = new CreationData(DiskCreateOption.Empty),
                    MaxShares    = 2,
                };
                computeClient.Disks.CreateOrUpdate(resourceGroupName, diskName1, disk1);
                disk1 = computeClient.Disks.Get(resourceGroupName, diskName1);

                // create disk pool
                var diskPoolSku = new DiskPoolSku("Standard", "Standard");
                var diskPool    = new DiskPoolCreate(diskPoolSku, subnet.Id, location, new[] { availabilityZone });
                client.DiskPools.CreateOrUpdate(resourceGroupName, diskPoolName, diskPool);

                // assert that create succeeded
                var createdDiskPool = client.DiskPools.Get(resourceGroupName, diskPoolName);
                Assert.NotNull(createdDiskPool);
                Assert.Equal("Succeeded", createdDiskPool.ProvisioningState);


                // update disk pool -- add disk
                diskPool.Disks = new Disk[] { new Disk(disk1.Id) };
                client.DiskPools.CreateOrUpdate(resourceGroupName, diskPoolName, diskPool);

                // assert that create succeeded
                var updatedDiskPool = client.DiskPools.Get(resourceGroupName, diskPoolName);
                Assert.NotNull(updatedDiskPool);
                Assert.Equal("Succeeded", updatedDiskPool.ProvisioningState);

                // delete disk pool
                client.DiskPools.Delete(resourceGroupName, diskPoolName);
            }
            finally
            {
                DeleteResourceGroup(context, resourceGroupName);
            }
        }
예제 #19
0
        /// <summary>
        /// create a default private endpoint for managed instance.
        /// please make sure your MI built using CreateDefaultManagedInstance() or vnet AddressPrefixes = 10.10.0.0/16
        /// </summary>
        /// <param name="managedInstance"></param>
        /// <param name="location"></param>
        /// <param name="resourceGroup"></param>
        /// <param name=""></param>
        /// <returns></returns>
        protected async Task <PrivateEndpoint> CreateDefaultPrivateEndpoint(ManagedInstance managedInstance, VirtualNetwork vnet, Location location, ResourceGroup resourceGroup)
        {
            // Add new subnet
            SubnetData subnetData = new SubnetData()
            {
                AddressPrefix = "10.10.5.0/24",
                PrivateEndpointNetworkPolicies = "Disabled"
            };
            var privateEndpointSubnet = await vnet.GetSubnets().CreateOrUpdateAsync($"private-endpoint-subnet", subnetData);

            // Create private endpoint
            string privateEndpointName = $"{managedInstance.Data.Name}-private-endpoint";
            var    endpointCollection  = resourceGroup.GetPrivateEndpoints();
            PrivateEndpointData data   = new PrivateEndpointData()
            {
                Subnet = new SubnetData()
                {
                    Id = privateEndpointSubnet.Value.Data.Id
                },
                Location = location,
                PrivateLinkServiceConnections =
                {
                    new PrivateLinkServiceConnection()
                    {
                        Name = privateEndpointName,
                        PrivateLinkServiceId = managedInstance.Data.Id.ToString(),
                        GroupIds             = { "managedInstance" },
                    }
                },
            };
            var privateEndpoint = await resourceGroup.GetPrivateEndpoints().CreateOrUpdateAsync(privateEndpointName, data);

            return(privateEndpoint.Value);
        }
        public void NetworkInterfaceEnableIPForwardingTest()
        {
            var handler = new RecordedDelegatingHandler {
                StatusCodeToReturn = HttpStatusCode.OK
            };

            using (var context = UndoContext.Current)
            {
                context.Start();
                var resourcesClient = ResourcesManagementTestUtilities.GetResourceManagementClientWithHandler(handler);
                var networkResourceProviderClient = NetworkManagementTestUtilities.GetNetworkResourceProviderClient(handler);

                var location = NetworkManagementTestUtilities.GetResourceLocation(resourcesClient, "Microsoft.Network/networkInterfaces");

                string resourceGroupName = TestUtilities.GenerateName("csmrg");
                resourcesClient.ResourceGroups.CreateOrUpdate(resourceGroupName,
                                                              new ResourceGroup
                {
                    Location = location
                });

                // Create Vnet
                // Populate parameter for Put Vnet
                string vnetName   = TestUtilities.GenerateName();
                string subnetName = TestUtilities.GenerateName();

                var vnet = new VirtualNetwork()
                {
                    Location = location,

                    AddressSpace = new AddressSpace()
                    {
                        AddressPrefixes = new List <string>()
                        {
                            "10.0.0.0/16",
                        }
                    },
                    DhcpOptions = new DhcpOptions()
                    {
                        DnsServers = new List <string>()
                        {
                            "10.1.1.1",
                            "10.1.2.4"
                        }
                    },
                    Subnets = new List <Subnet>()
                    {
                        new Subnet()
                        {
                            Name          = subnetName,
                            AddressPrefix = "10.0.0.0/24",
                        }
                    }
                };

                var putVnetResponse = networkResourceProviderClient.VirtualNetworks.CreateOrUpdate(resourceGroupName, vnetName, vnet);
                Assert.Equal(HttpStatusCode.OK, putVnetResponse.StatusCode);

                var getSubnetResponse = networkResourceProviderClient.Subnets.Get(resourceGroupName, vnetName, subnetName);

                // Create Nic
                string nicName      = TestUtilities.GenerateName();
                string ipConfigName = TestUtilities.GenerateName();

                var nicParameters = new NetworkInterface()
                {
                    Location = location,
                    Name     = nicName,
                    Tags     = new Dictionary <string, string>()
                    {
                        { "key", "value" }
                    },
                    IpConfigurations = new List <NetworkInterfaceIpConfiguration>()
                    {
                        new NetworkInterfaceIpConfiguration()
                        {
                            Name = ipConfigName,
                            PrivateIpAllocationMethod = IpAllocationMethod.Dynamic,
                            Subnet = new ResourceId()
                            {
                                Id = getSubnetResponse.Subnet.Id
                            }
                        }
                    },
                    EnableIPForwarding = false,
                };

                // Test NIC apis
                var putNicResponse = networkResourceProviderClient.NetworkInterfaces.CreateOrUpdate(resourceGroupName, nicName, nicParameters);
                Assert.Equal(HttpStatusCode.OK, putNicResponse.StatusCode);

                var getNicResponse = networkResourceProviderClient.NetworkInterfaces.Get(resourceGroupName, nicName);
                Assert.Equal(getNicResponse.NetworkInterface.Name, nicName);
                Assert.Equal(getNicResponse.NetworkInterface.ProvisioningState, Microsoft.Azure.Management.Resources.Models.ProvisioningState.Succeeded);
                Assert.Null(getNicResponse.NetworkInterface.VirtualMachine);
                Assert.Null(getNicResponse.NetworkInterface.MacAddress);
                Assert.Equal(1, getNicResponse.NetworkInterface.IpConfigurations.Count);
                Assert.Equal(ipConfigName, getNicResponse.NetworkInterface.IpConfigurations[0].Name);
                Assert.False(getNicResponse.NetworkInterface.EnableIPForwarding);

                getNicResponse.NetworkInterface.EnableIPForwarding = true;
                networkResourceProviderClient.NetworkInterfaces.CreateOrUpdate(resourceGroupName, nicName, getNicResponse.NetworkInterface);
                getNicResponse = networkResourceProviderClient.NetworkInterfaces.Get(resourceGroupName, nicName);
                Assert.Equal(getNicResponse.NetworkInterface.Name, nicName);
                Assert.True(getNicResponse.NetworkInterface.EnableIPForwarding);

                // Delete Nic
                var deleteNicResponse = networkResourceProviderClient.NetworkInterfaces.Delete(resourceGroupName, nicName);
                Assert.Equal(HttpStatusCode.OK, deleteNicResponse.StatusCode);

                var getListNicResponse = networkResourceProviderClient.NetworkInterfaces.List(resourceGroupName);
                Assert.Equal(0, getListNicResponse.NetworkInterfaces.Count);

                // Delete VirtualNetwork
                var deleteVnetResponse = networkResourceProviderClient.VirtualNetworks.Delete(resourceGroupName, vnetName);
                Assert.Equal(HttpStatusCode.OK, deleteVnetResponse.StatusCode);
            }
        }
예제 #21
0
        public static VirtualNetwork CreateVirtualNetwork(SqlManagementTestContext context, ResourceGroup resourceGroup, string location)
        {
            NetworkManagementClient networkClient = context.GetClient <NetworkManagementClient>();

            // Create vnet andinitialize subnets
            string vnetName = SqlManagementTestUtilities.GenerateName();

            // Create network security group
            NetworkSecurityGroup networkSecurityGroupParams = new NetworkSecurityGroup()
            {
                Location      = TestEnvironmentUtilities.DefaultLocationId,
                SecurityRules = new List <SecurityRule>()
                {
                    new SecurityRule()
                    {
                        Direction = "Inbound",
                        Name      = "allow_management_inbound",
                        DestinationAddressPrefix = "*",
                        DestinationPortRanges    = new List <string>()
                        {
                            "1433", "1434", "5022", "9000", "9003", "1438", "1440", "1452", "80", "443"
                        },
                        SourceAddressPrefix = "*",
                        SourcePortRange     = "*",
                        Protocol            = "Tcp",
                        Access   = "Allow",
                        Priority = 100
                    },
                    new SecurityRule()
                    {
                        Direction                = "Inbound",
                        Name                     = "allow_misubnet_inbound",
                        DestinationPortRange     = "*",
                        DestinationAddressPrefix = "*",
                        SourceAddressPrefix      = "10.0.0.0/26",
                        SourcePortRange          = "*",
                        Protocol                 = "*",
                        Access                   = "Allow",
                        Priority                 = 200
                    },
                    new SecurityRule()
                    {
                        Direction = "Inbound",
                        Name      = "allow_health_probe",
                        DestinationAddressPrefix = "*",
                        DestinationPortRange     = "*",
                        SourceAddressPrefix      = "AzureLoadBalancer",
                        SourcePortRange          = "*",
                        Protocol = "*",
                        Access   = "Allow",
                        Priority = 300
                    },
                    new SecurityRule()
                    {
                        Direction = "Outbound",
                        Name      = "allow_management_outbound",
                        DestinationAddressPrefix = "*",
                        DestinationPortRanges    = new List <string>()
                        {
                            "80", "443", "12000"
                        },
                        Protocol            = "*",
                        SourceAddressPrefix = "*",
                        SourcePortRange     = "*",
                        Access   = "Allow",
                        Priority = 100
                    },
                    new SecurityRule()
                    {
                        Direction = "Outbound",
                        Name      = "allow_misubnet_outbound",
                        DestinationAddressPrefix = "10.0.0.0/26",
                        DestinationPortRange     = "*",
                        Protocol            = "*",
                        SourceAddressPrefix = "*",
                        SourcePortRange     = "*",
                        Access   = "Allow",
                        Priority = 200
                    }
                }
            };
            string networkSecurityGroupName = SqlManagementTestUtilities.GenerateName();

            networkClient.NetworkSecurityGroups.CreateOrUpdate(resourceGroup.Name, networkSecurityGroupName, networkSecurityGroupParams);
            NetworkSecurityGroup securityGroup = networkClient.NetworkSecurityGroups.Get(resourceGroup.Name, networkSecurityGroupName);

            // Create route table
            RouteTable routeTableParams = new RouteTable()
            {
                Location = TestEnvironmentUtilities.DefaultLocationId,
                Routes   = new List <Route>()
                {
                    new Route()
                    {
                        Name          = SqlManagementTestUtilities.GenerateName(),
                        AddressPrefix = "0.0.0.0/0",
                        NextHopType   = "Internet"
                    },
                    new Route()
                    {
                        Name          = SqlManagementTestUtilities.GenerateName(),
                        AddressPrefix = "10.0.0.0/26",
                        NextHopType   = "VnetLocal"
                    }
                }
            };
            string routeTableName = SqlManagementTestUtilities.GenerateName();

            networkClient.RouteTables.CreateOrUpdate(resourceGroup.Name, routeTableName, routeTableParams);
            RouteTable routeTable = networkClient.RouteTables.Get(resourceGroup.Name, routeTableName);

            // Create subnet
            List <Subnet> subnetList = new List <Subnet>();
            Subnet        subnet     = new Subnet()
            {
                Name                 = "MISubnet",
                AddressPrefix        = "10.0.0.0/26",
                NetworkSecurityGroup = securityGroup,
                RouteTable           = routeTable
            };

            subnetList.Add(subnet);

            // Create vnet
            var vnet = new VirtualNetwork()
            {
                Location = location,

                AddressSpace = new AddressSpace()
                {
                    AddressPrefixes = new List <string>()
                    {
                        "10.0.0.0/22",
                    }
                },
                Subnets = subnetList
            };

            // Put Vnet
            var putVnetResponse = networkClient.VirtualNetworks.CreateOrUpdate(resourceGroup.Name, vnetName, vnet);

            Assert.Equal("Succeeded", putVnetResponse.ProvisioningState);

            // Get Vnets
            var getVnetResponse = networkClient.VirtualNetworks.Get(resourceGroup.Name, vnetName);

            return(getVnetResponse);
        }
예제 #22
0
        public VirtualNetworkService
        (
            ILogger <VirtualNetworkService> logger,
            ICommandLineInterface cli,
            IVpnConnectionVerifier vpnConnectionVerifier,
            IPlatform platform,
            Subject <Object> clientServiceRestarting,
            Subject <Object> clientServiceRestarted,
            VirtualNetwork network
        )
        {
            if (clientServiceRestarting == null)
            {
                throw new ArgumentNullException(nameof(clientServiceRestarting));
            }
            if (clientServiceRestarted == null)
            {
                throw new ArgumentNullException(nameof(clientServiceRestarted));
            }

            this._Logger = logger ?? throw new ArgumentNullException(nameof(logger));
            this._Cli    = cli ?? throw new ArgumentNullException(nameof(cli));
            this._VpnConnectionVerifier = vpnConnectionVerifier ?? throw new ArgumentNullException(nameof(vpnConnectionVerifier));
            this._Platform     = platform ?? throw new ArgumentNullException(nameof(platform));
            this.Configuration = network ?? throw new ArgumentNullException(nameof(network));

            this._IsDisposed = new Subject <Object>();

            var __IsInitialized = new Subject <Object>();

            clientServiceRestarting

            .TakeUntil(this._IsDisposed)
            .SkipUntil(__IsInitialized)
            .Subscribe(this.OnClientServiceRestarting);

            clientServiceRestarted

            .TakeUntil(this._IsDisposed)
            .SkipUntil(__IsInitialized)
            .Subscribe(this.OnClientServiceRestarted);

            this._Account = new BehaviorSubject <Account>(null);
            this._Account

            .TakeUntil(this._IsDisposed)
            .SkipUntil(__IsInitialized)
            .DistinctUntilChanged()
            .Subscribe(this.OnAccountFoundChanged);

            this._Device = new BehaviorSubject <Device>(null);
            this._Device

            .SkipUntil(__IsInitialized)
            .TakeUntil(this._IsDisposed)
            .DistinctUntilChanged()
            .Subscribe(this.OnDeviceFoundChanged);

            // this._Interface = new BehaviorSubject<NetworkInterface>(null);
            // this._Interface
            //
            //  .TakeUntil(this._IsDisposed)
            //  .SkipUntil(__IsInitialized)
            //  .DistinctUntilChanged()
            //  .Subscribe(this.OnInterfaceFoundChanged);

            this._InterfaceName = new BehaviorSubject <String>(null);
            this._InterfaceName

            .TakeUntil(this._IsDisposed)
            .SkipUntil(__IsInitialized)
            .DistinctUntilChanged()
            .Subscribe(this.OnInterfaceFoundChanged);

            this._IPv4AddressAssigned = new BehaviorSubject <Boolean?>(null);
            this._IPv4AddressAssigned

            .TakeUntil(this._IsDisposed)
            .SkipUntil(__IsInitialized)
            .NotNull()
            .DistinctUntilChanged()
            .Subscribe(this.OnIPv4AddressAssignedChanged);

            this._IPv6AddressAssigned = new BehaviorSubject <Boolean?>(null);
            this._IPv6AddressAssigned

            .TakeUntil(this._IsDisposed)
            .SkipUntil(__IsInitialized)
            .NotNull()
            .DistinctUntilChanged()
            .Subscribe(this.OnIPv6AddressAssignedChanged);

            this._IPv4RoutesAssigned = new BehaviorSubject <Boolean?>(null);
            this._IPv4RoutesAssigned

            .TakeUntil(this._IsDisposed)
            .SkipUntil(__IsInitialized)
            .NotNull()
            .DistinctUntilChanged()
            .Subscribe(this.OnIPv4RoutesAppliedChanged);

            this._IPv6RoutesAssigned = new BehaviorSubject <Boolean?>(null);
            this._IPv6RoutesAssigned

            .TakeUntil(this._IsDisposed)
            .SkipUntil(__IsInitialized)
            .NotNull()
            .DistinctUntilChanged()
            .Subscribe(this.OnIPv6RoutesAppliedChanged);

            this._ConfigurationState = new BehaviorSubject <ConfigurationState?>(null);
            this._ConfigurationState

            .TakeUntil(this._IsDisposed)
            .SkipUntil(__IsInitialized)
            .NotNull()
            .DistinctUntilChanged()
            .Subscribe(this.OnConfigurationStateChanged);

            this._ConnectionState = new BehaviorSubject <ConnectionState?>(null);
            this._ConnectionState

            .TakeUntil(this._IsDisposed)
            .SkipUntil(__IsInitialized)
            .NotNull()
            .DistinctUntilChanged()
            .Subscribe(this.OnConnectionStateChanged);

            this._ReachableState = new BehaviorSubject <ReachableState?>(null);
            this._ReachableState

            .TakeUntil(this._IsDisposed)
            .NotNull()
            .DistinctUntilChanged()
            .Subscribe(this.OnReachableStateChanged);

            this._ConnectionVerificationResult = new BehaviorSubject <ConnectionVerificationResult>(null);
            this._ConnectionVerificationResult

            .TakeUntil(this._IsDisposed)
            .NotNull()
            .DistinctUntilChanged()
            .Subscribe(this.OnConnectionVerificationResultChanged);

            __IsInitialized.OnNext(null);
        }
예제 #23
0
    public WorkloadStack()
    {
        var baseStack   = new StackReference("evgenyb/iac-base/lab");
        var config      = new Config();
        var environment = Deployment.Instance.StackName;

        // Create an Azure Resource Group
        var resourceGroup = new ResourceGroup("rg", new ResourceGroupArgs
        {
            Name = NamingConvention.GetResourceGroupName(environment),
            Tags =
            {
                { "owner",       Constants.TeamPlatform },
                { "environment", environment            }
            }
        });

        var vnet = new VirtualNetwork("vnet", new VirtualNetworkArgs
        {
            Name = NamingConvention.GetVNetName(environment),
            ResourceGroupName = resourceGroup.Name,
            AddressSpaces     =
            {
                config.Require("vnet.addressSpaces")
            },
            Tags =
            {
                { "owner",       Constants.TeamPlatform },
                { "environment", environment            }
            }
        });

        // Create a Subnet for the cluster
        var aksSubnet = new Subnet("aks-net", new SubnetArgs
        {
            Name = "aks-net",
            ResourceGroupName  = resourceGroup.Name,
            VirtualNetworkName = vnet.Name,
            AddressPrefixes    =
            {
                config.Require("vnet.subnets.aks.addressPrefixes")
            },
        });

        var agwSubnet = new Subnet("agw-net", new SubnetArgs
        {
            Name = "agw-net",
            ResourceGroupName  = resourceGroup.Name,
            VirtualNetworkName = vnet.Name,
            AddressPrefixes    =
            {
                config.Require("vnet.subnets.agw.addressPrefixes")
            },
        });

        // var agwName = NamingConvention.GetAGWName("api", environment);
        // var agwPublicIp = new PublicIp("agw-api-pip", new PublicIpArgs
        // {
        //     Name = NamingConvention.GetPublicIpName("agw-api", environment),
        //     ResourceGroupName = resourceGroup.Name,
        //     Sku = "Standard",
        //     AllocationMethod = "Static",
        //     DomainNameLabel = agwName
        // });
        //
        // var agwMI = new UserAssignedIdentity("agw-mi", new UserAssignedIdentityArgs
        // {
        //     Name = NamingConvention.GetManagedIdentityName("agw", environment),
        //     ResourceGroupName = resourceGroup.Name
        // });
        //
        // var apiAgw = new ApplicationGateway("agw-api", new ApplicationGatewayArgs
        // {
        //     Name = agwName,
        //     ResourceGroupName = resourceGroup.Name,
        //     Identity = new ApplicationGatewayIdentityArgs
        //     {
        //         Type = "UserAssigned",
        //         IdentityIds = agwMI.Id
        //     },
        //     Sku = new ApplicationGatewaySkuArgs
        //     {
        //         Name = "WAF_v2",
        //         Tier = "WAF_v2",
        //         Capacity = 1
        //     },
        //     SslCertificates = new []
        //     {
        //         new ApplicationGatewaySslCertificateArgs
        //         {
        //             Name = "gateway-listener",
        //             KeyVaultSecretId = config.Require("keyVaultSecretId")
        //         }
        //     },
        //     FrontendPorts = new []
        //     {
        //         new ApplicationGatewayFrontendPortArgs
        //         {
        //             Name = "port443",
        //             Port = 443
        //         },
        //         new ApplicationGatewayFrontendPortArgs
        //         {
        //             Name = "port80",
        //             Port = 80
        //         }
        //     },
        //     GatewayIpConfigurations = new []
        //     {
        //         new ApplicationGatewayGatewayIpConfigurationArgs
        //         {
        //             Name = "appGatewayIpConfig",
        //             SubnetId = agwSubnet.Id
        //         }
        //     },
        //     FrontendIpConfigurations = new []
        //     {
        //         new ApplicationGatewayFrontendIpConfigurationArgs
        //         {
        //             Name = "appGatewayFrontendIP",
        //             PublicIpAddressId = agwPublicIp.Id
        //         }
        //     },
        //     HttpListeners = new []
        //     {
        //         new ApplicationGatewayHttpListenerArgs
        //         {
        //             Name = "gateway-listener",
        //             FrontendIpConfigurationName = "appGatewayFrontendIP",
        //             FrontendPortName = "port443",
        //             Protocol = "Https",
        //             HostName = "iac-lab-api.iac-labs.com",
        //             RequireSni = true,
        //             SslCertificateName = "gateway-listener"
        //         },
        //         new ApplicationGatewayHttpListenerArgs
        //         {
        //             Name = "management-listener",
        //             FrontendIpConfigurationName = "appGatewayFrontendIP",
        //             FrontendPortName = "port443",
        //             Protocol = "Https",
        //             HostName = "iac-lab-management.iac-labs.com",
        //             RequireSni = true,
        //             SslCertificateName = "gateway-listener"
        //         },
        //         new ApplicationGatewayHttpListenerArgs
        //         {
        //             Name = "portal-listener",
        //             FrontendIpConfigurationName = "appGatewayFrontendIP",
        //             FrontendPortName = "port443",
        //             Protocol = "Https",
        //             HostName = "iac-lab-portal.iac-labs.com",
        //             RequireSni = true,
        //             SslCertificateName = "gateway-listener"
        //         }
        //     },
        //     BackendAddressPools = new[]
        //     {
        //         new ApplicationGatewayBackendAddressPoolArgs
        //         {
        //             Name = "apim-backend-pool",
        //             IpAddresses = config.RequireSecret("apim.backend.ip")
        //         }
        //     },
        //     Probes = new[]
        //     {
        //         new ApplicationGatewayProbeArgs
        //         {
        //             Name = "apim-probe",
        //             Protocol = "Https",
        //             Path = "/status-0123456789abcdef",
        //             Host = "iac-lab-api.iac-labs.com",
        //             Interval = 30,
        //             Timeout = 120,
        //             UnhealthyThreshold = 8,
        //             PickHostNameFromBackendHttpSettings = false,
        //             MinimumServers = 0
        //         }
        //     },
        //     BackendHttpSettings = new []
        //     {
        //         new ApplicationGatewayBackendHttpSettingArgs
        //         {
        //             Name = "apim-settings",
        //             Port = 443,
        //             Protocol = "Https",
        //             CookieBasedAffinity = "Disabled",
        //             PickHostNameFromBackendAddress = false,
        //             RequestTimeout = 30,
        //             ProbeName = "apim-probe"
        //         }
        //     },
        //     RequestRoutingRules = new[]
        //     {
        //         new ApplicationGatewayRequestRoutingRuleArgs
        //         {
        //             Name = "gateway",
        //             RuleType = "Basic",
        //             HttpListenerName = "gateway-listener",
        //             BackendAddressPoolName = "apim-backend-pool",
        //             BackendHttpSettingsName = "apim-settings"
        //         },
        //         new ApplicationGatewayRequestRoutingRuleArgs
        //         {
        //             Name = "management",
        //             RuleType = "Basic",
        //             HttpListenerName = "management-listener",
        //             BackendAddressPoolName = "apim-backend-pool",
        //             BackendHttpSettingsName = "apim-settings"
        //         },
        //         new ApplicationGatewayRequestRoutingRuleArgs
        //         {
        //             Name = "portal",
        //             RuleType = "Basic",
        //             HttpListenerName = "portal-listener",
        //             BackendAddressPoolName = "apim-backend-pool",
        //             BackendHttpSettingsName = "apim-settings"
        //         },
        //     }
        // });
        //
        // var appInsight = new Insights("ai", new InsightsArgs
        // {
        //     Name = NamingConvention.GetAppInsightName(environment),
        //     ResourceGroupName = resourceGroup.Name,
        //     Location = resourceGroup.Location,
        //     ApplicationType = "web",
        //
        // });

        // var la = new AnalyticsWorkspace("la", new AnalyticsWorkspaceArgs
        // {
        //     Name = NamingConvention.GetLogAnalyticsName(environment),
        //     ResourceGroupName = resourceGroup.Name,
        //     Location = resourceGroup.Location,
        //     Sku = "PerGB2018"
        // });

        var aksEgressPublicIp = new PublicIp("aks-egress-pip", new PublicIpArgs
        {
            Name = NamingConvention.GetPublicIpName("aks-egress", environment),
            ResourceGroupName = resourceGroup.Name,
            Sku = "Standard",
            AllocationMethod = "Static"
        });

        var logAnalyticsWorkspaceId = baseStack.RequireOutput("LogAnalyticsWorkspaceId").Apply(x => x.ToString());
        var aks = new KubernetesCluster("aks", new KubernetesClusterArgs
        {
            Name = NamingConvention.GetAksName(environment),
            ResourceGroupName = resourceGroup.Name,
            Location          = resourceGroup.Location,
            Identity          = new KubernetesClusterIdentityArgs
            {
                Type = "SystemAssigned"
            },
            DefaultNodePool = new KubernetesClusterDefaultNodePoolArgs
            {
                Name         = "aksagentpool",
                NodeCount    = 1,
                VmSize       = "Standard_B2s",
                OsDiskSizeGb = 30,
                VnetSubnetId = aksSubnet.Id
            },
            DnsPrefix = "iacpulumiaks",
            RoleBasedAccessControl = new KubernetesClusterRoleBasedAccessControlArgs
            {
                Enabled = true,
                AzureActiveDirectory = new KubernetesClusterRoleBasedAccessControlAzureActiveDirectoryArgs
                {
                    AdminGroupObjectIds = config.RequireSecret("teamPlatformAADId"),
                    TenantId            = config.RequireSecret("tenantId"),
                    Managed             = true
                }
            },
            NetworkProfile = new KubernetesClusterNetworkProfileArgs
            {
                NetworkPlugin       = "azure",
                NetworkPolicy       = "calico",
                DnsServiceIp        = "10.2.2.254",
                ServiceCidr         = "10.2.2.0/24",
                DockerBridgeCidr    = "172.17.0.1/16",
                LoadBalancerProfile = new KubernetesClusterNetworkProfileLoadBalancerProfileArgs
                {
                    OutboundIpAddressIds = new []
                    {
                        aksEgressPublicIp.Id
                    }
                }
            },
            AddonProfile = new KubernetesClusterAddonProfileArgs
            {
                OmsAgent = new KubernetesClusterAddonProfileOmsAgentArgs
                {
                    Enabled = true,
                    LogAnalyticsWorkspaceId = logAnalyticsWorkspaceId
                },
                KubeDashboard = new KubernetesClusterAddonProfileKubeDashboardArgs
                {
                    Enabled = false
                }
            }
        });

        var pool = new KubernetesClusterNodePool("workload-pool", new KubernetesClusterNodePoolArgs
        {
            Name = "workload",
            KubernetesClusterId = aks.Id,
            Mode         = "User",
            NodeCount    = 1,
            VmSize       = "Standard_B2s",
            OsDiskSizeGb = 30,
            VnetSubnetId = aksSubnet.Id,
            NodeLabels   =
            {
                { "disk", "ssd"      },
                { "type", "workload" }
            }
        });

        this.KubeConfig = aks.KubeConfigRaw;
    }
 /// <summary>
 /// Creates or updates a virtual network in the specified resource group.
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='resourceGroupName'>
 /// The name of the resource group.
 /// </param>
 /// <param name='virtualNetworkName'>
 /// The name of the virtual network.
 /// </param>
 /// <param name='parameters'>
 /// Parameters supplied to the create or update virtual network operation
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task <VirtualNetwork> BeginCreateOrUpdateAsync(this IVirtualNetworksOperations operations, string resourceGroupName, string virtualNetworkName, VirtualNetwork parameters, CancellationToken cancellationToken = default(CancellationToken))
 {
     using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, virtualNetworkName, parameters, null, cancellationToken).ConfigureAwait(false))
     {
         return(_result.Body);
     }
 }
 /// <summary>
 /// Creates or updates a virtual network in the specified resource group.
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='resourceGroupName'>
 /// The name of the resource group.
 /// </param>
 /// <param name='virtualNetworkName'>
 /// The name of the virtual network.
 /// </param>
 /// <param name='parameters'>
 /// Parameters supplied to the create or update virtual network operation
 /// </param>
 public static VirtualNetwork BeginCreateOrUpdate(this IVirtualNetworksOperations operations, string resourceGroupName, string virtualNetworkName, VirtualNetwork parameters)
 {
     return(operations.BeginCreateOrUpdateAsync(resourceGroupName, virtualNetworkName, parameters).GetAwaiter().GetResult());
 }
예제 #26
0
        public async Task NegotiateStream_StreamToStream_Authentication_EmptyCredentials_Fails()
        {
            string targetName = "testTargetName";

            // Ensure there is no confusion between DefaultCredentials / DefaultNetworkCredentials and a
            // NetworkCredential object with empty user, password and domain.
            NetworkCredential emptyNetworkCredential = new NetworkCredential("", "", "");

            Assert.NotEqual(emptyNetworkCredential, CredentialCache.DefaultCredentials);
            Assert.NotEqual(emptyNetworkCredential, CredentialCache.DefaultNetworkCredentials);

            VirtualNetwork network = new VirtualNetwork();

            using (var clientStream = new VirtualNetworkStream(network, isServer: false))
                using (var serverStream = new VirtualNetworkStream(network, isServer: true))
                    using (var client = new NegotiateStream(clientStream))
                        using (var server = new NegotiateStream(serverStream))
                        {
                            Assert.False(client.IsAuthenticated);
                            Assert.False(server.IsAuthenticated);

                            Task[] auth = new Task[2];

                            auth[0] = AuthenticateAsClientAsync(client, emptyNetworkCredential, targetName);
                            auth[1] = AuthenticateAsServerAsync(server);

                            await TestConfiguration.WhenAllOrAnyFailedWithTimeout(auth);

                            // Expected Client property values:
                            Assert.True(client.IsAuthenticated);
                            Assert.Equal(TokenImpersonationLevel.Identification, client.ImpersonationLevel);
                            Assert.Equal(true, client.IsEncrypted);
                            Assert.Equal(false, client.IsMutuallyAuthenticated);
                            Assert.Equal(false, client.IsServer);
                            Assert.Equal(true, client.IsSigned);
                            Assert.Equal(false, client.LeaveInnerStreamOpen);

                            IIdentity serverIdentity = client.RemoteIdentity;
                            Assert.Equal("NTLM", serverIdentity.AuthenticationType);
                            Assert.Equal(true, serverIdentity.IsAuthenticated);
                            Assert.Equal(targetName, serverIdentity.Name);

                            // Expected Server property values:
                            Assert.True(server.IsAuthenticated);
                            Assert.Equal(TokenImpersonationLevel.Identification, server.ImpersonationLevel);
                            Assert.Equal(true, server.IsEncrypted);
                            Assert.Equal(false, server.IsMutuallyAuthenticated);
                            Assert.Equal(true, server.IsServer);
                            Assert.Equal(true, server.IsSigned);
                            Assert.Equal(false, server.LeaveInnerStreamOpen);

                            IIdentity clientIdentity = server.RemoteIdentity;
                            Assert.Equal("NTLM", clientIdentity.AuthenticationType);

                            // TODO #5241: Behavior difference:
                            Assert.Equal(false, clientIdentity.IsAuthenticated);
                            // On .NET Desktop: Assert.Equal(true, clientIdentity.IsAuthenticated);

                            IdentityValidator.AssertHasName(clientIdentity, new SecurityIdentifier(WellKnownSidType.AnonymousSid, null).Translate(typeof(NTAccount)).Value);
                        }
        }
예제 #27
0
        public async Task NewCode()
        {
#endif
            var armClient = new ArmClient(new DefaultAzureCredential());

            var location = AzureLocation.WestUS;
            // Create ResourceGroup
            Subscription subscription = await armClient.GetDefaultSubscriptionAsync();
            ArmOperation<ResourceGroup> rgOperation = await subscription.GetResourceGroups().CreateOrUpdateAsync(WaitUntil.Completed, "myResourceGroup", new ResourceGroupData(location));
            ResourceGroup resourceGroup = rgOperation.Value;

            // Create AvailabilitySet
            var availabilitySetData = new AvailabilitySetData(location)
            {
                PlatformUpdateDomainCount = 5,
                PlatformFaultDomainCount = 2,
                Sku = new ComputeSku() { Name = "Aligned" }
            };
            ArmOperation<AvailabilitySet> asetOperation = await resourceGroup.GetAvailabilitySets().CreateOrUpdateAsync(WaitUntil.Completed, "myAvailabilitySet", availabilitySetData);
            AvailabilitySet availabilitySet = asetOperation.Value;

            // Create VNet
            var vnetData = new VirtualNetworkData()
            {
                Location = location,
                Subnets =
                {
                    new SubnetData()
                    {
                        Name = "mySubnet",
                        AddressPrefix = "10.0.0.0/24",
                    }
                },
            };
            vnetData.AddressPrefixes.Add("10.0.0.0/16");
            ArmOperation<VirtualNetwork> vnetOperation = await resourceGroup.GetVirtualNetworks().CreateOrUpdateAsync(WaitUntil.Completed, "myVirtualNetwork", vnetData);
            VirtualNetwork vnet = vnetOperation.Value;

            // Create Network interface
            var nicData = new NetworkInterfaceData()
            {
                Location = location,
                IPConfigurations =
                {
                    new NetworkInterfaceIPConfigurationData()
                    {
                        Name = "Primary",
                        Primary = true,
                        Subnet = new SubnetData() { Id = vnet.Data.Subnets.First().Id },
                        PrivateIPAllocationMethod = IPAllocationMethod.Dynamic,
                    }
                }
            };
            ArmOperation<NetworkInterface> nicOperation = await resourceGroup.GetNetworkInterfaces().CreateOrUpdateAsync(WaitUntil.Completed, "myNetworkInterface", nicData);
            NetworkInterface nic = nicOperation.Value;

            var vmData = new VirtualMachineData(location)
            {
                AvailabilitySet = new WritableSubResource() { Id = availabilitySet.Id },
                NetworkProfile = new Compute.Models.NetworkProfile { NetworkInterfaces = { new NetworkInterfaceReference() { Id = nic.Id } } },
                OSProfile = new OSProfile
                {
                    ComputerName = "testVM",
                    AdminUsername = "******",
                    AdminPassword = "******",
                    LinuxConfiguration = new LinuxConfiguration { DisablePasswordAuthentication = false, ProvisionVmAgent = true }
                },
                StorageProfile = new StorageProfile()
                {
                    ImageReference = new ImageReference()
                    {
                        Offer = "UbuntuServer",
                        Publisher = "Canonical",
                        Sku = "18.04-LTS",
                        Version = "latest"
                    }
                },
                HardwareProfile = new HardwareProfile() { VmSize = VirtualMachineSizeTypes.StandardB1Ms },
            };
            ArmOperation<VirtualMachine> vmOperation = await resourceGroup.GetVirtualMachines().CreateOrUpdateAsync(WaitUntil.Completed, "myVirtualMachine", vmData);
            VirtualMachine vm = vmOperation.Value;
            #endregion
        }
예제 #28
0
 /// <summary>
 /// The Put VirtualNetwork operation creates/updates a virtual network in the
 /// specified resource group.
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='resourceGroupName'>
 /// The name of the resource group.
 /// </param>
 /// <param name='virtualNetworkName'>
 /// The name of the virtual network.
 /// </param>
 /// <param name='parameters'>
 /// Parameters supplied to the create/update Virtual Network operation
 /// </param>
 public static VirtualNetwork BeginCreateOrUpdate(this IVirtualNetworksOperations operations, string resourceGroupName, string virtualNetworkName, VirtualNetwork parameters)
 {
     return(Task.Factory.StartNew(s => ((IVirtualNetworksOperations)s).BeginCreateOrUpdateAsync(resourceGroupName, virtualNetworkName, parameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult());
 }
예제 #29
0
        public void NegotiateStream_StreamToStream_Authentication_EmptyCredentials_Fails()
        {
            string targetName = "testTargetName";

            // Ensure there is no confusion between DefaultCredentials / DefaultNetworkCredentials and a
            // NetworkCredential object with empty user, password and domain.
            NetworkCredential emptyNetworkCredential = new NetworkCredential("", "", "");

            Assert.NotEqual(emptyNetworkCredential, CredentialCache.DefaultCredentials);
            Assert.NotEqual(emptyNetworkCredential, CredentialCache.DefaultNetworkCredentials);

            VirtualNetwork network = new VirtualNetwork();

            using (var clientStream = new VirtualNetworkStream(network, isServer: false))
                using (var serverStream = new VirtualNetworkStream(network, isServer: true))
                    using (var client = new NegotiateStream(clientStream))
                        using (var server = new NegotiateStream(serverStream))
                        {
                            Assert.False(client.IsAuthenticated);
                            Assert.False(server.IsAuthenticated);

                            Task[] auth = new Task[2];

                            auth[0] = client.AuthenticateAsClientAsync(emptyNetworkCredential, targetName);
                            auth[1] = server.AuthenticateAsServerAsync();

                            bool finished = Task.WaitAll(auth, TestConfiguration.PassingTestTimeoutMilliseconds);
                            Assert.True(finished, "Handshake completed in the allotted time");

                            // Expected Client property values:
                            Assert.True(client.IsAuthenticated);
                            Assert.Equal(TokenImpersonationLevel.Identification, client.ImpersonationLevel);
                            Assert.Equal(true, client.IsEncrypted);
                            Assert.Equal(false, client.IsMutuallyAuthenticated);
                            Assert.Equal(false, client.IsServer);
                            Assert.Equal(true, client.IsSigned);
                            Assert.Equal(false, client.LeaveInnerStreamOpen);

                            IIdentity serverIdentity = client.RemoteIdentity;
                            Assert.Equal("NTLM", serverIdentity.AuthenticationType);
                            Assert.Equal(true, serverIdentity.IsAuthenticated);
                            Assert.Equal(targetName, serverIdentity.Name);

                            // Expected Server property values:
                            Assert.True(server.IsAuthenticated);
                            Assert.Equal(TokenImpersonationLevel.Identification, server.ImpersonationLevel);
                            Assert.Equal(true, server.IsEncrypted);
                            Assert.Equal(false, server.IsMutuallyAuthenticated);
                            Assert.Equal(true, server.IsServer);
                            Assert.Equal(true, server.IsSigned);
                            Assert.Equal(false, server.LeaveInnerStreamOpen);

                            IIdentity clientIdentity = server.RemoteIdentity;
                            Assert.Equal("NTLM", clientIdentity.AuthenticationType);

                            // TODO #5241: Behavior difference:
                            Assert.Equal(false, clientIdentity.IsAuthenticated);
                            // On .Net Desktop: Assert.Equal(true, clientIdentity.IsAuthenticated);

                            IdentityValidator.AssertHasName(clientIdentity, @"NT AUTHORITY\ANONYMOUS LOGON");
                        }
        }
예제 #30
0
파일: MyStack.cs 프로젝트: tlaothong/pulsf
    public MyStack()
    {
        var tags = new InputMap <string> {
            { "resourceType", "Service Fabric" },
            { "clusterName", "thepulsf" }
        };

        // Create an Azure Resource Group
        var resourceGroup = new ResourceGroup("resourceGroup", new ResourceGroupArgs
        {
            ResourceGroupName = "apulsf",
            Location          = "SoutheastAsia",
            Tags = tags,
        });

        // Create a Storage Account for Log
        var storageAccountLog = new StorageAccount("saLog", new StorageAccountArgs
        {
            ResourceGroupName = resourceGroup.Name,
            AccountName       = "sflogstore",
            Location          = resourceGroup.Location,
            Sku = new SkuArgs
            {
                Name = "Standard_LRS",
                Tier = "Standard"
            },
            Kind = "StorageV2",
            Tags = tags,
        });
        // Create a Storage Account for Application Diagnostics
        var storageAccountAppDx = new StorageAccount("saAppDx", new StorageAccountArgs
        {
            ResourceGroupName = resourceGroup.Name,
            AccountName       = "sfappdxstore",
            Location          = resourceGroup.Location,
            Sku = new SkuArgs
            {
                Name = "Standard_LRS",
                Tier = "Standard"
            },
            Kind = "StorageV2",
            Tags = tags,
        });
        // Virtual Network
        var vnet = new VirtualNetwork("vnet", new VirtualNetworkArgs {
            ResourceGroupName  = resourceGroup.Name,
            VirtualNetworkName = "thevnet4sf",
            Location           = resourceGroup.Location,
            AddressSpace       = new nwin.AddressSpaceArgs {
                AddressPrefixes = "10.10.0.0/16",
            },
            Subnets =
            {
                new nwin.SubnetArgs {
                    Name          = "Subnet0",
                    AddressPrefix = "10.10.10.0/24",
                }
            },
            Tags = tags,
        });
        // Public IP Address
        var pubIpAddr = new PublicIPAddress("pubip4sf", new PublicIPAddressArgs {
            ResourceGroupName   = resourceGroup.Name,
            PublicIpAddressName = "thesfpubip",
            Location            = resourceGroup.Location,
            DnsSettings         = new nwin.PublicIPAddressDnsSettingsArgs {
                DomainNameLabel = "thepulsf",
            },
            PublicIPAllocationMethod = "Dynamic",
            Tags = tags,
        });

        // Load Balancer
        var loadBalancer = new LoadBalancer("lb", new LoadBalancerArgs {
            ResourceGroupName        = resourceGroup.Name,
            Location                 = resourceGroup.Location,
            LoadBalancerName         = "thepulsflb4set0",
            FrontendIPConfigurations = new nwin.FrontendIPConfigurationArgs {
                Name            = "lbipconfig",
                PublicIPAddress = new nwin.PublicIPAddressArgs {
                    Id = pubIpAddr.Id,
                },
            },
            Tags = tags,
        });
        var bepool0 = new lb.BackendAddressPool("bepool0", new lb.BackendAddressPoolArgs {
            Name = "bepool0",
            ResourceGroupName = resourceGroup.Name,
            LoadbalancerId    = loadBalancer.Id,
        });
        var lbPorts = new [] { 19000, 19080, 80, 443 };

        for (int i = 0; i < lbPorts.Length; i++)
        {
            var port = lbPorts[i];

            var probe = new lb.Probe($"lbProbe{i}", new lb.ProbeArgs {
                ResourceGroupName = resourceGroup.Name,
                LoadbalancerId    = loadBalancer.Id,
                Port = port,
                IntervalInSeconds = 5,
                NumberOfProbes    = 2,
                Protocol          = "tcp",
            });
            var rule = new lb.Rule($"lbRule{i}", new lb.RuleArgs {
                ResourceGroupName           = resourceGroup.Name,
                LoadbalancerId              = loadBalancer.Id,
                FrontendIpConfigurationName = "lbipconfig",
                FrontendPort         = port,
                BackendAddressPoolId = bepool0.Id,
                BackendPort          = port,
                IdleTimeoutInMinutes = 5,
                EnableFloatingIp     = false,
                Protocol             = "tcp",
            });
        }
        var lbNatPool = new lb.NatPool("lbNatPool", new lb.NatPoolArgs {
            ResourceGroupName           = resourceGroup.Name,
            LoadbalancerId              = loadBalancer.Id,
            FrontendIpConfigurationName = "lbipconfig",
            FrontendPortStart           = 3389,
            FrontendPortEnd             = 4500,
            BackendPort = 3389,
            Protocol    = "tcp",
        });

        var sfCluster = new Cluster("thesf", new ClusterArgs {
            ClusterName       = "thesf",
            ResourceGroupName = resourceGroup.Name,
            Location          = resourceGroup.Location,

            AddOnFeatures =
            {
                "DnsService",
                "BackupRestoreService"
            },
            Certificate = new sfi.CertificateDescriptionArgs {
                Thumbprint    = "4426C164D9E66C2C813DEEC0486F235C0E933212",
                X509StoreName = "My",
            },
            DiagnosticsStorageAccountConfig = new sfi.DiagnosticsStorageAccountConfigArgs {
                BlobEndpoint            = storageAccountLog.PrimaryEndpoints.Apply(it => it.Blob),
                ProtectedAccountKeyName = "StorageAccountKey1",
                QueueEndpoint           = storageAccountLog.PrimaryEndpoints.Apply(it => it.Queue),
                StorageAccountName      = storageAccountLog.Name,
                TableEndpoint           = storageAccountLog.PrimaryEndpoints.Apply(it => it.Table),
            },
            FabricSettings =
            {
                new sfi.SettingsSectionDescriptionArgs           {
                    Parameters =
                    {
                        new sfi.SettingsParameterDescriptionArgs {
                            Name  = "SecretEncryptionCertThumbprint",
                            Value = "4426C164D9E66C2C813DEEC0486F235C0E933212",
                        },
                        new sfi.SettingsParameterDescriptionArgs {
                            Name  = "SecretEncryptionCertX509StoreName",
                            Value = "My",
                        },
                    },
                    Name = "BackupRestoreService",
                },
                new sfi.SettingsSectionDescriptionArgs           {
                    Parameters =
                    {
                        new sfi.SettingsParameterDescriptionArgs {
                            Name  = "ClusterProtectionLevel",
                            Value = "EncryptAndSign",
                        },
                    },
                    Name = "Security",
                },
            },
            ManagementEndpoint = Output.Format($"https://{pubIpAddr.DnsSettings.Apply(it => it?.Fqdn)}:19080"),
            NodeTypes          =
            {
                new sfi.NodeTypeDescriptionArgs {
                    Name             = "Type925",
                    ApplicationPorts = new sfi.EndpointRangeDescriptionArgs{
                        StartPort = 20000,
                        EndPort   = 30000,
                    },
                    ClientConnectionEndpointPort = 19000,
                    DurabilityLevel = "Silver",
                    EphemeralPorts  = new sfi.EndpointRangeDescriptionArgs {
                        StartPort = 49152,
                        EndPort   = 65534,
                    },
                    HttpGatewayEndpointPort = 19080,
                    IsPrimary       = true,
                    VmInstanceCount = 5,
                },
            },
            ReliabilityLevel = "Silver",
            UpgradeMode      = "Automatic",
            VmImage          = "Windows",
        });


        Key1 = GetStorageKey(resourceGroup, storageAccountLog, 0);
        Key2 = GetStorageKey(resourceGroup, storageAccountLog, 1);
        Input <string> key1 = Key1;
        Input <string> key2 = Key2;

        var vmScaleSet = new VirtualMachineScaleSet("sfScaleSet", new VirtualMachineScaleSetArgs {
            ResourceGroupName = resourceGroup.Name,
            Location          = resourceGroup.Location,
            VmScaleSetName    = "sfScaleSet0",
            Sku = new cpi.SkuArgs {
                Name     = "Standard_D2s_v3",
                Capacity = 5,
                Tier     = "Standard",
            },
            Overprovision = false,
            UpgradePolicy = new cpi.UpgradePolicyArgs {
                Mode = "Automatic",
            },
            VirtualMachineProfile = new cpi.VirtualMachineScaleSetVMProfileArgs {
                ExtensionProfile = new cpi.VirtualMachineScaleSetExtensionProfileArgs {
                    Extensions =
                    {
                        new cpi.VirtualMachineScaleSetExtensionArgs                 {
                            Name = "Type925_ServiceFabricNode",
                            Type = "ServiceFabricNode",
                            TypeHandlerVersion      = "1.1",
                            AutoUpgradeMinorVersion = true,
                            // EnableAutomaticUpgrade = true,   // MUST NOT ENABLED
                            ProtectedSettings =
                            {
                                { "StorageAccountKey1", key1                                                        },
                                { "StorageAccountKey2", key2                                                        },
                            },
                            Publisher = "Microsoft.Azure.ServiceFabric",
                            Settings  =
                            {
                                // { "id", "thepulsf" },
                                // { "clusterId", "thepulsf" },
                                // { "clusterEndpoint", pubIpAddr.DnsSettings.Apply(it => it?.Fqdn) },
                                { "clusterEndpoint",    sfCluster.ClusterEndpoint                                             },
                                { "nodeTypeRef",        "Type925"                                                             },
                                { "dataPath",           @"D:\\SvcFab"                                                         },
                                { "durabilityLevel",    "Silver"                                                              },
                                { "enableParallelJobs", true                                                                  },
                                { "nicPrefixOverride",  "10.10.10.0/24"                                                       },
                                { "certificate",        new InputMap <string>
                                                                                      {
                                                                                          { "thumbprint",         "4426C164D9E66C2C813DEEC0486F235C0E933212"                            },
                                                                                          { "x509StoreName",      "My"                                                                  },
                                                                                      } },
                            },
                        },
                        new cpi.VirtualMachineScaleSetExtensionArgs                 {
                            Name = "VMDiagnosticsVmExt_Set0",
                            Type = "IaaSDiagnostics",
                            TypeHandlerVersion = "1.5",
                            ProtectedSettings  =
                            {
                                { "storageAccountName",     storageAccountAppDx.Name                                    },
                                { "storageAccountKey",      GetStorageKey(resourceGroup, storageAccountAppDx, 0)        },
                                { "storageAccountEndPoint", "https://core.windows.net/"                                 },
                            },
                            Publisher = "Microsoft.Azure.Diagnostics",
                            Settings  =
                            {
                                { "WadCfg",                              new InputMap <object>
                                                                                      {
                                                                                          { "DiagnosticMonitorConfiguration",      new InputMap <object>
                                                                                      {
                                                                                          { "overallQuotaInMB",                    "50000"                                                               },
                                                                                          { "EtwProviders",                        new InputMap <object>
                                                                                      {
                                                                                          { "EtwEventSourceProviderConfiguration", new InputList <InputMap <object> >
                                                                                      {
                                                                                          new InputMap <object>
                                                                                          {
                                                                                              { "provider",                            "Microsoft-ServiceFabric-Actors"                                      },
                                                                                              { "scheduledTransferKeywordFilter",      "1"                                                                   },
                                                                                              { "scheduledTransferPeriod",             "PT5M"                                                                },
                                                                                              { "DefaultEvents",                       new InputMap <string>
                                                                                      {
                                                                                          { "eventDestination",                    "ServiceFabricReliableActorEventTable"                                }
                                                                                      } },
                                                                                          },
                                                                                          new InputMap <object>
                                                                                          {
                                                                                              { "provider",                            "Microsoft-ServiceFabric-Services"                                    },
                                                                                              { "scheduledTransferPeriod",             "PT5M"                                                                },
                                                                                              { "DefaultEvents",                       new InputMap <string>
                                                                                      {
                                                                                          { "eventDestination",                    "ServiceFabricReliableServiceEventTable"                              }
                                                                                      } },
                                                                                          },
                                                                                      } },
                                                                                          { "EtwManifestProviderConfiguration",    new InputList <InputMap <object> >
                                                                                      {
                                                                                          new InputMap <object> {
                                                                                              { "provider",                            "cbd93bc2-71e5-4566-b3a7-595d8eeca6e8"                                },
                                                                                              { "scheduledTransferLogLevelFilter",     "Information"                                                         },
                                                                                              { "scheduledTransferKeywordFilter",      "4611686018427387904"                                                 },
                                                                                              { "scheduledTransferPeriod",             "PT5M"                                                                },
                                                                                              { "DefaultEvents",                       new InputMap <string>
                                                                                      {
                                                                                          { "eventDestination",                    "ServiceFabricSystemEventTable"                                       }
                                                                                      } },
                                                                                          }
                                                                                      } },
                                                                                      } },
                                                                                      } },
                                                                                      } },
                                { "StorageAccount",                      storageAccountAppDx.Name                                              },
                            },
                        },
                    },
                },
                NetworkProfile = new cpi.VirtualMachineScaleSetNetworkProfileArgs {
                    NetworkInterfaceConfigurations =
                    {
                        new cpi.VirtualMachineScaleSetNetworkConfigurationArgs    {
                            Name             = "nicSfSet-0",
                            IpConfigurations =
                            {
                                new cpi.VirtualMachineScaleSetIPConfigurationArgs {
                                    Name = "nicSfSet-0",
                                    LoadBalancerBackendAddressPools = new cpi.SubResourceArgs{
                                        Id = bepool0.Id
                                    },
                                    LoadBalancerInboundNatPools = new cpi.SubResourceArgs{
                                        Id = lbNatPool.Id
                                    },
                                    Subnet = new cpi.ApiEntityReferenceArgs       {
                                        Id = vnet.Subnets.First().Apply(it => it.Id ?? string.Empty),
                                    },
                                },
                            },
                            Primary = true,
                        },
                    },
                },
                OsProfile = new cpi.VirtualMachineScaleSetOSProfileArgs {
                    AdminUsername      = "******",
                    AdminPassword      = "******",
                    ComputerNamePrefix = "Type925",
                    Secrets            =
                    {
                        new cpi.VaultSecretGroupArgs         {
                            SourceVault = new cpi.SubResourceArgs{
                                Id = "/subscriptions/5fb1076d-8ce2-4bf8-90af-d53f1b8f8289/resourceGroups/prepkvault/providers/Microsoft.KeyVault/vaults/thekv4sf"
                            },
                            VaultCertificates =
                            {
                                new cpi.VaultCertificateArgs {
                                    CertificateStore = "My",
                                    CertificateUrl   = "https://thekv4sf.vault.azure.net/secrets/thesfcert/4379416a51dc4570bda6bc79a6fbfa59",
                                },
                            },
                        },
                    },
                },
                StorageProfile = new cpi.VirtualMachineScaleSetStorageProfileArgs {
                    ImageReference = new cpi.ImageReferenceArgs {
                        Publisher = "MicrosoftWindowsServer",
                        Offer     = "WindowsServer",
                        Sku       = "2019-Datacenter-with-Containers",
                        Version   = "latest",
                    },
                    OsDisk = new cpi.VirtualMachineScaleSetOSDiskArgs {
                        Caching      = "ReadOnly",
                        CreateOption = "FromImage",
                        ManagedDisk  = new cpi.VirtualMachineScaleSetManagedDiskParametersArgs {
                            StorageAccountType = "Standard_LRS",
                        },
                    },
                },
            },
        });

        // Export the primary key of> the Storage Account
        this.PrimaryStorageKey = Output.Tuple(resourceGroup.Name, storageAccountAppDx.Name).Apply(names =>
                                                                                                  Output.CreateSecret(GetStorageAccountKey(names.Item1, names.Item2, 0)));
    }