Example #1
0
            public async Task <ResourceConfig <VirtualMachine> > CreateConfigAsync()
            {
                if (_cmdlet.DiskFile == null)
                {
                    ImageAndOsType = await _client.UpdateImageAndOsTypeAsync(
                        ImageAndOsType, _cmdlet.ResourceGroupName, _cmdlet.Image, Location);
                }

                _cmdlet.DomainNameLabel = await PublicIPAddressStrategy.UpdateDomainNameLabelAsync(
                    domainNameLabel : _cmdlet.DomainNameLabel,
                    name : _cmdlet.Name,
                    location : Location,
                    client : _client);

                var resourceGroup  = ResourceGroupStrategy.CreateResourceGroupConfig(_cmdlet.ResourceGroupName);
                var virtualNetwork = resourceGroup.CreateVirtualNetworkConfig(
                    name: _cmdlet.VirtualNetworkName, addressPrefix: _cmdlet.AddressPrefix);
                var subnet          = virtualNetwork.CreateSubnet(_cmdlet.SubnetName, _cmdlet.SubnetAddressPrefix);
                var publicIpAddress = resourceGroup.CreatePublicIPAddressConfig(
                    name: _cmdlet.PublicIpAddressName,
                    domainNameLabel: _cmdlet.DomainNameLabel,
                    allocationMethod: _cmdlet.AllocationMethod,
                    sku: _cmdlet.Zone == null ? PublicIPAddressStrategy.Sku.Basic : PublicIPAddressStrategy.Sku.Standard,
                    zones: _cmdlet.Zone);

                _cmdlet.OpenPorts = ImageAndOsType.UpdatePorts(_cmdlet.OpenPorts);

                var networkSecurityGroup = resourceGroup.CreateNetworkSecurityGroupConfig(
                    name: _cmdlet.SecurityGroupName,
                    openPorts: _cmdlet.OpenPorts);

                bool enableAcceleratedNetwork = Utils.DoesConfigSupportAcceleratedNetwork(_client,
                                                                                          ImageAndOsType, _cmdlet.Size, Location, DefaultLocation);

                var networkInterface = resourceGroup.CreateNetworkInterfaceConfig(
                    _cmdlet.Name, subnet, publicIpAddress, networkSecurityGroup, enableAcceleratedNetwork);

                var ppgSubResourceFunc = resourceGroup.CreateProximityPlacementGroupSubResourceFunc(_cmdlet.ProximityPlacementGroup);

                var availabilitySet = _cmdlet.AvailabilitySetName == null
                    ? null
                    : resourceGroup.CreateAvailabilitySetConfig(
                    name: _cmdlet.AvailabilitySetName,
                    proximityPlacementGroup: ppgSubResourceFunc);

                if (_cmdlet.DiskFile == null)
                {
                    return(resourceGroup.CreateVirtualMachineConfig(
                               name: _cmdlet.Name,
                               networkInterface: networkInterface,
                               imageAndOsType: ImageAndOsType,
                               adminUsername: _cmdlet.Credential.UserName,
                               adminPassword:
                               new NetworkCredential(string.Empty, _cmdlet.Credential.Password).Password,
                               size: _cmdlet.Size,
                               availabilitySet: availabilitySet,
                               dataDisks: _cmdlet.DataDiskSizeInGb,
                               zones: _cmdlet.Zone,
                               ultraSSDEnabled: _cmdlet.EnableUltraSSD.IsPresent,
                               identity: _cmdlet.GetVMIdentityFromArgs(),
                               proximityPlacementGroup: ppgSubResourceFunc,
                               hostId: _cmdlet.HostId,
                               priority: _cmdlet.Priority,
                               evictionPolicy: _cmdlet.EvictionPolicy,
                               maxPrice: _cmdlet.IsParameterBound(c => c.MaxPrice) ? _cmdlet.MaxPrice : (double?)null
                               ));
                }
                else
                {
                    var disk = resourceGroup.CreateManagedDiskConfig(
                        name: _cmdlet.Name,
                        sourceUri: DestinationUri.Uri.ToString());

                    return(resourceGroup.CreateVirtualMachineConfig(
                               name: _cmdlet.Name,
                               networkInterface: networkInterface,
                               osType: ImageAndOsType.OsType,
                               disk: disk,
                               size: _cmdlet.Size,
                               availabilitySet: availabilitySet,
                               dataDisks: _cmdlet.DataDiskSizeInGb,
                               zones: _cmdlet.Zone,
                               ultraSSDEnabled: _cmdlet.EnableUltraSSD.IsPresent,
                               identity: _cmdlet.GetVMIdentityFromArgs(),
                               proximityPlacementGroup: ppgSubResourceFunc,
                               hostId: _cmdlet.HostId,
                               priority: _cmdlet.Priority,
                               evictionPolicy: _cmdlet.EvictionPolicy,
                               maxPrice: _cmdlet.IsParameterBound(c => c.MaxPrice) ? _cmdlet.MaxPrice : (double?)null
                               ));
                }
            }
        async Task StrategyExecuteCmdletAsync(IAsyncCmdlet asyncCmdlet)
        {
            ResourceGroupName   = ResourceGroupName ?? Name;
            VirtualNetworkName  = VirtualNetworkName ?? Name;
            SubnetName          = SubnetName ?? Name;
            PublicIpAddressName = PublicIpAddressName ?? Name;
            SecurityGroupName   = SecurityGroupName ?? Name;

            var imageAndOsType = new ImageAndOsType(OperatingSystemTypes.Windows, null);

            var resourceGroup  = ResourceGroupStrategy.CreateResourceGroupConfig(ResourceGroupName);
            var virtualNetwork = resourceGroup.CreateVirtualNetworkConfig(
                name: VirtualNetworkName, addressPrefix: AddressPrefix);
            var subnet          = virtualNetwork.CreateSubnet(SubnetName, SubnetAddressPrefix);
            var publicIpAddress = resourceGroup.CreatePublicIPAddressConfig(
                name: PublicIpAddressName,
                getDomainNameLabel: () => DomainNameLabel,
                allocationMethod: AllocationMethod);
            var networkSecurityGroup = resourceGroup.CreateNetworkSecurityGroupConfig(
                name: SecurityGroupName,
                openPorts: OpenPorts,
                getOsType: () => imageAndOsType.OsType);
            var networkInterface = resourceGroup.CreateNetworkInterfaceConfig(
                Name, subnet, publicIpAddress, networkSecurityGroup);

            var availabilitySet = AvailabilitySetName == null
                ? null
                : resourceGroup.CreateAvailabilitySetConfig(name: AvailabilitySetName);

            ResourceConfig <VirtualMachine> virtualMachine = null;

            if (DiskFile == null)
            {
                virtualMachine = resourceGroup.CreateVirtualMachineConfig(
                    name: Name,
                    networkInterface: networkInterface,
                    getImageAndOsType: () => imageAndOsType,
                    adminUsername: Credential.UserName,
                    adminPassword: new NetworkCredential(string.Empty, Credential.Password).Password,
                    size: Size,
                    availabilitySet: availabilitySet);
            }
            else
            {
                var resourceClient =
                    AzureSession.Instance.ClientFactory.CreateArmClient <ResourceManagementClient>(DefaultProfile.DefaultContext,
                                                                                                   AzureEnvironment.Endpoint.ResourceManager);
                if (!resourceClient.ResourceGroups.CheckExistence(ResourceGroupName))
                {
                    var st0 = resourceClient.ResourceGroups.CreateOrUpdate(ResourceGroupName, new ResourceGroup
                    {
                        Location = Location,
                        Name     = ResourceGroupName
                    });
                }
                imageAndOsType = new ImageAndOsType(
                    Linux ? OperatingSystemTypes.Linux : OperatingSystemTypes.Windows,
                    null);
                var storageClient =
                    AzureSession.Instance.ClientFactory.CreateArmClient <StorageManagementClient>(DefaultProfile.DefaultContext,
                                                                                                  AzureEnvironment.Endpoint.ResourceManager);
                var st1 = storageClient.StorageAccounts.Create(
                    ResourceGroupName,
                    Name,
                    new StorageAccountCreateParameters
                {
#if !NETSTANDARD
                    AccountType = AccountType.PremiumLRS,
#else
                    Sku = new Microsoft.Azure.Management.Storage.Models.Sku
                    {
                        Name = SkuName.PremiumLRS
                    },
#endif
                    Location = Location
                });
                var filePath = new FileInfo(SessionState.Path.GetUnresolvedProviderPathFromPSPath(DiskFile));
                using (var vds = new VirtualDiskStream(filePath.FullName))
                {
                    if (vds.DiskType == DiskType.Fixed)
                    {
                        long divisor = Convert.ToInt64(Math.Pow(2, 9));
                        long rem     = 0;
                        Math.DivRem(filePath.Length, divisor, out rem);
                        if (rem != 0)
                        {
                            throw new ArgumentOutOfRangeException(
                                      "filePath",
                                      string.Format("Given vhd file '{0}' is a corrupted fixed vhd", filePath));
                        }
                    }
                }
                var     storageAccount = storageClient.StorageAccounts.GetProperties(ResourceGroupName, Name);
                BlobUri destinationUri = null;
                BlobUri.TryParseUri(
                    new Uri(string.Format(
                                "{0}{1}/{2}{3}",
                                storageAccount.PrimaryEndpoints.Blob,
                                ResourceGroupName.ToLower(),
                                Name.ToLower(),
                                ".vhd")),
                    out destinationUri);
                if (destinationUri == null || destinationUri.Uri == null)
                {
                    throw new ArgumentNullException("destinationUri");
                }
                var storageCredentialsFactory = new StorageCredentialsFactory(
                    this.ResourceGroupName, storageClient, DefaultContext.Subscription);
                var parameters = new UploadParameters(destinationUri, null, filePath, true, 2)
                {
                    Cmdlet            = this,
                    BlobObjectFactory = new CloudPageBlobObjectFactory(storageCredentialsFactory, TimeSpan.FromMinutes(1))
                };
                if (!string.Equals(
                        Environment.GetEnvironmentVariable("AZURE_TEST_MODE"), "Playback", StringComparison.OrdinalIgnoreCase))
                {
                    var st2 = VhdUploaderModel.Upload(parameters);
                }
                var disk = resourceGroup.CreateManagedDiskConfig(
                    name: Name,
                    sourceUri: destinationUri.Uri.ToString()
                    );
                virtualMachine = resourceGroup.CreateVirtualMachineConfig(
                    name: Name,
                    networkInterface: networkInterface,
                    osType: imageAndOsType.OsType,
                    disk: disk,
                    size: Size,
                    availabilitySet: availabilitySet);
            }

            var client = new Client(DefaultProfile.DefaultContext);

            // get current Azure state
            var current = await virtualMachine.GetStateAsync(client, new CancellationToken());

            Location = current.UpdateLocation(Location, virtualMachine);

            // generate a domain name label if it's not specified.
            DomainNameLabel = await PublicIPAddressStrategy.UpdateDomainNameLabelAsync(
                domainNameLabel : DomainNameLabel,
                name : Name,
                location : Location,
                client : client);

            var fqdn = PublicIPAddressStrategy.Fqdn(DomainNameLabel, Location);

            if (DiskFile == null)
            {
                imageAndOsType = await client.UpdateImageAndOsTypeAsync(ImageName, Location);
            }

            // create target state
            var engine = new SdkEngine(client.SubscriptionId);
            var target = virtualMachine.GetTargetState(current, engine, Location);

            if (target.Get(availabilitySet) != null)
            {
                throw new InvalidOperationException("Availability set doesn't exist.");
            }

            // apply target state
            var newState = await virtualMachine
                           .UpdateStateAsync(
                client,
                target,
                new CancellationToken(),
                new ShouldProcess(asyncCmdlet),
                asyncCmdlet.ReportTaskProgress);

            var result = newState.Get(virtualMachine);

            if (result == null)
            {
                result = current.Get(virtualMachine);
            }
            if (result != null)
            {
                var psResult = ComputeAutoMapperProfile.Mapper.Map <PSVirtualMachine>(result);
                psResult.FullyQualifiedDomainName = fqdn;
                var connectionString = imageAndOsType.GetConnectionString(
                    fqdn,
                    Credential.UserName);
                asyncCmdlet.WriteVerbose(
                    Resources.VirtualMachineUseConnectionString,
                    connectionString);
                asyncCmdlet.WriteObject(psResult);
            }
        }
            public async Task <ResourceConfig <VirtualMachineScaleSet> > CreateConfigAsync()
            {
                ImageAndOsType = await _client.UpdateImageAndOsTypeAsync(
                    ImageAndOsType, _cmdlet.ResourceGroupName, _cmdlet.ImageName, Location);

                // generate a domain name label if it's not specified.
                _cmdlet.DomainNameLabel = await PublicIPAddressStrategy.UpdateDomainNameLabelAsync(
                    domainNameLabel : _cmdlet.DomainNameLabel,
                    name : _cmdlet.VMScaleSetName,
                    location : Location,
                    client : _client);

                var resourceGroup = ResourceGroupStrategy.CreateResourceGroupConfig(_cmdlet.ResourceGroupName);

                var noZones = _cmdlet.Zone == null || _cmdlet.Zone.Count == 0;

                var publicIpAddress = resourceGroup.CreatePublicIPAddressConfig(
                    name: _cmdlet.PublicIpAddressName,
                    domainNameLabel: _cmdlet.DomainNameLabel,
                    allocationMethod: _cmdlet.AllocationMethod,
                    //sku.Basic is not compatible with multiple placement groups
                    sku: (noZones && _cmdlet.SinglePlacementGroup.IsPresent)
                        ? PublicIPAddressStrategy.Sku.Basic
                        : PublicIPAddressStrategy.Sku.Standard,
                    zones: null);

                var virtualNetwork = resourceGroup.CreateVirtualNetworkConfig(
                    name: _cmdlet.VirtualNetworkName,
                    addressPrefix: _cmdlet.VnetAddressPrefix);

                var subnet = virtualNetwork.CreateSubnet(
                    _cmdlet.SubnetName, _cmdlet.SubnetAddressPrefix);

                var loadBalancer = resourceGroup.CreateLoadBalancerConfig(
                    name: _cmdlet.LoadBalancerName,
                    //sku.Basic is not compatible with multiple placement groups
                    sku: (noZones && _cmdlet.SinglePlacementGroup.IsPresent)
                        ? LoadBalancerStrategy.Sku.Basic
                        : LoadBalancerStrategy.Sku.Standard);

                var frontendIpConfiguration = loadBalancer.CreateFrontendIPConfiguration(
                    name: _cmdlet.FrontendPoolName,
                    publicIpAddress: publicIpAddress);

                var backendAddressPool = loadBalancer.CreateBackendAddressPool(
                    name: _cmdlet.BackendPoolName);

                if (_cmdlet.BackendPort != null)
                {
                    var loadBalancingRuleName = _cmdlet.LoadBalancerName;
                    foreach (var backendPort in _cmdlet.BackendPort)
                    {
                        loadBalancer.CreateLoadBalancingRule(
                            name: loadBalancingRuleName + backendPort.ToString(),
                            fronendIpConfiguration: frontendIpConfiguration,
                            backendAddressPool: backendAddressPool,
                            frontendPort: backendPort,
                            backendPort: backendPort);
                    }
                }

                _cmdlet.NatBackendPort = ImageAndOsType.UpdatePorts(_cmdlet.NatBackendPort);

                var inboundNatPoolName = _cmdlet.VMScaleSetName;
                var PortRangeSize      = _cmdlet.InstanceCount * 2;

                var ports = _cmdlet
                            .NatBackendPort
                            ?.Select((port, i) => Tuple.Create(
                                         port,
                                         FirstPortRangeStart + i * 2000))
                            .ToList();

                var inboundNatPools = ports
                                      ?.Select(p => loadBalancer.CreateInboundNatPool(
                                                   name: inboundNatPoolName + p.Item1.ToString(),
                                                   frontendIpConfiguration: frontendIpConfiguration,
                                                   frontendPortRangeStart: p.Item2,
                                                   frontendPortRangeEnd: p.Item2 + PortRangeSize,
                                                   backendPort: p.Item1))
                                      .ToList();

                var networkSecurityGroup = noZones
                    ? null
                    : resourceGroup.CreateNetworkSecurityGroupConfig(
                    _cmdlet.VMScaleSetName,
                    _cmdlet.NatBackendPort.Concat(_cmdlet.BackendPort).ToList());

                return(resourceGroup.CreateVirtualMachineScaleSetConfig(
                           name: _cmdlet.VMScaleSetName,
                           subnet: subnet,
                           backendAdressPool: backendAddressPool,
                           inboundNatPools: inboundNatPools,
                           networkSecurityGroup: networkSecurityGroup,
                           imageAndOsType: ImageAndOsType,
                           adminUsername: _cmdlet.Credential.UserName,
                           adminPassword: new NetworkCredential(string.Empty, _cmdlet.Credential.Password).Password,
                           vmSize: _cmdlet.VmSize,
                           instanceCount: _cmdlet.InstanceCount,
                           upgradeMode: _cmdlet.MyInvocation.BoundParameters.ContainsKey(nameof(UpgradePolicyMode))
                        ? _cmdlet.UpgradePolicyMode
                        : (UpgradeMode?)null,
                           dataDisks: _cmdlet.DataDiskSizeInGb,
                           zones: _cmdlet.Zone,
                           identity: _cmdlet.GetVmssIdentityFromArgs(),
                           singlePlacementGroup: _cmdlet.SinglePlacementGroup.IsPresent));
            }
            public async Task <ResourceConfig <VirtualMachine> > CreateConfigAsync()
            {
                if (_cmdlet.DiskFile == null)
                {
                    ImageAndOsType = await _client.UpdateImageAndOsTypeAsync(
                        ImageAndOsType, _cmdlet.ResourceGroupName, _cmdlet.ImageName, Location);
                }

                _cmdlet.DomainNameLabel = await PublicIPAddressStrategy.UpdateDomainNameLabelAsync(
                    domainNameLabel : _cmdlet.DomainNameLabel,
                    name : _cmdlet.Name,
                    location : Location,
                    client : _client);

                var resourceGroup  = ResourceGroupStrategy.CreateResourceGroupConfig(_cmdlet.ResourceGroupName);
                var virtualNetwork = resourceGroup.CreateVirtualNetworkConfig(
                    name: _cmdlet.VirtualNetworkName, addressPrefix: _cmdlet.AddressPrefix);
                var subnet          = virtualNetwork.CreateSubnet(_cmdlet.SubnetName, _cmdlet.SubnetAddressPrefix);
                var publicIpAddress = resourceGroup.CreatePublicIPAddressConfig(
                    name: _cmdlet.PublicIpAddressName,
                    domainNameLabel: _cmdlet.DomainNameLabel,
                    allocationMethod: _cmdlet.AllocationMethod,
                    sku: PublicIPAddressStrategy.Sku.Basic,
                    zones: _cmdlet.Zone);

                _cmdlet.OpenPorts = ImageAndOsType.UpdatePorts(_cmdlet.OpenPorts);

                var networkSecurityGroup = resourceGroup.CreateNetworkSecurityGroupConfig(
                    name: _cmdlet.SecurityGroupName,
                    openPorts: _cmdlet.OpenPorts);

                var networkInterface = resourceGroup.CreateNetworkInterfaceConfig(
                    _cmdlet.Name, subnet, publicIpAddress, networkSecurityGroup);

                var availabilitySet = _cmdlet.AvailabilitySetName == null
                    ? null
                    : resourceGroup.CreateAvailabilitySetConfig(name: _cmdlet.AvailabilitySetName);

                if (_cmdlet.DiskFile == null)
                {
                    return(resourceGroup.CreateVirtualMachineConfig(
                               name: _cmdlet.Name,
                               networkInterface: networkInterface,
                               imageAndOsType: ImageAndOsType,
                               adminUsername: _cmdlet.Credential.UserName,
                               adminPassword:
                               new NetworkCredential(string.Empty, _cmdlet.Credential.Password).Password,
                               size: _cmdlet.Size,
                               availabilitySet: availabilitySet,
                               dataDisks: _cmdlet.DataDiskSizeInGb,
                               zones: _cmdlet.Zone));
                }
                else
                {
                    var disk = resourceGroup.CreateManagedDiskConfig(
                        name: _cmdlet.Name,
                        sourceUri: DestinationUri.Uri.ToString());

                    return(resourceGroup.CreateVirtualMachineConfig(
                               name: _cmdlet.Name,
                               networkInterface: networkInterface,
                               osType: ImageAndOsType.OsType,
                               disk: disk,
                               size: _cmdlet.Size,
                               availabilitySet: availabilitySet,
                               dataDisks: _cmdlet.DataDiskSizeInGb,
                               zones: _cmdlet.Zone));
                }
            }
Example #5
0
        async Task SimpleParameterSetExecuteCmdlet(IAsyncCmdlet asyncCmdlet)
        {
            ResourceGroupName   = ResourceGroupName ?? VMScaleSetName;
            VirtualNetworkName  = VirtualNetworkName ?? VMScaleSetName;
            SubnetName          = SubnetName ?? VMScaleSetName;
            PublicIpAddressName = PublicIpAddressName ?? VMScaleSetName;
            SecurityGroupName   = SecurityGroupName ?? VMScaleSetName;
            LoadBalancerName    = LoadBalancerName ?? VMScaleSetName;
            FrontendPoolName    = FrontendPoolName ?? VMScaleSetName;
            BackendPoolName     = BackendPoolName ?? VMScaleSetName;

            var imageAndOsType = new ImageAndOsType(OperatingSystemTypes.Windows, null);

            var resourceGroup = ResourceGroupStrategy.CreateResourceGroupConfig(ResourceGroupName);

            var publicIpAddress = resourceGroup.CreatePublicIPAddressConfig(
                name: PublicIpAddressName,
                getDomainNameLabel: () => DomainNameLabel,
                allocationMethod: AllocationMethod);

            var virtualNetwork = resourceGroup.CreateVirtualNetworkConfig(
                name: VirtualNetworkName, addressPrefix: VnetAddressPrefix);

            var subnet = virtualNetwork.CreateSubnet(SubnetName, SubnetAddressPrefix);

            var loadBalancer = resourceGroup.CreateLoadBalancerConfig(
                name: LoadBalancerName,
                froontendPoolName: FrontendPoolName,
                backendPoolName: BackendPoolName,
                zones: Zone,
                publicIPAddress: publicIpAddress,
                subnet: subnet);

            var frontendIpConfiguration = loadBalancer.CreateFrontendIPConfiguration(
                name: FrontendPoolName,
                zones: Zone,
                publicIPAddress: publicIpAddress,
                subnet: subnet);

            var backendAddressPool = loadBalancer.CreateBackendAddressPool(
                name: BackendPoolName);

            var virtualMachineScaleSet = resourceGroup.CreateVirtualMachineScaleSetConfig(
                name: VMScaleSetName,
                subnet: subnet,
                frontendIpConfigurations: new[] { frontendIpConfiguration },
                backendAdressPool: backendAddressPool,
                getImageAndOsType: () => imageAndOsType,
                adminUsername: Credential.UserName,
                adminPassword: new NetworkCredential(string.Empty, Credential.Password).Password,
                vmSize: VmSize,
                instanceCount: InstanceCount,
                upgradeMode: MyInvocation.BoundParameters.ContainsKey("UpgradePolicyMode")
                    ? UpgradePolicyMode
                    : (UpgradeMode?)null);

            var client = new Client(DefaultProfile.DefaultContext);

            // get current Azure state
            var current = await virtualMachineScaleSet.GetStateAsync(client, new CancellationToken());

            Location = current.UpdateLocation(Location, virtualMachineScaleSet);

            imageAndOsType = await client.UpdateImageAndOsTypeAsync(ImageName, Location);

            // generate a domain name label if it's not specified.
            DomainNameLabel = await PublicIPAddressStrategy.UpdateDomainNameLabelAsync(
                domainNameLabel : DomainNameLabel,
                name : VMScaleSetName,
                location : Location,
                client : client);

            var fqdn = PublicIPAddressStrategy.Fqdn(DomainNameLabel, Location);

            var target = virtualMachineScaleSet.GetTargetState(current, client.SubscriptionId, Location);

            var newState = await virtualMachineScaleSet
                           .UpdateStateAsync(
                client,
                target,
                new CancellationToken(),
                new ShouldProcess(asyncCmdlet),
                asyncCmdlet.ReportTaskProgress);

            var result = newState.Get(virtualMachineScaleSet);

            if (result == null)
            {
                result = current.Get(virtualMachineScaleSet);
            }

            if (result != null)
            {
                var psObject = new PSVirtualMachineScaleSet();
                ComputeAutomationAutoMapperProfile.Mapper.Map(result, psObject);
                psObject.FullyQualifiedDomainName = fqdn;
                asyncCmdlet.WriteObject(psObject);
            }
        }
Example #6
0
        async Task SimpleParameterSetExecuteCmdlet(IAsyncCmdlet asyncCmdlet)
        {
            ResourceGroupName   = ResourceGroupName ?? VMScaleSetName;
            VirtualNetworkName  = VirtualNetworkName ?? VMScaleSetName;
            SubnetName          = SubnetName ?? VMScaleSetName;
            PublicIpAddressName = PublicIpAddressName ?? VMScaleSetName;
            SecurityGroupName   = SecurityGroupName ?? VMScaleSetName;
            LoadBalancerName    = LoadBalancerName ?? VMScaleSetName;
            FrontendPoolName    = FrontendPoolName ?? VMScaleSetName;
            BackendPoolName     = BackendPoolName ?? VMScaleSetName;

            var imageAndOsType = new ImageAndOsType(OperatingSystemTypes.Windows, null);

            var resourceGroup = ResourceGroupStrategy.CreateResourceGroupConfig(ResourceGroupName);

            var publicIpAddress = resourceGroup.CreatePublicIPAddressConfig(
                name: PublicIpAddressName,
                getDomainNameLabel: () => DomainNameLabel,
                allocationMethod: AllocationMethod);

            var virtualNetwork = resourceGroup.CreateVirtualNetworkConfig(
                name: VirtualNetworkName, addressPrefix: VnetAddressPrefix);

            var subnet = virtualNetwork.CreateSubnet(SubnetName, SubnetAddressPrefix);

            var loadBalancer = resourceGroup.CreateLoadBalancerConfig(
                name: LoadBalancerName);

            var frontendIpConfiguration = loadBalancer.CreateFrontendIPConfiguration(
                name: FrontendPoolName,
                zones: Zone,
                publicIpAddress: publicIpAddress);

            var backendAddressPool = loadBalancer.CreateBackendAddressPool(
                name: BackendPoolName);

            if (BackendPort != null)
            {
                var LoadBalancingRuleName = LoadBalancerName;
                foreach (var backendPort in BackendPort)
                {
                    loadBalancer.CreateLoadBalancingRule(
                        name: LoadBalancingRuleName + backendPort.ToString(),
                        fronendIpConfiguration: frontendIpConfiguration,
                        backendAddressPool: backendAddressPool,
                        frontendPort: backendPort,
                        backendPort: backendPort);
                }
            }

            var inboundNatPools = new List <NestedResourceConfig <InboundNatPool, LoadBalancer> >();

            var virtualMachineScaleSet = resourceGroup.CreateVirtualMachineScaleSetConfig(
                name: VMScaleSetName,
                subnet: subnet,
                frontendIpConfigurations: new[] { frontendIpConfiguration },
                backendAdressPool: backendAddressPool,
                inboundNatPools: inboundNatPools,
                getImageAndOsType: () => imageAndOsType,
                adminUsername: Credential.UserName,
                adminPassword: new NetworkCredential(string.Empty, Credential.Password).Password,
                vmSize: VmSize,
                instanceCount: InstanceCount,
                upgradeMode: MyInvocation.BoundParameters.ContainsKey(nameof(UpgradePolicyMode))
                    ? UpgradePolicyMode
                    : (UpgradeMode?)null);

            var client = new Client(DefaultProfile.DefaultContext);

            // get current Azure state
            var current = await virtualMachineScaleSet.GetStateAsync(client, new CancellationToken());

            Location = current.UpdateLocation(Location, virtualMachineScaleSet);

            imageAndOsType = await client.UpdateImageAndOsTypeAsync(ImageName, Location);

            NatBackendPort = imageAndOsType.OsType.UpdatePorts(NatBackendPort);

            var       inboundNatPoolName  = VMScaleSetName;
            const int FirstPortRangeStart = 50000;
            var       portRangeStart      = FirstPortRangeStart;
            var       PortRangeSize       = InstanceCount * 2;

            foreach (var natBackendPort in NatBackendPort)
            {
                inboundNatPools.Add(
                    loadBalancer.CreateInboundNatPool(
                        name: inboundNatPoolName + natBackendPort.ToString(),
                        frontendIpConfiguration: frontendIpConfiguration,
                        frontendPortRangeStart: portRangeStart,
                        frontendPortRangeEnd: portRangeStart + PortRangeSize,
                        backendPort: natBackendPort));
                portRangeStart += 2000;
            }

            // generate a domain name label if it's not specified.
            DomainNameLabel = await PublicIPAddressStrategy.UpdateDomainNameLabelAsync(
                domainNameLabel : DomainNameLabel,
                name : VMScaleSetName,
                location : Location,
                client : client);

            var fqdn = PublicIPAddressStrategy.Fqdn(DomainNameLabel, Location);

            var engine = new SdkEngine(client.SubscriptionId);
            var target = virtualMachineScaleSet.GetTargetState(current, engine, Location);

            var newState = await virtualMachineScaleSet
                           .UpdateStateAsync(
                client,
                target,
                new CancellationToken(),
                new ShouldProcess(asyncCmdlet),
                asyncCmdlet.ReportTaskProgress);

            var result = newState.Get(virtualMachineScaleSet);

            if (result == null)
            {
                result = current.Get(virtualMachineScaleSet);
            }

            if (result != null)
            {
                var psObject = new PSVirtualMachineScaleSet();
                ComputeAutomationAutoMapperProfile.Mapper.Map(result, psObject);
                psObject.FullyQualifiedDomainName = fqdn;

                var port             = "<port>";
                var connectionString = imageAndOsType.GetConnectionString(
                    fqdn,
                    Credential.UserName,
                    port);
                var range =
                    FirstPortRangeStart.ToString() +
                    ".." +
                    (FirstPortRangeStart + PortRangeSize).ToString();

                asyncCmdlet.WriteVerbose(
                    Resources.VmssUseConnectionString,
                    connectionString);
                asyncCmdlet.WriteVerbose(
                    Resources.VmssPortRange,
                    port,
                    range);
                asyncCmdlet.WriteObject(psObject);
            }
        }
Example #7
0
            private async Task <ResourceConfig <VirtualMachineScaleSet> > SimpleParameterSetOrchestrationModeFlexible()
            {
                //check omode params and throw error otherwise
                checkFlexibleOrchestrationModeParams();
                int             platformFaultDomainCountFlexibleDefault = 1;
                SwitchParameter singlePlacementGroupFlexibleDefault     = false;

                ImageAndOsType = await _client.UpdateImageAndOsTypeAsync(
                    ImageAndOsType, _cmdlet.ResourceGroupName, _cmdlet.ImageName, Location);

                // generate a domain name label if it's not specified.
                _cmdlet.DomainNameLabel = await PublicIPAddressStrategy.UpdateDomainNameLabelAsync(
                    domainNameLabel : _cmdlet.DomainNameLabel,
                    name : _cmdlet.VMScaleSetName,
                    location : Location,
                    client : _client);

                var resourceGroup = ResourceGroupStrategy.CreateResourceGroupConfig(_cmdlet.ResourceGroupName);

                var noZones = _cmdlet.Zone == null || _cmdlet.Zone.Count == 0;

                var publicIpAddress = resourceGroup.CreatePublicIPAddressConfig(
                    name: _cmdlet.PublicIpAddressName,
                    edgeZone: _cmdlet.EdgeZone,
                    domainNameLabel: _cmdlet.DomainNameLabel,
                    allocationMethod: _cmdlet.AllocationMethod,
                    //sku.Basic is not compatible with multiple placement groups
                    sku: (noZones && _cmdlet.SinglePlacementGroup.IsPresent)
                        ? PublicIPAddressStrategy.Sku.Basic
                        : PublicIPAddressStrategy.Sku.Standard,
                    zones: null);

                var virtualNetwork = resourceGroup.CreateVirtualNetworkConfig(
                    name: _cmdlet.VirtualNetworkName,
                    edgeZone: _cmdlet.EdgeZone,
                    addressPrefix: _cmdlet.VnetAddressPrefix);

                var subnet = virtualNetwork.CreateSubnet(
                    _cmdlet.SubnetName, _cmdlet.SubnetAddressPrefix);

                var loadBalancer = resourceGroup.CreateLoadBalancerConfig(
                    name: _cmdlet.LoadBalancerName,
                    //sku.Basic is not compatible with multiple placement groups
                    sku: (noZones && _cmdlet.SinglePlacementGroup.IsPresent)
                        ? LoadBalancerStrategy.Sku.Basic
                        : LoadBalancerStrategy.Sku.Standard);

                var frontendIpConfiguration = loadBalancer.CreateFrontendIPConfiguration(
                    name: _cmdlet.FrontendPoolName,
                    publicIpAddress: publicIpAddress);

                var backendAddressPool = loadBalancer.CreateBackendAddressPool(
                    name: _cmdlet.BackendPoolName);

                if (_cmdlet.BackendPort != null)
                {
                    var loadBalancingRuleName = _cmdlet.LoadBalancerName;
                    foreach (var backendPort in _cmdlet.BackendPort)
                    {
                        loadBalancer.CreateLoadBalancingRule(
                            name: loadBalancingRuleName + backendPort.ToString(),
                            fronendIpConfiguration: frontendIpConfiguration,
                            backendAddressPool: backendAddressPool,
                            frontendPort: backendPort,
                            backendPort: backendPort);
                    }
                }

                _cmdlet.NatBackendPort = ImageAndOsType.UpdatePorts(_cmdlet.NatBackendPort);

                var networkSecurityGroup = noZones
                    ? null
                    : resourceGroup.CreateNetworkSecurityGroupConfig(
                    _cmdlet.VMScaleSetName,
                    _cmdlet.NatBackendPort.Concat(_cmdlet.BackendPort).ToList());

                var proximityPlacementGroup = resourceGroup.CreateProximityPlacementGroupSubResourceFunc(_cmdlet.ProximityPlacementGroupId);

                var hostGroup = resourceGroup.CreateDedicatedHostGroupSubResourceFunc(_cmdlet.HostGroupId);

                return(resourceGroup.CreateVirtualMachineScaleSetConfigOrchestrationModeFlexible(
                           name: _cmdlet.VMScaleSetName,
                           subnet: subnet,
                           backendAdressPool: backendAddressPool,
                           networkSecurityGroup: networkSecurityGroup,
                           imageAndOsType: ImageAndOsType,
                           adminUsername: _cmdlet.Credential.UserName,
                           adminPassword: new NetworkCredential(string.Empty, _cmdlet.Credential.Password).Password,
                           vmSize: _cmdlet.VmSize,
                           instanceCount: _cmdlet.InstanceCount,
                           dataDisks: _cmdlet.DataDiskSizeInGb,
                           zones: _cmdlet.Zone,
                           ultraSSDEnabled: _cmdlet.EnableUltraSSD.IsPresent,
                           identity: _cmdlet.GetVmssIdentityFromArgs(),
                           singlePlacementGroup: singlePlacementGroupFlexibleDefault,
                           proximityPlacementGroup: proximityPlacementGroup,
                           hostGroup: hostGroup,
                           priority: _cmdlet.Priority,
                           evictionPolicy: _cmdlet.EvictionPolicy,
                           maxPrice: _cmdlet.IsParameterBound(c => c.MaxPrice) ? _cmdlet.MaxPrice : (double?)null,
                           scaleInPolicy: _cmdlet.ScaleInPolicy,
                           doNotRunExtensionsOnOverprovisionedVMs: _cmdlet.SkipExtensionsOnOverprovisionedVMs.IsPresent,
                           encryptionAtHost: _cmdlet.EncryptionAtHost.IsPresent,
                           platformFaultDomainCount: platformFaultDomainCountFlexibleDefault,
                           edgeZone: _cmdlet.EdgeZone,
                           orchestrationMode: _cmdlet.IsParameterBound(c => c.OrchestrationMode) ? _cmdlet.OrchestrationMode : null,
                           capacityReservationId: _cmdlet.IsParameterBound(c => c.CapacityReservationGroupId) ? _cmdlet.CapacityReservationGroupId : null
                           ));
            }
Example #8
0
            private async Task <ResourceConfig <VirtualMachineScaleSet> > SimpleParameterSetNormalMode()
            {
                ImageAndOsType = await _client.UpdateImageAndOsTypeAsync(
                    ImageAndOsType, _cmdlet.ResourceGroupName, _cmdlet.ImageName, Location);

                // generate a domain name label if it's not specified.
                _cmdlet.DomainNameLabel = await PublicIPAddressStrategy.UpdateDomainNameLabelAsync(
                    domainNameLabel : _cmdlet.DomainNameLabel,
                    name : _cmdlet.VMScaleSetName,
                    location : Location,
                    client : _client);

                var resourceGroup = ResourceGroupStrategy.CreateResourceGroupConfig(_cmdlet.ResourceGroupName);

                var noZones = _cmdlet.Zone == null || _cmdlet.Zone.Count == 0;

                var publicIpAddress = resourceGroup.CreatePublicIPAddressConfig(
                    name: _cmdlet.PublicIpAddressName,
                    edgeZone: _cmdlet.EdgeZone,
                    domainNameLabel: _cmdlet.DomainNameLabel,
                    allocationMethod: _cmdlet.AllocationMethod,
                    //sku.Basic is not compatible with multiple placement groups
                    sku: (noZones && _cmdlet.SinglePlacementGroup.IsPresent)
                        ? PublicIPAddressStrategy.Sku.Basic
                        : PublicIPAddressStrategy.Sku.Standard,
                    zones: null);

                var virtualNetwork = resourceGroup.CreateVirtualNetworkConfig(
                    name: _cmdlet.VirtualNetworkName,
                    edgeZone: _cmdlet.EdgeZone,
                    addressPrefix: _cmdlet.VnetAddressPrefix);

                var subnet = virtualNetwork.CreateSubnet(
                    _cmdlet.SubnetName, _cmdlet.SubnetAddressPrefix);

                var loadBalancer = resourceGroup.CreateLoadBalancerConfig(
                    name: _cmdlet.LoadBalancerName,
                    //sku.Basic is not compatible with multiple placement groups
                    sku: (noZones && _cmdlet.SinglePlacementGroup.IsPresent)
                        ? LoadBalancerStrategy.Sku.Basic
                        : LoadBalancerStrategy.Sku.Standard);

                var frontendIpConfiguration = loadBalancer.CreateFrontendIPConfiguration(
                    name: _cmdlet.FrontendPoolName,
                    publicIpAddress: publicIpAddress);

                var backendAddressPool = loadBalancer.CreateBackendAddressPool(
                    name: _cmdlet.BackendPoolName);

                if (_cmdlet.BackendPort != null)
                {
                    var loadBalancingRuleName = _cmdlet.LoadBalancerName;
                    foreach (var backendPort in _cmdlet.BackendPort)
                    {
                        loadBalancer.CreateLoadBalancingRule(
                            name: loadBalancingRuleName + backendPort.ToString(),
                            fronendIpConfiguration: frontendIpConfiguration,
                            backendAddressPool: backendAddressPool,
                            frontendPort: backendPort,
                            backendPort: backendPort);
                    }
                }

                _cmdlet.NatBackendPort = ImageAndOsType.UpdatePorts(_cmdlet.NatBackendPort);

                var inboundNatPoolName = _cmdlet.VMScaleSetName;
                var PortRangeSize      = _cmdlet.InstanceCount * 2;

                var ports = _cmdlet
                            .NatBackendPort
                            ?.Select((port, i) => Tuple.Create(
                                         port,
                                         FirstPortRangeStart + i * 2000))
                            .ToList();

                var inboundNatPools = ports
                                      ?.Select(p => loadBalancer.CreateInboundNatPool(
                                                   name: inboundNatPoolName + p.Item1.ToString(),
                                                   frontendIpConfiguration: frontendIpConfiguration,
                                                   frontendPortRangeStart: p.Item2,
                                                   frontendPortRangeEnd: p.Item2 + PortRangeSize,
                                                   backendPort: p.Item1))
                                      .ToList();

                var networkSecurityGroup = noZones
                    ? null
                    : resourceGroup.CreateNetworkSecurityGroupConfig(
                    _cmdlet.VMScaleSetName,
                    _cmdlet.NatBackendPort.Concat(_cmdlet.BackendPort).ToList());

                var proximityPlacementGroup = resourceGroup.CreateProximityPlacementGroupSubResourceFunc(_cmdlet.ProximityPlacementGroupId);

                var hostGroup = resourceGroup.CreateDedicatedHostGroupSubResourceFunc(_cmdlet.HostGroupId);

                if (_cmdlet.IsParameterBound(c => c.UserData))
                {
                    if (!ValidateBase64EncodedString.ValidateStringIsBase64Encoded(_cmdlet.UserData))
                    {
                        _cmdlet.UserData = ValidateBase64EncodedString.EncodeStringToBase64(_cmdlet.UserData);
                        _cmdlet.WriteInformation(ValidateBase64EncodedString.UserDataEncodeNotification, new string[] { "PSHOST" });
                    }
                }

                return(resourceGroup.CreateVirtualMachineScaleSetConfig(
                           name: _cmdlet.VMScaleSetName,
                           subnet: subnet,
                           backendAdressPool: backendAddressPool,
                           inboundNatPools: inboundNatPools,
                           networkSecurityGroup: networkSecurityGroup,
                           imageAndOsType: ImageAndOsType,
                           adminUsername: _cmdlet.Credential.UserName,
                           adminPassword: new NetworkCredential(string.Empty, _cmdlet.Credential.Password).Password,
                           vmSize: _cmdlet.VmSize,
                           instanceCount: _cmdlet.InstanceCount,
                           upgradeMode: _cmdlet.MyInvocation.BoundParameters.ContainsKey(nameof(UpgradePolicyMode))
                        ? _cmdlet.UpgradePolicyMode
                        : (UpgradeMode?)null,
                           dataDisks: _cmdlet.DataDiskSizeInGb,
                           zones: _cmdlet.Zone,
                           ultraSSDEnabled: _cmdlet.EnableUltraSSD.IsPresent,
                           identity: _cmdlet.GetVmssIdentityFromArgs(),
                           singlePlacementGroup: _cmdlet.SinglePlacementGroup.IsPresent,
                           proximityPlacementGroup: proximityPlacementGroup,
                           hostGroup: hostGroup,
                           priority: _cmdlet.Priority,
                           evictionPolicy: _cmdlet.EvictionPolicy,
                           maxPrice: _cmdlet.IsParameterBound(c => c.MaxPrice) ? _cmdlet.MaxPrice : (double?)null,
                           scaleInPolicy: _cmdlet.ScaleInPolicy,
                           doNotRunExtensionsOnOverprovisionedVMs: _cmdlet.SkipExtensionsOnOverprovisionedVMs.IsPresent,
                           encryptionAtHost: _cmdlet.EncryptionAtHost.IsPresent,
                           platformFaultDomainCount: _cmdlet.IsParameterBound(c => c.PlatformFaultDomainCount) ? _cmdlet.PlatformFaultDomainCount : (int?)null,
                           edgeZone: _cmdlet.EdgeZone,
                           orchestrationMode: _cmdlet.IsParameterBound(c => c.OrchestrationMode) ? _cmdlet.OrchestrationMode : null,
                           capacityReservationId: _cmdlet.IsParameterBound(c => c.CapacityReservationGroupId) ? _cmdlet.CapacityReservationGroupId : null,
                           userData: _cmdlet.IsParameterBound(c => c.UserData) ? _cmdlet.UserData : null
                           ));
            }