Beispiel #1
0
        public static void PrintNetworkSecurityGroup(INetworkSecurityGroup resource)
        {
            var nsgOutput = new StringBuilder();

            nsgOutput.Append("NSG: ").Append(resource.Id)
            .Append("Name: ").Append(resource.Name)
            .Append("\n\tResource group: ").Append(resource.ResourceGroupName)
            .Append("\n\tRegion: ").Append(resource.RegionName)
            .Append("\n\tTags: ").Append(FormatDictionary(resource.Tags));

            // Output security rules
            foreach (var rule in resource.SecurityRules.Values)
            {
                nsgOutput.Append("\n\tRule: ").Append(rule.Name)
                .Append("\n\t\tAccess: ").Append(rule.Access)
                .Append("\n\t\tDirection: ").Append(rule.Direction)
                .Append("\n\t\tFrom address: ").Append(rule.SourceAddressPrefix)
                .Append("\n\t\tFrom port range: ").Append(rule.SourcePortRange)
                .Append("\n\t\tTo address: ").Append(rule.DestinationAddressPrefix)
                .Append("\n\t\tTo port: ").Append(rule.DestinationPortRange)
                .Append("\n\t\tProtocol: ").Append(rule.Protocol)
                .Append("\n\t\tPriority: ").Append(rule.Priority);
            }
            Console.WriteLine(nsgOutput.ToString());
        }
Beispiel #2
0
        ///GENMHASH:AC21A10EE2E745A89E94E447800452C1:AE9E4236A459ED3A7B2F266E3CEED6AD
        override protected void BeforeCreating()
        {
            INetworkSecurityGroup networkSecurityGroup = null;

            if (creatableNetworkSecurityGroupKey != null)
            {
                networkSecurityGroup = (INetworkSecurityGroup)this.CreatedResource(creatableNetworkSecurityGroupKey);
            }
            else if (existingNetworkSecurityGroupToAssociate != null)
            {
                networkSecurityGroup = existingNetworkSecurityGroupToAssociate;
            }

            // Associate an NSG if needed
            if (networkSecurityGroup != null)
            {
                Inner.NetworkSecurityGroup = new SubResource(networkSecurityGroup.Id);
            }

            NicIPConfigurationImpl.EnsureConfigurations(new List <INicIPConfiguration>(nicIPConfigurations.Values));

            // Reset and update IP configs
            Inner.IpConfigurations =
                InnersFromWrappers <NetworkInterfaceIPConfigurationInner, INicIPConfiguration>(nicIPConfigurations.Values);
        }
        protected override void ProcessRecord()
        {
            base.ProcessRecord();

            var networkConfiguration = GetNetworkConfiguration();

            if (networkConfiguration == null)
            {
                throw new ArgumentOutOfRangeException(Resources.NetworkConfigurationNotFoundOnPersistentVM);
            }

            string networkSecurityGroupName = networkConfiguration.NetworkSecurityGroup;

            if (string.IsNullOrEmpty(networkSecurityGroupName))
            {
                WriteWarningWithTimestamp(string.Format(Resources.WarningVmIsNotDirectlyAssociatedWithNetworkSecurityGroup, this.VM.GetInstance().RoleName));
            }

            else
            {
                var networkClient = new NetworkClient(Profile, Profile.Context.Subscription, CommandRuntime);
                INetworkSecurityGroup networkSecurityGroup = networkClient.GetNetworkSecurityGroup(networkSecurityGroupName, Detailed);

                WriteObject(networkSecurityGroup, true);
            }
        }
        public void Print(INetworkSecurityGroup resource)
        {
            var info = new StringBuilder();

            info.Append("NSG: ").Append(resource.Id)
            .Append("Name: ").Append(resource.Name)
            .Append("\n\tResource group: ").Append(resource.ResourceGroupName)
            .Append("\n\tRegion: ").Append(resource.Region)
            .Append("\n\tTags: ").Append(resource.Tags);

            // Output security rules
            foreach (INetworkSecurityRule rule in resource.SecurityRules.Values)
            {
                info.Append("\n\tRule: ").Append(rule.Name)
                .Append("\n\t\tAccess: ").Append(rule.Access)
                .Append("\n\t\tDirection: ").Append(rule.Direction)
                .Append("\n\t\tFrom address: ").Append(rule.SourceAddressPrefix)
                .Append("\n\t\tFrom port range: ").Append(rule.SourcePortRange)
                .Append("\n\t\tTo address: ").Append(rule.DestinationAddressPrefix)
                .Append("\n\t\tTo port: ").Append(rule.DestinationPortRange)
                .Append("\n\t\tProtocol: ").Append(rule.Protocol)
                .Append("\n\t\tPriority: ").Append(rule.Priority)
                .Append("\n\t\tDescription: ").Append(rule.Description);
            }

            info.Append("\n\tNICs: ").Append(resource.NetworkInterfaceIds);
            TestHelper.WriteLine(info.ToString());
        }
        ResourceProvisioningResult CreateResult(INetworkSecurityGroup nsg)
        {
            var crudResult = ResourceProvisioningResultUtil.CreateFromIResource(nsg);

            crudResult.CurrentProvisioningState = nsg.Inner.ProvisioningState.ToString();
            crudResult.NewSharedVariables.Add(AzureCrudSharedVariable.NETWORK_SECURITY_GROUP_NAME, nsg.Name);
            return(crudResult);
        }
Beispiel #6
0
        public async Task <bool> DeleteAsync(INetworkSecurityGroup record)
        {
            Ensure.NotNull(record, nameof(record));

            return(await db.NetworkSecurityGroups.PatchAsync(record.Id, new[] {
                Change.Replace("deleted", Func("NOW"))
            }, condition : IsNull("deleted")) > 0);
        }
Beispiel #7
0
        public void WithExistingNetworkSecurityGroup()
        {
            using (var context = FluentMockContext.Start(GetType().FullName))
            {
                var    testId = TestUtilities.GenerateName("");
                string rgName = "rg" + testId;
                string nic    = "nic" + testId;
                string vnet1BackEndSubnetNsgName = "backendnsg";
                Region region = Region.USEast;

                var azure = TestHelper.CreateRollupClient();
                try
                {
                    INetworkSecurityGroup nsg = azure.NetworkSecurityGroups
                                                .Define(vnet1BackEndSubnetNsgName)
                                                .WithRegion(Region.USEast)
                                                .WithNewResourceGroup(rgName)
                                                .DefineRule("DenyInternetInComing")
                                                .DenyInbound()
                                                .FromAddress("INTERNET")
                                                .FromAnyPort()
                                                .ToAnyAddress()
                                                .ToAnyPort()
                                                .WithAnyProtocol()
                                                .Attach()
                                                .DefineRule("DenyInternetOutGoing")
                                                .DenyOutbound()
                                                .FromAnyAddress()
                                                .FromAnyPort()
                                                .ToAddress("INTERNET")
                                                .ToAnyPort()
                                                .WithAnyProtocol()
                                                .Attach()
                                                .Create();

                    var vnet = azure.Networks.Define(nic)
                               .WithRegion(region)
                               .WithExistingResourceGroup(rgName)
                               .WithTag("redis", "OwnerName")
                               .WithAddressSpace("172.16.0.0/12")
                               .DefineSubnet("subnet")
                               .WithAddressPrefix("172.16.0.0/16")
                               .WithExistingNetworkSecurityGroup(nsg)
                               .Attach()
                               .CreateAsync().ConfigureAwait(false).GetAwaiter().GetResult();

                    azure.ResourceGroups.BeginDeleteByName(rgName);
                }
                finally
                {
                    try
                    {
                        azure.ResourceGroups.DeleteByName(rgName);
                    }
                    catch { }
                }
            }
        }
        public NetworkSecurityGroup(Asm.NetworkSecurityGroup source, TargetSettings targetSettings)
        {
            _SourceNetworkSecurityGroup = source;
            this.SetTargetName(source.Name, targetSettings);

            foreach (Asm.NetworkSecurityGroupRule sourceRule in source.Rules)
            {
                NetworkSecurityGroupRule targetRule = new NetworkSecurityGroupRule(sourceRule, targetSettings);
                this.Rules.Add(targetRule);
            }
        }
Beispiel #9
0
 ///GENMHASH:2E4015B29759BBD97527EBAE809B083C:3A31AFD1DFD5FF7364435492A5063098
 internal INetworkSecurityGroup GetNetworkSecurityGroup()
 {
     if (networkSecurityGroup == null && NetworkSecurityGroupId() != null)
     {
         string id = NetworkSecurityGroupId();
         networkSecurityGroup = Manager
                                .NetworkSecurityGroups
                                .GetByResourceGroup(ResourceUtils.GroupFromResourceId(id), ResourceUtils.NameFromResourceId(id));
     }
     return(networkSecurityGroup);
 }
Beispiel #10
0
        public NetworkSecurityGroup(Arm.NetworkSecurityGroup source, TargetSettings targetSettings) : base(ArmConst.MicrosoftNetwork, ArmConst.NetworkSecurityGroups)
        {
            _SourceNetworkSecurityGroup = source;
            this.SetTargetName(source.Name, targetSettings);

            foreach (Arm.NetworkSecurityGroupRule sourceRule in source.Rules)
            {
                NetworkSecurityGroupRule targetRule = new NetworkSecurityGroupRule(sourceRule, targetSettings);
                this.Rules.Add(targetRule);
            }
        }
        public NetworkSecurityGroup(AzureContext azureContext, Arm.NetworkSecurityGroup source)
        {
            _AzureContext = azureContext;
            _SourceNetworkSecurityGroup = source;
            this.TargetName             = source.Name;

            foreach (Arm.NetworkSecurityGroupRule sourceRule in source.Rules)
            {
                NetworkSecurityGroupRule targetRule = new NetworkSecurityGroupRule(azureContext, sourceRule);
                this.Rules.Add(targetRule);
            }
        }
Beispiel #12
0
        protected override async Task <string> DeployResourcesAsync(List <IGenericResource> unexpectedResources, IAzure azure, IResourceManager resourceManager, CancellationToken cancellationToken)
        {
            var gatewayIp = await DeployPublicIp(unexpectedResources, azure, Settings.Name + "-IP", Settings.Name, cancellationToken);

            INetworkSecurityGroup nsg = await DeployNetworkSecurityGroup(unexpectedResources, gatewayIp, azure, cancellationToken);

            INetwork vnet = await DeployVirtualNetwork(unexpectedResources, azure, nsg, cancellationToken);

            var gatewayId = await DeployApplicationGateway(unexpectedResources, resourceManager, gatewayIp, vnet, cancellationToken);

            return($"VNet='{vnet.Id}'\nGateway='{gatewayId}'\n");
        }
Beispiel #13
0
        private async Task <INetwork> DeployVirtualNetwork(ICollection <IGenericResource> unexpectedResources,
                                                           IAzure azure, INetworkSecurityGroup nsg, CancellationToken cancellationToken)
        {
            string vnetName = Settings.Name + "-vnet";

            IGenericResource existingNetworkResource = unexpectedResources.FirstOrDefault(r =>
                                                                                          string.Equals(r.ResourceProviderNamespace, "Microsoft.Network", StringComparison.OrdinalIgnoreCase) &&
                                                                                          string.Equals(r.ResourceType, "virtualNetworks", StringComparison.OrdinalIgnoreCase) &&
                                                                                          string.Equals(r.Name, vnetName, StringComparison.OrdinalIgnoreCase));

            var pairs       = Enumerable.Range(1, 5).SelectMany(i => Enumerable.Range(1, 5).Select(j => (i, j)));
            var nodeSubnets = pairs.Select(p => ($"Cluster-{p.i}-Node-{p.j}", $"10.{p.i}.{p.j}.0/24"));
            IEnumerable <(string, string)> neededSubnets = new[]
        public override void ExecuteCmdlet()
        {
            var getForSubnetResponse = Client.GetNetworkSecurityGroupForSubnet(VirtualNetworkName, SubnetName);

            if (getForSubnetResponse.State != "Created")
            {
                WriteWarningWithTimestamp(
                    string.Format(Resources.NetworkSecurityGroupNotActiveInSubnet, getForSubnetResponse.Name, VirtualNetworkName, SubnetName));
            }

            INetworkSecurityGroup securityGroup = Client.GetNetworkSecurityGroup(getForSubnetResponse.Name, Detailed);

            WriteObject(securityGroup);
        }
 async Task NsgApplyBaseRules(INetworkSecurityGroup nsg)
 {
     await nsg.Update()
     .DefineRule(AzureVmConstants.RulePresets.ALLOW_FOR_SERVICETAG_VNET)
     .AllowOutbound()
     .FromAnyAddress()
     .FromAnyPort()
     .ToAddress("VirtualNetwork")
     .ToAnyPort()
     .WithAnyProtocol()
     .WithPriority(AzureVmConstants.RulePresets.ALLOW_FOR_SERVICETAG_VNET_PRIORITY)
     .Attach()
     .ApplyAsync();
 }
Beispiel #16
0
 ///GENMHASH:9BCDEB79AFC04D55B9BC280847723DFC:7E388FA346F0E33887182060FBAF25FB
 internal NetworkInterfaceImpl WithExistingNetworkSecurityGroup(INetworkSecurityGroup networkSecurityGroup)
 {
     existingNetworkSecurityGroupToAssociate = networkSecurityGroup;
     return(this);
 }
 private void WriteNetworkSecurityGroup(INetworkSecurityGroup networkSecurityGroup)
 {
     WriteObject(networkSecurityGroup, true);
 }
        private void GetByName()
        {
            INetworkSecurityGroup networkSecurityGroup = Client.GetNetworkSecurityGroup(Name, Detailed);

            WriteNetworkSecurityGroup(networkSecurityGroup);
        }
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation($"{DateAndTime()} | C# HTTP trigger function processed a request.");

            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();

            ProvisioningModel provisioningModel = JsonConvert.DeserializeObject <ProvisioningModel>(requestBody);


            if (string.IsNullOrEmpty(provisioningModel.ClientId) ||
                string.IsNullOrEmpty(provisioningModel.ClientSecret) ||
                string.IsNullOrEmpty(provisioningModel.TenantId) ||
                string.IsNullOrEmpty(provisioningModel.SubscriptionId) ||
                string.IsNullOrEmpty(provisioningModel.ClustrerName) ||
                string.IsNullOrEmpty(provisioningModel.ResourceGroupName) ||
                string.IsNullOrEmpty(provisioningModel.MainVhdURL) ||
                string.IsNullOrEmpty(provisioningModel.SmtpServer) ||
                string.IsNullOrEmpty(provisioningModel.SmtpPort.ToString()) ||
                string.IsNullOrEmpty(provisioningModel.SmtpEmail) ||
                string.IsNullOrEmpty(provisioningModel.SmtpPassword))
            {
                log.LogInformation($"{DateAndTime()} | Error |  Missing parameter | \n{requestBody}");
                return(new BadRequestObjectResult(false));
            }
            else
            {
                bool isSingleInstance;

                switch (provisioningModel.InstanceCount)
                {
                case "1": { isSingleInstance = true; break; }

                case "3": {
                    isSingleInstance = false;
                    if (
                        string.IsNullOrEmpty(provisioningModel.MysqlVhdURL) ||
                        string.IsNullOrEmpty(provisioningModel.MongoVhdURL))
                    {
                        log.LogInformation($"{DateAndTime()} | Error | Missing parameter for 3 instance (MysqlVhdURL/MongoVhdURL) | \n{requestBody}");
                        return(new BadRequestObjectResult(false));
                    }
                    break;
                }

                default:
                {
                    log.LogInformation($"{DateAndTime()} | Error | Please set valid instance count (1 or 3) | \n{requestBody}");
                    return(new BadRequestObjectResult(false));
                }
                }

                SmtpClient smtpClient = new SmtpClient()
                {
                    Host                  = provisioningModel.SmtpServer,
                    Port                  = provisioningModel.SmtpPort,
                    EnableSsl             = true,
                    UseDefaultCredentials = false,
                    Credentials           = new NetworkCredential(provisioningModel.SmtpEmail, provisioningModel.SmtpPassword)
                };

                MailMessage mailMessage = new MailMessage();

                mailMessage.From = new MailAddress(provisioningModel.SmtpEmail);
                mailMessage.To.Add(new MailAddress(provisioningModel.SmtpEmail));
                mailMessage.Subject = "Branch Academy Installation";

                try
                {
                    string resourceGroupName = provisioningModel.ResourceGroupName;
                    string clusterName       = provisioningModel.ClustrerName;
                    string MainVhdURL        = provisioningModel.MainVhdURL;
                    string MysqlVhdURL       = provisioningModel.MysqlVhdURL;
                    string MongoVhdURL       = provisioningModel.MongoVhdURL;
                    string subnet            = "default";
                    string username          = provisioningModel.Username;
                    string password          = provisioningModel.Password;

                    string contactPerson = provisioningModel.SmtpEmail;

                    log.LogInformation("deploying Main instance");
                    Utils.Email(smtpClient, "Main Instance Deployed Successfully", log, mailMessage);

                    ServicePrincipalLoginInformation principalLogIn = new ServicePrincipalLoginInformation();
                    principalLogIn.ClientId     = provisioningModel.ClientId;
                    principalLogIn.ClientSecret = provisioningModel.ClientSecret;

                    AzureEnvironment environment = AzureEnvironment.AzureGlobalCloud;
                    AzureCredentials credentials = new AzureCredentials(principalLogIn, provisioningModel.TenantId, environment);

                    IAzure _azureProd = Azure.Configure()
                                        .WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
                                        .Authenticate(credentials)
                                        .WithSubscription(provisioningModel.SubscriptionId);


                    IResourceGroup resourceGroup = _azureProd.ResourceGroups.GetByName(resourceGroupName);
                    Region         region        = resourceGroup.Region;

                    #region comment

                    #region Create Virtual Network
                    INetwork virtualNetwork = _azureProd.Networks.Define($"{clusterName}-vnet")
                                              .WithRegion(region)
                                              .WithExistingResourceGroup(resourceGroupName)
                                              .WithAddressSpace("10.0.0.0/16")
                                              .DefineSubnet(subnet)
                                              .WithAddressPrefix("10.0.0.0/24")
                                              .Attach()
                                              .WithTag("_contact_person", contactPerson)
                                              .Create();

                    #endregion

                    log.LogInformation($"{DateAndTime()} | Created | VNET");

                    #region Create VM IP
                    IPublicIPAddress publicIpAddress = _azureProd.PublicIPAddresses.Define($"{clusterName}-vm-ip")
                                                       .WithRegion(region)
                                                       .WithExistingResourceGroup(resourceGroupName)
                                                       .WithDynamicIP()
                                                       .WithLeafDomainLabel(clusterName)
                                                       .WithTag("_contact_person", contactPerson)
                                                       .Create();
                    #endregion

                    log.LogInformation($"{DateAndTime()} | Created | VM IP Address");

                    #region NSG
                    INetworkSecurityGroup networkSecurityGroup = _azureProd.NetworkSecurityGroups.Define($"{clusterName}-nsg")
                                                                 .WithRegion(region)
                                                                 .WithExistingResourceGroup(resourceGroupName)
                                                                 .DefineRule("ALLOW-SSH")
                                                                 .AllowInbound()
                                                                 .FromAnyAddress()
                                                                 .FromAnyPort()
                                                                 .ToAnyAddress()
                                                                 .ToPort(22)
                                                                 .WithProtocol(SecurityRuleProtocol.Tcp)
                                                                 .WithPriority(100)
                                                                 .WithDescription("Allow SSH")
                                                                 .Attach()
                                                                 .DefineRule("LMS")
                                                                 .AllowInbound()
                                                                 .FromAnyAddress()
                                                                 .FromAnyPort()
                                                                 .ToAnyAddress()
                                                                 .ToPort(80)
                                                                 .WithProtocol(SecurityRuleProtocol.Tcp)
                                                                 .WithPriority(101)
                                                                 .WithDescription("LMS")
                                                                 .Attach()
                                                                 .DefineRule("CMS")
                                                                 .AllowInbound()
                                                                 .FromAnyAddress()
                                                                 .FromAnyPort()
                                                                 .ToAnyAddress()
                                                                 .ToPort(18010)
                                                                 .WithProtocol(SecurityRuleProtocol.Tcp)
                                                                 .WithPriority(102)
                                                                 .WithDescription("CMS")
                                                                 .Attach()
                                                                 .DefineRule("CMSSSLPort")
                                                                 .AllowInbound()
                                                                 .FromAnyAddress()
                                                                 .FromAnyPort()
                                                                 .ToAnyAddress()
                                                                 .ToPort(48010)
                                                                 .WithProtocol(SecurityRuleProtocol.Tcp)
                                                                 .WithPriority(112)
                                                                 .WithDescription("CMSSSLPort")
                                                                 .Attach()
                                                                 .DefineRule("LMSSSLPort")
                                                                 .AllowInbound()
                                                                 .FromAnyAddress()
                                                                 .FromAnyPort()
                                                                 .ToAnyAddress()
                                                                 .ToPort(443)
                                                                 .WithProtocol(SecurityRuleProtocol.Tcp)
                                                                 .WithPriority(122)
                                                                 .WithDescription("LMSSSLPort")
                                                                 .Attach()
                                                                 .DefineRule("Certs")
                                                                 .AllowInbound()
                                                                 .FromAnyAddress()
                                                                 .FromAnyPort()
                                                                 .ToAnyAddress()
                                                                 .ToPort(18090)
                                                                 .WithProtocol(SecurityRuleProtocol.Tcp)
                                                                 .WithPriority(132)
                                                                 .WithDescription("Certs")
                                                                 .Attach()
                                                                 .DefineRule("Discovery")
                                                                 .AllowInbound()
                                                                 .FromAnyAddress()
                                                                 .FromAnyPort()
                                                                 .ToAnyAddress()
                                                                 .ToPort(18381)
                                                                 .WithProtocol(SecurityRuleProtocol.Tcp)
                                                                 .WithPriority(142)
                                                                 .WithDescription("Discovery")
                                                                 .Attach()
                                                                 .DefineRule("Ecommerce")
                                                                 .AllowInbound()
                                                                 .FromAnyAddress()
                                                                 .FromAnyPort()
                                                                 .ToAnyAddress()
                                                                 .ToPort(18130)
                                                                 .WithProtocol(SecurityRuleProtocol.Tcp)
                                                                 .WithPriority(152)
                                                                 .WithDescription("Ecommerce")
                                                                 .Attach()
                                                                 .DefineRule("edx-release")
                                                                 .AllowInbound()
                                                                 .FromAnyAddress()
                                                                 .FromAnyPort()
                                                                 .ToAnyAddress()
                                                                 .ToPort(8099)
                                                                 .WithProtocol(SecurityRuleProtocol.Tcp)
                                                                 .WithPriority(162)
                                                                 .WithDescription("edx-release")
                                                                 .Attach()
                                                                 .DefineRule("Forum")
                                                                 .AllowInbound()
                                                                 .FromAnyAddress()
                                                                 .FromAnyPort()
                                                                 .ToAnyAddress()
                                                                 .ToPort(18080)
                                                                 .WithProtocol(SecurityRuleProtocol.Tcp)
                                                                 .WithPriority(172)
                                                                 .WithDescription("Forum")
                                                                 .Attach()
                                                                 .WithTag("_contact_person", contactPerson)
                                                                 .DefineRule("Xqueue")
                                                                 .AllowInbound()
                                                                 .FromAnyAddress()
                                                                 .FromAnyPort()
                                                                 .ToAnyAddress()
                                                                 .ToPort(18040)
                                                                 .WithProtocol(SecurityRuleProtocol.Tcp)
                                                                 .WithPriority(182)
                                                                 .WithDescription("Xqueue")
                                                                 .Attach()
                                                                 .WithTag("_contact_person", contactPerson)
                                                                 .Create();
                    #endregion

                    log.LogInformation($"{DateAndTime()} | Created | Network Security Group");

                    #region nic
                    INetworkInterface networkInterface = _azureProd.NetworkInterfaces.Define($"{clusterName}-nic")
                                                         .WithRegion(region)
                                                         .WithExistingResourceGroup(resourceGroupName)
                                                         .WithExistingPrimaryNetwork(virtualNetwork)
                                                         .WithSubnet(subnet)
                                                         .WithPrimaryPrivateIPAddressDynamic()
                                                         .WithExistingPrimaryPublicIPAddress(publicIpAddress)
                                                         .WithExistingNetworkSecurityGroup(networkSecurityGroup)
                                                         .WithTag("_contact_person", contactPerson)
                                                         .Create();
                    #endregion

                    log.LogInformation($"{DateAndTime()} | Created | Network Interface");

                    IStorageAccount storageAccount = _azureProd.StorageAccounts.GetByResourceGroup(resourceGroupName, $"{clusterName}vhdsa");

                    #region vm
                    IVirtualMachine createVm = _azureProd.VirtualMachines.Define($"{clusterName}-jb")
                                               .WithRegion(region)
                                               .WithExistingResourceGroup(resourceGroupName)
                                               .WithExistingPrimaryNetworkInterface(networkInterface)
                                               .WithStoredLinuxImage(MainVhdURL)
                                               .WithRootUsername(username)
                                               .WithRootPassword(password)
                                               .WithComputerName(username)
                                               .WithBootDiagnostics(storageAccount)
                                               .WithSize(VirtualMachineSizeTypes.StandardD2sV3)
                                               .WithTag("_contact_person", contactPerson)
                                               .Create();
                    #endregion

                    log.LogInformation($"{DateAndTime()} | Created | Main Virtual Machine");

                    #region LMS IP
                    IPublicIPAddress publicIPAddressLMS = _azureProd.PublicIPAddresses.Define($"{clusterName}-lms-ip")
                                                          .WithRegion(region)
                                                          .WithExistingResourceGroup(resourceGroupName)
                                                          .WithDynamicIP()
                                                          .WithLeafDomainLabel($"{clusterName}-lms-ip")
                                                          .WithTag("_contact_person", contactPerson)
                                                          .Create();
                    #endregion

                    log.LogInformation($"{DateAndTime()} | Created | LMS Public IP Address");

                    #region CMS IP
                    IPublicIPAddress publicIPAddressCMS = _azureProd.PublicIPAddresses.Define($"{clusterName}-cms-ip")
                                                          .WithRegion(region)
                                                          .WithExistingResourceGroup(resourceGroupName)
                                                          .WithDynamicIP()
                                                          .WithLeafDomainLabel($"{clusterName}-cms-ip")
                                                          .WithTag("_contact_person", contactPerson)
                                                          .Create();
                    #endregion

                    log.LogInformation($"{DateAndTime()} | Created | CMS Public IP Address");

                    #region LoadBalancer
                    ILoadBalancer loadBalancer = _azureProd.LoadBalancers.Define($"{clusterName}-lb")
                                                 .WithRegion(region)
                                                 .WithExistingResourceGroup(resourceGroupName)

                                                 .DefineLoadBalancingRule("LBRuleCMS")
                                                 .WithProtocol(TransportProtocol.Tcp)
                                                 .FromFrontend("CMS")
                                                 .FromFrontendPort(80)
                                                 .ToBackend($"{clusterName}-bepool")
                                                 .ToBackendPort(18010)
                                                 .WithProbe("tcpProbeCMS")
                                                 .WithFloatingIPDisabled()
                                                 .Attach()

                                                 .DefineLoadBalancingRule("LBRuleCMS_SSL")
                                                 .WithProtocol(TransportProtocol.Tcp)
                                                 .FromFrontend("CMS")
                                                 .FromFrontendPort(443)
                                                 .ToBackend($"{clusterName}-bepool")
                                                 .ToBackendPort(48010)
                                                 .WithProbe("tcpProbeCMSSSL")
                                                 .WithFloatingIPDisabled()
                                                 .Attach()

                                                 .DefineLoadBalancingRule("LBRuleLMS")
                                                 .WithProtocol(TransportProtocol.Tcp)
                                                 .FromFrontend("LMS")
                                                 .FromFrontendPort(80)
                                                 .ToBackend($"{clusterName}-bepool")
                                                 .ToBackendPort(80)
                                                 .WithProbe("tcpProbeLMS")
                                                 .WithFloatingIPDisabled()
                                                 .Attach()

                                                 .DefineLoadBalancingRule("LBRuleLMS_SSL")
                                                 .WithProtocol(TransportProtocol.Tcp)
                                                 .FromFrontend("LMS")
                                                 .FromFrontendPort(443)
                                                 .ToBackend($"{clusterName}-bepool")
                                                 .ToBackendPort(443)
                                                 .WithProbe("tcpProbeLMSSSL")
                                                 .WithFloatingIPDisabled()
                                                 .Attach()

                                                 .DefineBackend($"{clusterName}-bepool")
                                                 .WithExistingVirtualMachines(createVm)
                                                 .Attach()

                                                 .DefinePublicFrontend("LMS")
                                                 .WithExistingPublicIPAddress(publicIPAddressLMS)
                                                 .Attach()

                                                 .DefinePublicFrontend("CMS")
                                                 .WithExistingPublicIPAddress(publicIPAddressCMS)
                                                 .Attach()

                                                 .DefineHttpProbe("tcpProbeCMS")
                                                 .WithRequestPath("/heartbeat")
                                                 .WithPort(18010)
                                                 .WithIntervalInSeconds(5)
                                                 .WithNumberOfProbes(6)
                                                 .Attach()

                                                 .DefineTcpProbe("tcpProbeCMSSSL")
                                                 .WithPort(48010)
                                                 .WithIntervalInSeconds(5)
                                                 .WithNumberOfProbes(6)
                                                 .Attach()

                                                 .DefineHttpProbe("tcpProbeLMS")
                                                 .WithRequestPath("/heartbeat")
                                                 .WithPort(80)
                                                 .WithIntervalInSeconds(5)
                                                 .WithNumberOfProbes(6)
                                                 .Attach()

                                                 .DefineTcpProbe("tcpProbeLMSSSL")
                                                 .WithPort(443)
                                                 .WithIntervalInSeconds(5)
                                                 .WithNumberOfProbes(6)
                                                 .Attach()
                                                 .WithTag("_contact_person", contactPerson)
                                                 .Create();
                    #endregion

                    log.LogInformation($"{DateAndTime()} | Created | Load Balancer");

                    #region tm
                    IWithEndpoint tmDefinitionLMS = _azureProd.TrafficManagerProfiles
                                                    .Define($"{clusterName}-lms-tm")
                                                    .WithExistingResourceGroup(resourceGroupName)
                                                    .WithLeafDomainLabel($"{clusterName}-lms-tm")
                                                    .WithPriorityBasedRouting();
                    ICreatable <ITrafficManagerProfile> tmCreatableLMS = null;

                    tmCreatableLMS = tmDefinitionLMS
                                     .DefineExternalTargetEndpoint($"{clusterName}-lms-tm")
                                     .ToFqdn(publicIPAddressLMS.Fqdn)
                                     .FromRegion(region)
                                     .WithRoutingPriority(1)
                                     .Attach()
                                     .WithTag("_contact_person", contactPerson);

                    ITrafficManagerProfile trafficManagerProfileLMS = tmCreatableLMS.Create();

                    log.LogInformation($"{DateAndTime()} | Created | LMS Traffic Manager");

                    IWithEndpoint tmDefinitionCMS = _azureProd.TrafficManagerProfiles
                                                    .Define($"{clusterName}-cms-tm")
                                                    .WithExistingResourceGroup(resourceGroupName)
                                                    .WithLeafDomainLabel($"{clusterName}-cms-tm")
                                                    .WithPriorityBasedRouting();
                    ICreatable <ITrafficManagerProfile> tmCreatableCMS = null;

                    tmCreatableCMS = tmDefinitionCMS
                                     .DefineExternalTargetEndpoint($"{clusterName}-cms-tm")
                                     .ToFqdn(publicIPAddressCMS.Fqdn)
                                     .FromRegion(region)
                                     .WithRoutingPriority(1)
                                     .Attach()
                                     .WithTag("_contact_person", contactPerson);

                    ITrafficManagerProfile trafficManagerProfileCMS = tmCreatableCMS.Create();

                    log.LogInformation($"{DateAndTime()} | Created | CMS Traffic Manager");

                    #endregion

                    #endregion

                    if (!isSingleInstance)
                    {
                        #region mysql
                        INetworkSecurityGroup networkSecurityGroupmysql = _azureProd.NetworkSecurityGroups.Define($"{clusterName}-mysql-nsg")
                                                                          .WithRegion(region)
                                                                          .WithExistingResourceGroup(resourceGroup)
                                                                          .DefineRule("ALLOW-SSH")
                                                                          .AllowInbound()
                                                                          .FromAnyAddress()
                                                                          .FromAnyPort()
                                                                          .ToAnyAddress()
                                                                          .ToPort(22)
                                                                          .WithProtocol(SecurityRuleProtocol.Tcp)
                                                                          .WithPriority(100)
                                                                          .WithDescription("Allow SSH")
                                                                          .Attach()
                                                                          .DefineRule("mysql")
                                                                          .AllowInbound()
                                                                          .FromAnyAddress()
                                                                          .FromAnyPort()
                                                                          .ToAnyAddress()
                                                                          .ToPort(3306)
                                                                          .WithProtocol(SecurityRuleProtocol.Tcp)
                                                                          .WithPriority(101)
                                                                          .WithDescription("mysql")
                                                                          .Attach()
                                                                          .WithTag("_contact_person", contactPerson)
                                                                          .Create();

                        log.LogInformation($"{DateAndTime()} | Created | MySQL Network Security Group");

                        INetworkInterface networkInterfacemysql = _azureProd.NetworkInterfaces.Define($"{clusterName}-mysql-nic")
                                                                  .WithRegion(region)
                                                                  .WithExistingResourceGroup(resourceGroup)
                                                                  .WithExistingPrimaryNetwork(virtualNetwork)
                                                                  .WithSubnet(subnet)
                                                                  .WithPrimaryPrivateIPAddressDynamic()
                                                                  .WithExistingNetworkSecurityGroup(networkSecurityGroupmysql)
                                                                  .WithTag("_contact_person", contactPerson)
                                                                  .Create();

                        log.LogInformation($"{DateAndTime()} | Created | MySQL Network Interface");

                        IVirtualMachine createVmmysql = _azureProd.VirtualMachines.Define($"{clusterName}-mysql")
                                                        .WithRegion(region)
                                                        .WithExistingResourceGroup(resourceGroup)
                                                        .WithExistingPrimaryNetworkInterface(networkInterfacemysql)
                                                        .WithStoredLinuxImage(MysqlVhdURL)
                                                        .WithRootUsername(username)
                                                        .WithRootPassword(password)
                                                        .WithComputerName("mysql")
                                                        .WithBootDiagnostics(storageAccount)
                                                        .WithSize(VirtualMachineSizeTypes.StandardD2V2)
                                                        .WithTag("_contact_person", contactPerson)
                                                        .Create();

                        log.LogInformation($"{DateAndTime()} | Created | MySQL Virtual Machine");

                        #endregion

                        #region mongodb
                        INetworkSecurityGroup networkSecurityGroupmongo = _azureProd.NetworkSecurityGroups.Define($"{clusterName}-mongo-nsg")
                                                                          .WithRegion(region)
                                                                          .WithExistingResourceGroup(resourceGroup)
                                                                          .DefineRule("ALLOW-SSH")
                                                                          .AllowInbound()
                                                                          .FromAnyAddress()
                                                                          .FromAnyPort()
                                                                          .ToAnyAddress()
                                                                          .ToPort(22)
                                                                          .WithProtocol(SecurityRuleProtocol.Tcp)
                                                                          .WithPriority(100)
                                                                          .WithDescription("Allow SSH")
                                                                          .Attach()
                                                                          .DefineRule("mongodb")
                                                                          .AllowInbound()
                                                                          .FromAnyAddress()
                                                                          .FromAnyPort()
                                                                          .ToAnyAddress()
                                                                          .ToPort(27017)
                                                                          .WithProtocol(SecurityRuleProtocol.Tcp)
                                                                          .WithPriority(101)
                                                                          .WithDescription("mongodb")
                                                                          .Attach()
                                                                          .WithTag("_contact_person", contactPerson)
                                                                          .Create();

                        log.LogInformation($"{DateAndTime()} | Created | MongoDB Network Security Group");

                        INetworkInterface networkInterfacemongo = _azureProd.NetworkInterfaces.Define($"{clusterName}-mongo-nic")
                                                                  .WithRegion(region)
                                                                  .WithExistingResourceGroup(resourceGroup)
                                                                  .WithExistingPrimaryNetwork(virtualNetwork)
                                                                  .WithSubnet(subnet)
                                                                  .WithPrimaryPrivateIPAddressDynamic()
                                                                  .WithExistingNetworkSecurityGroup(networkSecurityGroupmongo)
                                                                  .WithTag("_contact_person", contactPerson)
                                                                  .Create();

                        log.LogInformation($"{DateAndTime()} | Created | MongoDB Network Interface");

                        IVirtualMachine createVmmongo = _azureProd.VirtualMachines.Define($"{clusterName}-mongo")
                                                        .WithRegion(region)
                                                        .WithExistingResourceGroup(resourceGroup)
                                                        .WithExistingPrimaryNetworkInterface(networkInterfacemongo)
                                                        .WithStoredLinuxImage(MongoVhdURL)
                                                        .WithRootUsername(username)
                                                        .WithRootPassword(password)
                                                        .WithComputerName("mongo")
                                                        .WithBootDiagnostics(storageAccount)
                                                        .WithSize(VirtualMachineSizeTypes.StandardD2V2)
                                                        .WithTag("_contact_person", contactPerson)
                                                        .Create();

                        log.LogInformation($"{DateAndTime()} | Created | MongoDB Virtual Machine");

                        #endregion

                        log.LogInformation("deploying 3 instance");

                        Utils.Email(smtpClient, "MySQL Instance Deployed Successfully", log, mailMessage);
                    }


                    string cmsUrl = trafficManagerProfileCMS.DnsLabel;
                    string lmsUrl = trafficManagerProfileLMS.DnsLabel;

                    Utils.Email(smtpClient, "Your Learning Platform is Ready to use." +
                                "<br/>"
                                + $"<a href=\"{lmsUrl}\">LMS</a>" +
                                "<br/>" +
                                $"<a href=\"{cmsUrl}\">CMS</a>"
                                , log, mailMessage);
                    log.LogInformation($"Done");
                }
                catch (Exception e)
                {
                    log.LogInformation($"{DateAndTime()} | Error | {e.Message}");

                    return(new BadRequestObjectResult(false));
                }

                log.LogInformation($"{DateAndTime()} | Done");
                return(new OkObjectResult(true));
            }
        }
Beispiel #20
0
 /// <summary>
 /// Associates an existing network security group with the network interface.
 /// </summary>
 /// <param name="networkSecurityGroup">An existing network security group.</param>
 /// <return>The next stage of the network interface update.</return>
 NetworkInterface.Update.IUpdate NetworkInterface.Update.IWithNetworkSecurityGroup.WithExistingNetworkSecurityGroup(INetworkSecurityGroup networkSecurityGroup)
 {
     return this.WithExistingNetworkSecurityGroup(networkSecurityGroup) as NetworkInterface.Update.IUpdate;
 }
Beispiel #21
0
 /// <summary>
 /// Associates an existing network security group with the network interface.
 /// </summary>
 /// <param name="networkSecurityGroup">An existing network security group.</param>
 /// <return>The next stage of the definition.</return>
 NetworkInterface.Definition.IWithCreate NetworkInterface.Definition.IWithNetworkSecurityGroup.WithExistingNetworkSecurityGroup(INetworkSecurityGroup networkSecurityGroup)
 {
     return this.WithExistingNetworkSecurityGroup(networkSecurityGroup) as NetworkInterface.Definition.IWithCreate;
 }
        public void UnfinishedTest()
        {
            string vnetName1 = SdkContext.RandomResourceName("vnet1", 20);
            string vnetName2 = SdkContext.RandomResourceName("vnet2", 20);
            string vnet1FrontEndSubnetName    = "frontend";
            string vnet1BackEndSubnetName     = "backend";
            string vnet1FrontEndSubnetNsgName = "frontendnsg";
            string vnet1BackEndSubnetNsgName  = "backendnsg";
            string frontEndVMName             = SdkContext.RandomResourceName("fevm", 24);
            string backEndVMName = SdkContext.RandomResourceName("bevm", 24);
            string publicIPAddressLeafDNSForFrontEndVM = SdkContext.RandomResourceName("pip1", 24);

            INetworkManager manager = TestHelper.CreateNetworkManager();

            string rgName = SdkContext.RandomResourceName("rgNEMV", 24);
            INetworkSecurityGroup backEndSubnetNsg = manager.NetworkSecurityGroups
                                                     .Define(vnet1BackEndSubnetNsgName)
                                                     .WithRegion(Region.USEast)
                                                     .WithExistingResourceGroup(rgName)
                                                     .DefineRule("DenyInternetInComing")
                                                     .DenyInbound()
                                                     .FromAddress("INTERNET")
                                                     .FromAnyPort()
                                                     .ToAnyAddress()
                                                     .ToAnyPort()
                                                     .WithAnyProtocol()
                                                     .Attach()
                                                     .DefineRule("DenyInternetOutGoing")
                                                     .DenyOutbound()
                                                     .FromAnyAddress()
                                                     .FromAnyPort()
                                                     .ToAddress("INTERNET")
                                                     .ToAnyPort()
                                                     .WithAnyProtocol()
                                                     .Attach()
                                                     .Create();

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

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

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

            INetwork virtualNetwork2 = manager.Networks
                                       .Define(vnetName2)
                                       .WithRegion(Region.USEast)
                                       .WithNewResourceGroup(rgName)
                                       .Create();


            foreach (INetwork virtualNetwork in manager.Networks.ListByResourceGroup(rgName))
            {
            }


            manager.Networks.DeleteById(virtualNetwork2.Id);
        }
Beispiel #23
0
        static async Task <List <Task <INetworkInterface> > > CreateNICWithRetry(IAzure azure, string resourceGroupName,
                                                                                 ArgsOption agentConfig, INetwork network, List <Task <IPublicIPAddress> > publicIpTaskList,
                                                                                 string subNetName, INetworkSecurityGroup nsg, Region region)
        {
            var j           = 0;
            var i           = 0;
            var maxTry      = agentConfig.MaxRetry;
            var nicTaskList = new List <Task <INetworkInterface> >();

            while (j < maxTry)
            {
                try
                {
                    var allowAcceleratedNet = false;
                    if (agentConfig.CandidateOfAcceleratedNetVM != null)
                    {
                        allowAcceleratedNet = CheckValidVMForAcceleratedNet(agentConfig.CandidateOfAcceleratedNetVM, agentConfig.VmSize);
                    }
                    for (i = 0; i < agentConfig.VmCount; i++)
                    {
                        var nicName = agentConfig.Prefix + Convert.ToString(i) + "NIC";
                        Task <INetworkInterface> networkInterface = null;
                        if (allowAcceleratedNet && agentConfig.AcceleratedNetwork)
                        {
                            networkInterface = azure.NetworkInterfaces.Define(nicName)
                                               .WithRegion(region)
                                               .WithExistingResourceGroup(resourceGroupName)
                                               .WithExistingPrimaryNetwork(network)
                                               .WithSubnet(subNetName)
                                               .WithPrimaryPrivateIPAddressDynamic()
                                               .WithExistingPrimaryPublicIPAddress(publicIpTaskList[i].Result)
                                               .WithExistingNetworkSecurityGroup(nsg)
                                               .WithAcceleratedNetworking()
                                               .CreateAsync();
                            Util.Log("Accelerated Network is enabled!");
                        }
                        else
                        {
                            Util.Log("Accelerated Network is disabled!");
                            networkInterface = azure.NetworkInterfaces.Define(nicName)
                                               .WithRegion(region)
                                               .WithExistingResourceGroup(resourceGroupName)
                                               .WithExistingPrimaryNetwork(network)
                                               .WithSubnet(subNetName)
                                               .WithPrimaryPrivateIPAddressDynamic()
                                               .WithExistingPrimaryPublicIPAddress(publicIpTaskList[i].Result)
                                               .WithExistingNetworkSecurityGroup(nsg)
                                               .CreateAsync();
                        }
                        nicTaskList.Add(networkInterface);
                    }
                    await Task.WhenAll(nicTaskList.ToArray());

                    return(nicTaskList);
                }
                catch (Exception e)
                {
                    Util.Log(e.ToString());
                    nicTaskList.Clear();

                    var   allNICs = azure.NetworkInterfaces.ListByResourceGroupAsync(resourceGroupName);
                    await allNICs;
                    var   ids        = new List <string>();
                    var   enumerator = allNICs.Result.GetEnumerator();
                    while (enumerator.MoveNext())
                    {
                        ids.Add(enumerator.Current.Id);
                    }
                    await azure.NetworkInterfaces.DeleteByIdsAsync(ids);

                    if (j + 1 < maxTry)
                    {
                        Util.Log($"Fail to create NIC for {e.Message} and will retry");
                    }
                    else
                    {
                        Util.Log($"Fail to create NIC for {e.Message} and retry has reached max limit, will return with failure");
                    }
                }
                j++;
            }
            return(null);
        }
 /// <summary>
 /// Assigns an existing network security group to this subnet.
 /// </summary>
 /// <param name="nsg">The network security group to assign.</param>
 /// <return>The next stage of the definition.</return>
 Subnet.Definition.IWithAttach <Network.Definition.IWithCreateAndSubnet> Subnet.Definition.IWithNetworkSecurityGroup <Network.Definition.IWithCreateAndSubnet> .WithExistingNetworkSecurityGroup(INetworkSecurityGroup nsg)
 {
     return(this.WithExistingNetworkSecurityGroup(nsg));
 }
 private void WriteNetworkSecurityGroup(INetworkSecurityGroup networkSecurityGroup)
 {
     WriteObject(networkSecurityGroup, true);
 }
Beispiel #26
0
 ///GENMHASH:7F6A7E961EA5A11F2B8013E54123A7D0:9C961E2C320E3354B3C71EF99831C7AB
 private void ClearCachedRelatedResources()
 {
     networkSecurityGroup = null;
 }
        // Helper method to pre-create infrastructure to test Network Watcher
        ICreatedResources <IVirtualMachine> EnsureNetwork(INetworkManager networkManager, IComputeManager computeManager, String groupName)
        {
            IVirtualMachines vms = computeManager.VirtualMachines;

            // Create an NSG
            INetworkSecurityGroup nsg = networkManager.NetworkSecurityGroups.Define(SdkContext.RandomResourceName("nsg", 8))
                                        .WithRegion(REGION)
                                        .WithNewResourceGroup(groupName)
                                        .Create();

            // Create a network for the VMs
            INetwork network = networkManager.Networks.Define(SdkContext.RandomResourceName("net", 8))
                               .WithRegion(REGION)
                               .WithExistingResourceGroup(groupName)
                               .WithAddressSpace("10.0.0.0/28")
                               .DefineSubnet("subnet1")
                               .WithAddressPrefix("10.0.0.0/29")
                               .WithExistingNetworkSecurityGroup(nsg)
                               .Attach()
                               .WithSubnet("subnet2", "10.0.0.8/29")
                               .Create();

            INetworkInterface nic = networkManager.NetworkInterfaces.Define(SdkContext.RandomResourceName("ni", 8))
                                    .WithRegion(REGION)
                                    .WithExistingResourceGroup(groupName)
                                    .WithNewPrimaryNetwork("10.0.0.0/28")
                                    .WithPrimaryPrivateIPAddressDynamic()
                                    .WithNewPrimaryPublicIPAddress(SdkContext.RandomResourceName("pip", 8))
                                    .WithIPForwarding()
                                    .WithExistingNetworkSecurityGroup(nsg)
                                    .Create();

            // Create the requested number of VM definitions
            String userName      = "******";
            var    vmDefinitions = new List <ICreatable <IVirtualMachine> >();

            var vm1 = vms.Define(SdkContext.RandomResourceName("vm", 15))
                      .WithRegion(REGION)
                      .WithExistingResourceGroup(groupName)
                      .WithExistingPrimaryNetworkInterface(nic)
                      .WithPopularLinuxImage(KnownLinuxVirtualMachineImage.UbuntuServer14_04_Lts)
                      .WithRootUsername(userName)
                      .WithRootPassword("Abcdef.123456")
                      .WithSize(VirtualMachineSizeTypes.StandardA1)
                      .DefineNewExtension("packetCapture")
                      .WithPublisher("Microsoft.Azure.NetworkWatcher")
                      .WithType("NetworkWatcherAgentLinux")
                      .WithVersion("1.4")
                      .WithMinorVersionAutoUpgrade()
                      .Attach();

            String vmName = SdkContext.RandomResourceName("vm", 15);

            ICreatable <IVirtualMachine> vm2 = vms.Define(vmName)
                                               .WithRegion(REGION)
                                               .WithExistingResourceGroup(groupName)
                                               .WithExistingPrimaryNetwork(network)
                                               .WithSubnet(network.Subnets.Values.First().Name)
                                               .WithPrimaryPrivateIPAddressDynamic()
                                               .WithoutPrimaryPublicIPAddress()
                                               .WithPopularLinuxImage(KnownLinuxVirtualMachineImage.UbuntuServer14_04_Lts)
                                               .WithRootUsername(userName)
                                               .WithRootPassword("Abcdef.123456")
                                               .WithSize(VirtualMachineSizeTypes.StandardA1);

            vmDefinitions.Add(vm1);
            vmDefinitions.Add(vm2);
            vms.Create(vmDefinitions);
            var createdVMs2 = vms.Create(vmDefinitions);

            return(createdVMs2);
        }
 /// <summary>
 /// Assigns an existing network security group to this subnet.
 /// </summary>
 /// <param name="nsg">The network security group to assign.</param>
 /// <return>The next stage of the update.</return>
 Subnet.Update.IUpdate Subnet.Update.IWithNetworkSecurityGroup.WithExistingNetworkSecurityGroup(INetworkSecurityGroup nsg)
 {
     return(this.WithExistingNetworkSecurityGroup(nsg));
 }
        /**
         * Create a virtual network with two Subnets – frontend and backend
         * Frontend allows HTTP in and denies Internet out
         * Backend denies Internet in and Internet out
         * Create m Linux virtual machines in the frontend
         * Create m Windows virtual machines in the backend.
         */
        public static void RunSample(IAzure azure)
        {
            string rgName             = SdkContext.RandomResourceName("rgNEPP", 24);
            string frontEndNSGName    = SdkContext.RandomResourceName("fensg", 24);
            string backEndNSGName     = SdkContext.RandomResourceName("bensg", 24);
            string networkName        = SdkContext.RandomResourceName("vnetCOMV", 24);
            string storageAccountName = SdkContext.RandomResourceName("stgCOMV", 20);

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

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

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

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

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

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

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

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

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

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

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

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

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

                for (int i = 0; i < FrontendVMCount; i++)
                {
                    var creatableVirtualMachine = azure.VirtualMachines
                                                  .Define("VM-FE-" + i)
                                                  .WithRegion(Region.USEast)
                                                  .WithExistingResourceGroup(resourceGroup)
                                                  .WithExistingPrimaryNetwork(network)
                                                  .WithSubnet("Front-end")
                                                  .WithPrimaryPrivateIPAddressDynamic()
                                                  .WithoutPrimaryPublicIPAddress()
                                                  .WithPopularLinuxImage(KnownLinuxVirtualMachineImage.UbuntuServer16_04_Lts)
                                                  .WithRootUsername(UserName)
                                                  .WithRootPassword(Password)
                                                  .WithSize(VirtualMachineSizeTypes.Parse("Standard_D2a_v4"))
                                                  .WithNewStorageAccount(creatableStorageAccount);
                    frontendCreatableVirtualMachines.Add(creatableVirtualMachine);
                }

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

                for (int i = 0; i < BackendVMCount; i++)
                {
                    var creatableVirtualMachine = azure.VirtualMachines
                                                  .Define("VM-BE-" + i)
                                                  .WithRegion(Region.USEast)
                                                  .WithExistingResourceGroup(resourceGroup)
                                                  .WithExistingPrimaryNetwork(network)
                                                  .WithSubnet("Back-end")
                                                  .WithPrimaryPrivateIPAddressDynamic()
                                                  .WithoutPrimaryPublicIPAddress()
                                                  .WithPopularLinuxImage(KnownLinuxVirtualMachineImage.UbuntuServer16_04_Lts)
                                                  .WithRootUsername(UserName)
                                                  .WithRootPassword(Password)
                                                  .WithSize(VirtualMachineSizeTypes.Parse("Standard_D2a_v4"))
                                                  .WithNewStorageAccount(creatableStorageAccount);
                    backendCreatableVirtualMachines.Add(creatableVirtualMachine);
                }

                var startTime = DateTimeOffset.Now.UtcDateTime;
                Utilities.Log("Creating the virtual machines");

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

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

                var endTime = DateTimeOffset.Now.UtcDateTime;
                Utilities.Log("Created virtual machines");

                foreach (var virtualMachine in virtualMachines)
                {
                    Utilities.Log(virtualMachine.Id);
                }

                Utilities.Log($"Virtual machines create: took {(endTime - startTime).TotalSeconds } seconds");
            }
            finally
            {
                Utilities.Log($"Deleting resource group : {rgName}");
                azure.ResourceGroups.DeleteByName(rgName);
                Utilities.Log($"Deleted resource group : {rgName}");
            }
        }
 /// <summary>
 /// Assigns an existing network security group to this subnet.
 /// </summary>
 /// <param name="nsg">The network security group to assign.</param>
 /// <return>The next stage of the definition.</return>
 Subnet.UpdateDefinition.IWithAttach <Network.Update.IUpdate> Subnet.UpdateDefinition.IWithNetworkSecurityGroup <Network.Update.IUpdate> .WithExistingNetworkSecurityGroup(INetworkSecurityGroup nsg)
 {
     return(this.WithExistingNetworkSecurityGroup(nsg));
 }
Beispiel #31
0
        public void CreateUpdate()
        {
            using (var context = FluentMockContext.Start(GetType().FullName))
            {
                var testId = TestUtilities.GenerateName("");

                string newName   = "net" + testId;
                var    region    = Region.USWest;
                var    groupName = "rg" + testId;

                try
                {
                    // Create an NSG
                    var manager = TestHelper.CreateNetworkManager();
                    var nsg     = manager.NetworkSecurityGroups.Define("nsg" + testId)
                                  .WithRegion(region)
                                  .WithNewResourceGroup(groupName)
                                  .Create();

                    // Create a network
                    INetwork network = manager.Networks.Define(newName)
                                       .WithRegion(region)
                                       .WithNewResourceGroup(groupName)
                                       .WithAddressSpace("10.0.0.0/28")
                                       .WithAddressSpace("10.1.0.0/28")
                                       .WithSubnet("subnetA", "10.0.0.0/29")
                                       .DefineSubnet("subnetB")
                                       .WithAddressPrefix("10.0.0.8/29")
                                       .WithExistingNetworkSecurityGroup(nsg)
                                       .Attach()
                                       .Create();

                    // Verify address spaces
                    Assert.Equal(2, network.AddressSpaces.Count);
                    Assert.Contains("10.1.0.0/28", network.AddressSpaces);

                    // Verify subnets
                    Assert.Equal(2, network.Subnets.Count);
                    ISubnet subnet = network.Subnets["subnetA"];
                    Assert.Equal("10.0.0.0/29", subnet.AddressPrefix);
                    subnet = network.Subnets["subnetB"];
                    Assert.Equal("10.0.0.8/29", subnet.AddressPrefix);
                    Assert.Equal(nsg.Id, subnet.NetworkSecurityGroupId, ignoreCase: true);

                    // Verify NSG
                    var subnets = nsg.Refresh().ListAssociatedSubnets();
                    Assert.Equal(1, subnets.Count);
                    subnet = subnets[0];
                    Assert.Equal("subnetB", subnet.Name, ignoreCase: true);
                    Assert.Equal(subnet.Parent.Name, newName, ignoreCase: true);
                    Assert.NotNull(subnet.NetworkSecurityGroupId);
                    INetworkSecurityGroup nsg2 = subnet.GetNetworkSecurityGroup();
                    Assert.NotNull(nsg2);
                    Assert.Equal(nsg2.Id, nsg.Id, ignoreCase: true);

                    network = manager.Networks.GetByResourceGroup(groupName, newName);
                    network = network.Update()
                              .WithTag("tag1", "value1")
                              .WithTag("tag2", "value2")
                              .WithAddressSpace("141.25.0.0/16")
                              .WithoutAddressSpace("10.1.0.0/28")
                              .WithSubnet("subnetC", "141.25.0.0/29")
                              .WithoutSubnet("subnetA")
                              .UpdateSubnet("subnetB")
                              .WithAddressPrefix("141.25.0.8/29")
                              .WithoutNetworkSecurityGroup()
                              .Parent()
                              .DefineSubnet("subnetD")
                              .WithAddressPrefix("141.25.0.16/29")
                              .WithExistingNetworkSecurityGroup(nsg)
                              .Attach()
                              .Apply();

                    // Verify address spaces
                    Assert.Equal(2, network.AddressSpaces.Count);
                    Assert.DoesNotContain("10.1.0.0/28", network.AddressSpaces);

                    // Verify subnets
                    Assert.Equal(3, network.Subnets.Count);
                    Assert.False(network.Subnets.ContainsKey("subnetA"));

                    Assert.True(network.Subnets.ContainsKey("subnetB"));
                    subnet = network.Subnets["subnetB"];
                    Assert.Equal("141.25.0.8/29", subnet.AddressPrefix);
                    Assert.Null(subnet.NetworkSecurityGroupId);

                    Assert.True(network.Subnets.ContainsKey("subnetC"));
                    subnet = network.Subnets["subnetC"];
                    Assert.Equal("141.25.0.0/29", subnet.AddressPrefix);
                    Assert.Null(subnet.NetworkSecurityGroupId);

                    Assert.True(network.Subnets.ContainsKey("subnetD"));
                    subnet = network.Subnets["subnetD"];
                    Assert.NotNull(subnet);
                    Assert.Equal("141.25.0.16/29", subnet.AddressPrefix);
                    Assert.Equal(nsg.Id, subnet.NetworkSecurityGroupId, ignoreCase: true);

                    Assert.True(network.Tags.ContainsKey("tag1"));

                    manager.Networks.DeleteById(network.Id);
                    manager.NetworkSecurityGroups.DeleteById(nsg.Id);
                    manager.ResourceManager.ResourceGroups.BeginDeleteByName(groupName);
                }
                finally
                {
                    try
                    {
                        TestHelper.CreateResourceManager().ResourceGroups.DeleteByName(groupName);
                    }
                    catch { }
                }
            }
        }