Example #1
0
        private void Run()
        {
            // VirtualMachineProfile
            if (this.VirtualMachineScaleSet.VirtualMachineProfile == null)
            {
                this.VirtualMachineScaleSet.VirtualMachineProfile = new PSVirtualMachineScaleSetVMProfile();
            }

            // NetworkProfile
            if (this.VirtualMachineScaleSet.VirtualMachineProfile.NetworkProfile == null)
            {
                this.VirtualMachineScaleSet.VirtualMachineProfile.NetworkProfile = new VirtualMachineScaleSetNetworkProfile();
            }

            if (this.IsParameterBound(c => c.NetworkApiVersion))
            {
                this.VirtualMachineScaleSet.VirtualMachineProfile.NetworkProfile.NetworkApiVersion = this.NetworkApiVersion;
            }
            else
            {
                // If networkApiVersion is not specified, reuse the existing one in network profile if not null,
                // else use default version
                this.VirtualMachineScaleSet.VirtualMachineProfile.NetworkProfile.NetworkApiVersion = this.VirtualMachineScaleSet.VirtualMachineProfile.NetworkProfile.NetworkApiVersion
                                                                                                     ?? Microsoft.Azure.Management.Compute.Models.NetworkApiVersion.TwoZeroTwoZeroHyphenMinusOneOneHyphenMinusZeroOne;
            }

            // NetworkInterfaceConfigurations
            if (this.VirtualMachineScaleSet.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations == null)
            {
                this.VirtualMachineScaleSet.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations = new List <VirtualMachineScaleSetNetworkConfiguration>();
            }

            var vNetworkInterfaceConfigurations = new VirtualMachineScaleSetNetworkConfiguration();

            vNetworkInterfaceConfigurations.Name    = this.IsParameterBound(c => c.Name) ? this.Name : null;
            vNetworkInterfaceConfigurations.Primary = this.IsParameterBound(c => c.Primary) ? this.Primary : (bool?)null;
            vNetworkInterfaceConfigurations.EnableAcceleratedNetworking = this.EnableAcceleratedNetworking.IsPresent;
            vNetworkInterfaceConfigurations.EnableIPForwarding          = this.EnableIPForwarding.IsPresent;
            vNetworkInterfaceConfigurations.Id = this.IsParameterBound(c => c.Id) ? this.Id : null;
            if (this.IsParameterBound(c => c.NetworkSecurityGroupId))
            {
                // NetworkSecurityGroup
                vNetworkInterfaceConfigurations.NetworkSecurityGroup    = new SubResource();
                vNetworkInterfaceConfigurations.NetworkSecurityGroup.Id = this.NetworkSecurityGroupId;
            }
            if (this.IsParameterBound(c => c.DnsSettingsDnsServer))
            {
                // DnsSettings
                vNetworkInterfaceConfigurations.DnsSettings            = new VirtualMachineScaleSetNetworkConfigurationDnsSettings();
                vNetworkInterfaceConfigurations.DnsSettings.DnsServers = this.DnsSettingsDnsServer;
            }
            vNetworkInterfaceConfigurations.IpConfigurations = this.IsParameterBound(c => c.IpConfiguration) ? this.IpConfiguration : null;
            this.VirtualMachineScaleSet.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations.Add(vNetworkInterfaceConfigurations);
            WriteObject(this.VirtualMachineScaleSet);
        }
Example #2
0
        private void Run()
        {
            // VirtualMachineProfile
            if (this.VirtualMachineScaleSet.VirtualMachineProfile == null)
            {
                this.VirtualMachineScaleSet.VirtualMachineProfile = new PSVirtualMachineScaleSetVMProfile();
            }

            // NetworkProfile
            if (this.VirtualMachineScaleSet.VirtualMachineProfile.NetworkProfile == null)
            {
                this.VirtualMachineScaleSet.VirtualMachineProfile.NetworkProfile = new VirtualMachineScaleSetNetworkProfile();
            }

            if (this.IsParameterBound(c => c.NetworkApiVersion))
            {
                this.VirtualMachineScaleSet.VirtualMachineProfile.NetworkProfile.NetworkApiVersion = this.NetworkApiVersion;
            }

            // NetworkInterfaceConfigurations
            if (this.VirtualMachineScaleSet.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations == null)
            {
                this.VirtualMachineScaleSet.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations = new List <VirtualMachineScaleSetNetworkConfiguration>();
            }

            var vNetworkInterfaceConfigurations = new VirtualMachineScaleSetNetworkConfiguration();

            vNetworkInterfaceConfigurations.Name    = this.IsParameterBound(c => c.Name) ? this.Name : null;
            vNetworkInterfaceConfigurations.Primary = this.IsParameterBound(c => c.Primary) ? this.Primary : (bool?)null;
            vNetworkInterfaceConfigurations.EnableAcceleratedNetworking = this.EnableAcceleratedNetworking.IsPresent;
            vNetworkInterfaceConfigurations.EnableIPForwarding          = this.EnableIPForwarding.IsPresent;
            vNetworkInterfaceConfigurations.Id = this.IsParameterBound(c => c.Id) ? this.Id : null;
            if (this.IsParameterBound(c => c.NetworkSecurityGroupId))
            {
                // NetworkSecurityGroup
                vNetworkInterfaceConfigurations.NetworkSecurityGroup    = new SubResource();
                vNetworkInterfaceConfigurations.NetworkSecurityGroup.Id = this.NetworkSecurityGroupId;
            }
            if (this.IsParameterBound(c => c.DnsSettingsDnsServer))
            {
                // DnsSettings
                vNetworkInterfaceConfigurations.DnsSettings            = new VirtualMachineScaleSetNetworkConfigurationDnsSettings();
                vNetworkInterfaceConfigurations.DnsSettings.DnsServers = this.DnsSettingsDnsServer;
            }
            vNetworkInterfaceConfigurations.IpConfigurations = this.IsParameterBound(c => c.IpConfiguration) ? this.IpConfiguration : null;
            this.VirtualMachineScaleSet.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations.Add(vNetworkInterfaceConfigurations);
            WriteObject(this.VirtualMachineScaleSet);
        }
Example #3
0
        private void Run()
        {
            // VirtualMachineProfile
            if (this.VirtualMachineScaleSet.VirtualMachineProfile == null)
            {
                this.VirtualMachineScaleSet.VirtualMachineProfile = new VirtualMachineScaleSetVMProfile();
            }

            // NetworkProfile
            if (this.VirtualMachineScaleSet.VirtualMachineProfile.NetworkProfile == null)
            {
                this.VirtualMachineScaleSet.VirtualMachineProfile.NetworkProfile = new VirtualMachineScaleSetNetworkProfile();
            }

            // NetworkInterfaceConfigurations
            if (this.VirtualMachineScaleSet.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations == null)
            {
                this.VirtualMachineScaleSet.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations = new List <VirtualMachineScaleSetNetworkConfiguration>();
            }

            var vNetworkInterfaceConfigurations = new VirtualMachineScaleSetNetworkConfiguration();

            vNetworkInterfaceConfigurations.Name    = this.MyInvocation.BoundParameters.ContainsKey("Name") ? this.Name : null;
            vNetworkInterfaceConfigurations.Primary = this.MyInvocation.BoundParameters.ContainsKey("Primary") ? this.Primary : (bool?)null;
            vNetworkInterfaceConfigurations.EnableAcceleratedNetworking = this.EnableAcceleratedNetworking.IsPresent;
            vNetworkInterfaceConfigurations.EnableIPForwarding          = this.EnableIPForwarding.IsPresent;
            vNetworkInterfaceConfigurations.Id = this.MyInvocation.BoundParameters.ContainsKey("Id") ? this.Id : null;
            if (this.MyInvocation.BoundParameters.ContainsKey("NetworkSecurityGroupId"))
            {
                // NetworkSecurityGroup
                vNetworkInterfaceConfigurations.NetworkSecurityGroup    = new SubResource();
                vNetworkInterfaceConfigurations.NetworkSecurityGroup.Id = this.NetworkSecurityGroupId;
            }
            if (this.MyInvocation.BoundParameters.ContainsKey("DnsSettingsDnsServer"))
            {
                // DnsSettings
                vNetworkInterfaceConfigurations.DnsSettings            = new VirtualMachineScaleSetNetworkConfigurationDnsSettings();
                vNetworkInterfaceConfigurations.DnsSettings.DnsServers = this.DnsSettingsDnsServer;
            }
            vNetworkInterfaceConfigurations.IpConfigurations = this.MyInvocation.BoundParameters.ContainsKey("IpConfiguration") ? this.IpConfiguration : null;
            this.VirtualMachineScaleSet.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations.Add(vNetworkInterfaceConfigurations);
            WriteObject(this.VirtualMachineScaleSet);
        }
Example #4
0
        protected void CompareVmssNicConfig(VirtualMachineScaleSetNetworkConfiguration nicconfig,
                                            VirtualMachineScaleSetNetworkConfiguration outnicconfig)
        {
            if (nicconfig.IpConfigurations != null && nicconfig.IpConfigurations.Count > 0)
            {
                Assert.NotNull(outnicconfig.IpConfigurations);

                Assert.AreEqual(nicconfig.IpConfigurations.Count, outnicconfig.IpConfigurations.Count);

                foreach (var ipconfig in nicconfig.IpConfigurations)
                {
                    var outipconfig =
                        outnicconfig.IpConfigurations.First(
                            ic => string.Equals(ic.Name, ipconfig.Name, StringComparison.OrdinalIgnoreCase));
                    Assert.NotNull(outipconfig);
                    CompareIpConfigApplicationGatewayPools(ipconfig, outipconfig);
                }
            }
            else
            {
                Assert.True((outnicconfig.IpConfigurations == null) || (outnicconfig.IpConfigurations.Count == 0));
            }
        }
Example #5
0
        private VirtualMachineScaleSetNetworkProfile CreateNetworkResource(VirtualMachineScaleSetNetworkConfiguration existingNetworkConfig)
        {
            var suffix            = $"{this.Name.ToLower()}-{this.NodeType.ToLower()}";
            var publicAddressName = $"LBIP-{suffix}";
            var dnsLabel          = $"dns-{suffix}";
            var lbName            = $"LB-{suffix}";
            var nicName           = $"NIC-{suffix}";
            var ipconfigName      = $"IpCfg-{suffix}";

            var ipConfiguration = existingNetworkConfig.IpConfigurations.FirstOrDefault();

            if (ipConfiguration == null)
            {
                throw new PSInvalidOperationException(ServiceFabricProperties.Resources.InvalidVmssNetworkConfiguration);
            }

            this.addressPrefix = GetSubnetAddressPrefix(ipConfiguration);

            var publicIp = NetworkManagementClient.PublicIPAddresses.CreateOrUpdate(
                this.ResourceGroupName,
                publicAddressName,
                new PublicIPAddress()
            {
                PublicIPAllocationMethod = "Dynamic",
                Location    = GetLocation(),
                DnsSettings = new PublicIPAddressDnsSettings(dnsLabel)
            });

            var backendAddressPoolName      = "LoadBalancerBEAddressPool";
            var frontendIpConfigurationName = "LoadBalancerIPConfig";
            var probeName          = "FabricGatewayProbe";
            var probeHTTPName      = "FabricHttpGatewayProbe";
            var inboundNatPoolName = "LoadBalancerBEAddressNatPool";

            var newLoadBalancerId = string.Format(
                LoadBalancerIdFormat,
                this.NetworkManagementClient.SubscriptionId,
                this.ResourceGroupName,
                lbName);

            var newLoadBalancer = new LoadBalancer(newLoadBalancerId, lbName)
            {
                Location = GetLocation(),
                FrontendIPConfigurations = new List <FrontendIPConfiguration>()
                {
                    new FrontendIPConfiguration()
                    {
                        Name            = frontendIpConfigurationName,
                        PublicIPAddress = new PublicIPAddress()
                        {
                            Id = publicIp.Id
                        }
                    }
                },
                BackendAddressPools = new List <BackendAddressPool>()
                {
                    new BackendAddressPool()
                    {
                        Name = backendAddressPoolName
                    }
                },
                LoadBalancingRules = new List <LoadBalancingRule>()
                {
                    new LoadBalancingRule()
                    {
                        Name = "LBRule",
                        BackendAddressPool = new Management.Internal.Network.Version2017_10_01.Models.SubResource()
                        {
                            Id = string.Format(
                                BackendAddressIdFormat,
                                NetworkManagementClient.SubscriptionId,
                                this.ResourceGroupName,
                                lbName,
                                backendAddressPoolName)
                        },
                        BackendPort             = Constants.DefaultTcpPort,
                        EnableFloatingIP        = false,
                        FrontendIPConfiguration = new Management.Internal.Network.Version2017_10_01.Models.SubResource()
                        {
                            Id = string.Format(
                                FrontendIdFormat,
                                NetworkManagementClient.SubscriptionId,
                                this.ResourceGroupName,
                                lbName,
                                frontendIpConfigurationName)
                        },
                        FrontendPort         = Constants.DefaultTcpPort,
                        IdleTimeoutInMinutes = 5,
                        Protocol             = "tcp",
                        Probe = new Management.Internal.Network.Version2017_10_01.Models.SubResource()
                        {
                            Id = string.Format(
                                ProbeIdFormat,
                                NetworkManagementClient.SubscriptionId,
                                this.ResourceGroupName,
                                lbName,
                                probeName)
                        }
                    },
                    new LoadBalancingRule()
                    {
                        Name = "LBHttpRule",
                        BackendAddressPool = new Management.Internal.Network.Version2017_10_01.Models.SubResource()
                        {
                            Id = string.Format(
                                BackendAddressIdFormat,
                                NetworkManagementClient.SubscriptionId,
                                this.ResourceGroupName,
                                lbName,
                                backendAddressPoolName)
                        },
                        BackendPort             = Constants.DefaultHttpPort,
                        EnableFloatingIP        = false,
                        FrontendIPConfiguration = new Management.Internal.Network.Version2017_10_01.Models.SubResource()
                        {
                            Id = string.Format(
                                FrontendIdFormat,
                                NetworkManagementClient.SubscriptionId,
                                this.ResourceGroupName,
                                lbName,
                                frontendIpConfigurationName)
                        },
                        FrontendPort         = Constants.DefaultHttpPort,
                        IdleTimeoutInMinutes = 5,
                        Protocol             = "tcp",
                        Probe = new Management.Internal.Network.Version2017_10_01.Models.SubResource()
                        {
                            Id = string.Format(
                                ProbeIdFormat,
                                NetworkManagementClient.SubscriptionId,
                                this.ResourceGroupName,
                                lbName,
                                probeHTTPName)
                        }
                    }
                },
                Probes = new List <Probe>()
                {
                    new Probe()
                    {
                        Name = probeName,
                        IntervalInSeconds = 5,
                        NumberOfProbes    = 2,
                        Port = Constants.DefaultTcpPort
                    },
                    new Probe()
                    {
                        Name = probeHTTPName,
                        IntervalInSeconds = 5,
                        NumberOfProbes    = 2,
                        Port = Constants.DefaultHttpPort
                    },
                },
                InboundNatPools = new List <InboundNatPool>()
                {
                    new InboundNatPool()
                    {
                        Name                    = inboundNatPoolName,
                        BackendPort             = Constants.DefaultBackendPort,
                        FrontendIPConfiguration = new Management.Internal.Network.Version2017_10_01.Models.SubResource()
                        {
                            Id = string.Format(
                                FrontendIdFormat,
                                NetworkManagementClient.SubscriptionId,
                                this.ResourceGroupName,
                                lbName,
                                frontendIpConfigurationName)
                        },
                        FrontendPortRangeStart = Constants.DefaultFrontendPortRangeStart,
                        FrontendPortRangeEnd   = Constants.DefaultFrontendPortRangeEnd,
                        Protocol = "tcp"
                    }
                }
            };

            NetworkManagementClient.LoadBalancers.BeginCreateOrUpdate(
                this.ResourceGroupName,
                lbName,
                newLoadBalancer);

            newLoadBalancer = NetworkManagementClient.LoadBalancers.Get(this.ResourceGroupName, lbName);

            return(new VirtualMachineScaleSetNetworkProfile()
            {
                NetworkInterfaceConfigurations = new List <VirtualMachineScaleSetNetworkConfiguration>()
                {
                    new VirtualMachineScaleSetNetworkConfiguration()
                    {
                        IpConfigurations = new List <VirtualMachineScaleSetIPConfiguration>()
                        {
                            new VirtualMachineScaleSetIPConfiguration()
                            {
                                Name = ipconfigName,
                                LoadBalancerBackendAddressPools = newLoadBalancer.BackendAddressPools.Select(
                                    b => new Azure.Commands.Common.Compute.Version_2018_04.Models.SubResource()
                                {
                                    Id = b.Id
                                }
                                    ).ToList(),

                                LoadBalancerInboundNatPools = newLoadBalancer.InboundNatPools.Select(
                                    p => new Azure.Commands.Common.Compute.Version_2018_04.Models.SubResource()
                                {
                                    Id = p.Id
                                }
                                    ).ToList(),
                                Subnet = new ApiEntityReference()
                                {
                                    Id = ipConfiguration.Subnet.Id
                                }
                            }
                        },
                        Name = nicName,
                        Primary = true
                    }
                }
            });
        }
Example #6
0
        private VirtualMachineScaleSetNetworkProfile CreateNetworkResource(VirtualMachineScaleSetNetworkConfiguration existingNetworkConfig)
        {
            var subsetName = string.Format("Subnet-{0}", this.NodeType);

            var ipConfiguration = existingNetworkConfig.IpConfigurations.FirstOrDefault();

            if (ipConfiguration == null)
            {
                throw new PSInvalidOperationException(ServiceFabricProperties.Resources.InvalidVmssConfiguration);
            }

            var          subNetId        = ipConfiguration.Subnet.Id;
            const string virtualNetworks = "Microsoft.Network/virtualNetworks/";
            var          virtualNetwork  = string.Empty;
            int          index           = -1;

            if ((index = subNetId.IndexOf(virtualNetworks, StringComparison.OrdinalIgnoreCase)) != -1)
            {
                var end = subNetId.IndexOf("/", index + virtualNetworks.Length);
                virtualNetwork = subNetId.Substring(index + virtualNetworks.Length, end - index - virtualNetworks.Length);
            }

            if (string.IsNullOrEmpty(virtualNetwork))
            {
                throw new InvalidOperationException();
            }

            var network = NetworkManagementClient.VirtualNetworks.Get(this.ResourceGroupName, virtualNetwork);

            var    start  = 1;
            Subnet subnet = null;
            var    retry  = 5;

            while (retry-- >= 0)
            {
                try
                {
                    subnet = NetworkManagementClient.Subnets.CreateOrUpdate(
                        this.ResourceGroupName,
                        virtualNetwork,
                        string.Format("{0}-{1}", subsetName, start),
                        new Subnet()
                    {
                        AddressPrefix = string.Format("10.0.{0}.0/24", start++)
                    });

                    network.Subnets.Add(subnet);
                    network = NetworkManagementClient.VirtualNetworks.CreateOrUpdate(
                        this.ResourceGroupName,
                        virtualNetwork,
                        network);

                    this.addressPrefix = subnet.AddressPrefix;
                    break;
                }
                catch (Rest.Azure.CloudException ex)
                {
                    if (ex.Body.Code == "NetcfgInvalidSubnet" ||
                        ex.Body.Code == "InUseSubnetCannotBeUpdated")
                    {
                        network.Subnets.Remove(subnet);
                        continue;
                    }

                    if (ex.Body.Code == "InvalidRequestFormat")
                    {
                        if (ex.Body.Details != null)
                        {
                            var details = ex.Body.Details.Where(d => d.Code == "DuplicateResourceName");
                            if (details.Any())
                            {
                                network.Subnets.Remove(subnet);
                                continue;
                            }
                        }
                    }

                    throw;
                }
            }

            var publicAddressName = string.Format("LBIP-{0}-{1}{2}", this.Name.ToLower(), this.NodeType.ToLower(), index);
            var dnsLable          = string.Format("{0}-{1}{2}", this.Name.ToLower(), this.NodeType.ToLower(), index);
            var lbName            = string.Format("LB-{0}-{1}{2}", this.Name.ToLower(), this.NodeType.ToLower(), index);

            var publicIp = NetworkManagementClient.PublicIPAddresses.CreateOrUpdate(
                this.ResourceGroupName,
                publicAddressName,
                new PublicIPAddress()
            {
                PublicIPAllocationMethod = "Dynamic",
                Location    = GetLocation(),
                DnsSettings = new PublicIPAddressDnsSettings(dnsLable)
            });

            var backendAdressPollName       = "LoadBalancerBEAddressPool";
            var frontendIpConfigurationName = "LoadBalancerIPConfig";
            var probeName           = "FabricGatewayProbe";
            var probeHTTPName       = "FabricHttpGatewayProbe";
            var inboundNatPoolsName = "LoadBalancerBEAddressNatPool";

            var newLoadBalancerId = string.Format(
                LoadBalancerIdFormat,
                this.NetworkManagementClient.SubscriptionId,
                this.ResourceGroupName,
                lbName);

            var newLoadBalancer = new LoadBalancer(newLoadBalancerId, lbName)
            {
                Location = GetLocation(),
                FrontendIPConfigurations = new List <FrontendIPConfiguration>()
                {
                    new FrontendIPConfiguration()
                    {
                        Name            = frontendIpConfigurationName,
                        PublicIPAddress = new PublicIPAddress()
                        {
                            Id = publicIp.Id
                        }
                    }
                },
                BackendAddressPools = new List <BackendAddressPool>()
                {
                    new BackendAddressPool()
                    {
                        Name = backendAdressPollName
                    }
                },
                LoadBalancingRules = new List <LoadBalancingRule>()
                {
                    new LoadBalancingRule()
                    {
                        Name = "LBRule",
                        BackendAddressPool = new Management.Network.Models.SubResource()
                        {
                            Id = string.Format(
                                BackendAddressIdFormat,
                                NetworkManagementClient.SubscriptionId,
                                this.ResourceGroupName,
                                lbName,
                                backendAdressPollName)
                        },
                        BackendPort             = Constants.DefaultTcpPort,
                        EnableFloatingIP        = false,
                        FrontendIPConfiguration = new Management.Network.Models.SubResource()
                        {
                            Id = string.Format(
                                FrontendIDFormat,
                                NetworkManagementClient.SubscriptionId,
                                this.ResourceGroupName,
                                lbName,
                                frontendIpConfigurationName)
                        },
                        FrontendPort         = Constants.DefaultTcpPort,
                        IdleTimeoutInMinutes = 5,
                        Protocol             = "tcp",
                        Probe = new Management.Network.Models.SubResource()
                        {
                            Id = string.Format(
                                ProbeIDFormat,
                                NetworkManagementClient.SubscriptionId,
                                this.ResourceGroupName,
                                lbName,
                                probeName)
                        }
                    },
                    new LoadBalancingRule()
                    {
                        Name = "LBHttpRule",
                        BackendAddressPool = new Management.Network.Models.SubResource()
                        {
                            Id = string.Format(
                                BackendAddressIdFormat,
                                NetworkManagementClient.SubscriptionId,
                                this.ResourceGroupName,
                                lbName,
                                backendAdressPollName)
                        },
                        BackendPort             = Constants.DefaultHttpPort,
                        EnableFloatingIP        = false,
                        FrontendIPConfiguration = new Management.Network.Models.SubResource()
                        {
                            Id = string.Format(
                                FrontendIDFormat,
                                NetworkManagementClient.SubscriptionId,
                                this.ResourceGroupName,
                                lbName,
                                frontendIpConfigurationName)
                        },
                        FrontendPort         = Constants.DefaultHttpPort,
                        IdleTimeoutInMinutes = 5,
                        Protocol             = "tcp",
                        Probe = new Management.Network.Models.SubResource()
                        {
                            Id = string.Format(
                                ProbeIDFormat,
                                NetworkManagementClient.SubscriptionId,
                                this.ResourceGroupName,
                                lbName,
                                probeHTTPName)
                        }
                    }
                },
                Probes = new List <Probe>()
                {
                    new Probe()
                    {
                        Name = probeName,
                        IntervalInSeconds = 5,
                        NumberOfProbes    = 2,
                        Port = Constants.DefaultTcpPort
                    },
                    new Probe()
                    {
                        Name = probeHTTPName,
                        IntervalInSeconds = 5,
                        NumberOfProbes    = 2,
                        Port = Constants.DefaultHttpPort
                    },
                },
                InboundNatPools = new List <InboundNatPool>()
                {
                    new InboundNatPool()
                    {
                        Name                    = inboundNatPoolsName,
                        BackendPort             = Constants.DefaultBackendPort,
                        FrontendIPConfiguration = new Management.Network.Models.SubResource()
                        {
                            Id = string.Format(
                                FrontendIDFormat,
                                NetworkManagementClient.SubscriptionId,
                                this.ResourceGroupName,
                                lbName,
                                frontendIpConfigurationName)
                        },
                        FrontendPortRangeStart = Constants.DefaultFrontendPortRangeStart,
                        FrontendPortRangeEnd   = Constants.DefaultFrontendPortRangeEnd,
                        Protocol = "tcp"
                    }
                }
            };

            NetworkManagementClient.LoadBalancers.BeginCreateOrUpdate(
                this.ResourceGroupName,
                lbName,
                newLoadBalancer);

            newLoadBalancer = NetworkManagementClient.LoadBalancers.Get(this.ResourceGroupName, lbName);

            return(new VirtualMachineScaleSetNetworkProfile()
            {
                NetworkInterfaceConfigurations = new List <VirtualMachineScaleSetNetworkConfiguration>()
                {
                    new VirtualMachineScaleSetNetworkConfiguration()
                    {
                        IpConfigurations = new List <VirtualMachineScaleSetIPConfiguration>()
                        {
                            new VirtualMachineScaleSetIPConfiguration()
                            {
                                Name = string.Format("Nic-{0}", start),
                                LoadBalancerBackendAddressPools = newLoadBalancer.BackendAddressPools.Select(
                                    b => new Management.Compute.Models.SubResource()
                                {
                                    Id = b.Id
                                }
                                    ).ToList(),

                                LoadBalancerInboundNatPools = newLoadBalancer.InboundNatPools.Select(
                                    p => new Management.Compute.Models.SubResource()
                                {
                                    Id = p.Id
                                }
                                    ).ToList(),
                                Subnet = new ApiEntityReference()
                                {
                                    Id = subnet.Id
                                }
                            }
                        },
                        Name = string.Format("NIC-{0}-{1}", this.NodeType, start),
                        Primary = true
                    }
                }
            });
        }
Example #7
0
    public async Async.Task <OneFuzzResultVoid> CreateVmss(
        string location,
        Guid name,
        string vmSku,
        long vmCount,
        string image,
        string networkId,
        bool?spotInstance,
        bool ephemeralOsDisks,
        IList <VirtualMachineScaleSetExtensionData>?extensions,
        string password,
        string sshPublicKey,
        IDictionary <string, string> tags)
    {
        var vmss = await GetVmss(name);

        if (vmss is not null)
        {
            return(OneFuzzResultVoid.Ok);
        }
        _log.Info($"creating VM name: {name}, vm_sku: {vmSku}, vm_count: {vmCount}, image: {image}, subnet: {networkId}, spot_instance: {spotInstance}");
        var getOsResult = await _imageOps.GetOs(location, image);

        if (!getOsResult.IsOk)
        {
            return(getOsResult.ErrorV);
        }

        var vmssData = new VirtualMachineScaleSetData(location)
        {
            DoNotRunExtensionsOnOverprovisionedVms = false,
            Sku = new ComputeSku()
            {
                Name = vmSku
            },
            Overprovision        = false,
            SinglePlacementGroup = false,
            UpgradePolicy        = new UpgradePolicy()
            {
                Mode = UpgradeMode.Manual
            },
            Identity = new ManagedServiceIdentity(managedServiceIdentityType: ManagedServiceIdentityType.UserAssigned),
        };

        vmssData.Identity.UserAssignedIdentities.Add(_creds.GetScalesetIdentityResourcePath(), new UserAssignedIdentity());
        vmssData.VirtualMachineProfile = new VirtualMachineScaleSetVmProfile()
        {
            Priority = VirtualMachinePriorityTypes.Regular
        };
        var imageRef = new ImageReference();

        if (image.StartsWith('/'))
        {
            imageRef.Id = image;
        }
        else
        {
            var info = IImageOperations.GetImageInfo(image);
            imageRef.Publisher = info.Publisher;
            imageRef.Offer     = info.Offer;
            imageRef.Sku       = info.Sku;
            imageRef.Version   = info.Version;
        }
        vmssData.VirtualMachineProfile.StorageProfile = new VirtualMachineScaleSetStorageProfile()
        {
            ImageReference = imageRef
        };
        vmssData.VirtualMachineProfile.OSProfile = new VirtualMachineScaleSetOSProfile()
        {
            ComputerNamePrefix = "node", AdminUsername = "******"
        };

        var networkConfiguration = new VirtualMachineScaleSetNetworkConfiguration("onefuzz-nic")
        {
            Primary = true
        };
        var ipConfig = new VirtualMachineScaleSetIPConfiguration("onefuzz-ip-config");

        ipConfig.SubnetId = new ResourceIdentifier(networkId);
        networkConfiguration.IPConfigurations.Add(ipConfig);

        vmssData.VirtualMachineProfile.NetworkProfile = new VirtualMachineScaleSetNetworkProfile();
        vmssData.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations.Add(networkConfiguration);

        if (extensions is not null)
        {
            vmssData.VirtualMachineProfile.ExtensionProfile = new VirtualMachineScaleSetExtensionProfile();
            foreach (var e in extensions)
            {
                vmssData.VirtualMachineProfile.ExtensionProfile.Extensions.Add(e);
            }
        }

        switch (getOsResult.OkV)
        {
        case Os.Windows:
            vmssData.VirtualMachineProfile.OSProfile.AdminPassword = password;
            break;

        case Os.Linux:
            vmssData.VirtualMachineProfile.OSProfile.LinuxConfiguration = new LinuxConfiguration();
            vmssData.VirtualMachineProfile.OSProfile.LinuxConfiguration.DisablePasswordAuthentication = true;
            var i = new SshPublicKeyInfo()
            {
                KeyData = sshPublicKey, Path = "/home/onefuzz/.ssh/authorized_keys"
            };
            vmssData.VirtualMachineProfile.OSProfile.LinuxConfiguration.SshPublicKeys.Add(i);
            break;

        default:
            return(OneFuzzResultVoid.Error(ErrorCode.INVALID_CONFIGURATION, $"unhandled OS: {getOsResult.OkV} in image: {image}"));
        }

        if (ephemeralOsDisks)
        {
            vmssData.VirtualMachineProfile.StorageProfile.OSDisk = new VirtualMachineScaleSetOSDisk(DiskCreateOptionTypes.FromImage);
            vmssData.VirtualMachineProfile.StorageProfile.OSDisk.DiffDiskSettings        = new DiffDiskSettings();
            vmssData.VirtualMachineProfile.StorageProfile.OSDisk.DiffDiskSettings.Option = DiffDiskOptions.Local;
            vmssData.VirtualMachineProfile.StorageProfile.OSDisk.Caching = CachingTypes.ReadOnly;
        }

        if (spotInstance.HasValue && spotInstance.Value)
        {
            // Setting max price to -1 means it won't be evicted because of
            // price.
            //
            // https://docs.microsoft.com/en-us/azure/
            //   virtual-machine-scale-sets/use-spot#resource-manager-templates
            vmssData.VirtualMachineProfile.EvictionPolicy  = VirtualMachineEvictionPolicyTypes.Deallocate;
            vmssData.VirtualMachineProfile.Priority        = VirtualMachinePriorityTypes.Spot;
            vmssData.VirtualMachineProfile.BillingMaxPrice = 1.0;
        }

        foreach (var tag in tags)
        {
            vmssData.Tags.Add(tag);
        }

        if (_serviceConfig.OneFuzzOwner is not null)
        {
            vmssData.Tags.Add("OWNER", _serviceConfig.OneFuzzOwner);
        }

        try {
            var rg           = _creds.GetResourceGroupResource();
            var createUpdate = await rg.GetVirtualMachineScaleSets().CreateOrUpdateAsync(WaitUntil.Started, name.ToString(), vmssData);

            if (createUpdate.GetRawResponse().IsError)
            {
                var msg = $"Failed to create new scaleset due to {createUpdate.GetRawResponse().ReasonPhrase}";
                _log.Error(msg);
                return(OneFuzzResultVoid.Error(ErrorCode.VM_CREATE_FAILED, new[] { msg }));
            }
            else
            {
                return(OneFuzzResultVoid.Ok);
            }
        } catch (Exception ex) {
            _log.Exception(ex);
            return(OneFuzzResultVoid.Error(ErrorCode.VM_CREATE_FAILED, new[] { ex.Message }));
        }
    }