public Task <ResourceConfig <SignalRResource> > CreateConfigAsync() { _cmdlet.ResolveResourceGroupName(required: false); _cmdlet.ResourceGroupName = _cmdlet.ResourceGroupName ?? _cmdlet.Name; var resourceGroup = ResourceGroupStrategy.CreateResourceGroupConfig( _cmdlet.ResourceGroupName); var result = SignalRStrategy.Strategy.CreateResourceConfig( resourceGroup: resourceGroup, name: _cmdlet.Name, createModel: engine => new SignalRResource( tags: _cmdlet.Tag, sku: new ResourceSku(_cmdlet.Sku, capacity: _cmdlet.UnitCount), hostNamePrefix: null /* _cmdlet.Name*/)); // hostNamePrefix is just a placeholder and ignored in the resource provider. return(Task.FromResult(result)); }
public async Task <ResourceConfig <Site> > CreateConfigAsync() { _cmdlet.ResourceGroupName = _cmdlet.ResourceGroupName ?? _cmdlet.Name; _cmdlet.AppServicePlan = _cmdlet.AppServicePlan ?? _cmdlet.Name; var planResourceGroup = _cmdlet.ResourceGroupName; var planName = _cmdlet.AppServicePlan; var rgStrategy = ResourceGroupStrategy.CreateResourceGroupConfig(_cmdlet.ResourceGroupName); var planRG = rgStrategy; if (_cmdlet.MyInvocation.BoundParameters.ContainsKey(nameof(AppServicePlan))) { if (!_cmdlet.TryGetServerFarmFromResourceId(_cmdlet.AppServicePlan, out planResourceGroup, out planName)) { planResourceGroup = _cmdlet.ResourceGroupName; planName = _cmdlet.AppServicePlan; } planRG = ResourceGroupStrategy.CreateResourceGroupConfig(planResourceGroup); } else { var farm = await _cmdlet.GetDefaultServerFarm(Location); if (farm != null) { planResourceGroup = farm.ResourceGroup; planName = farm.Name; planRG = ResourceGroupStrategy.CreateResourceGroupConfig(planResourceGroup); } } AppServicePlan appServiceplan = _websitesClient.GetAppServicePlan(planResourceGroup, planName); // If ContainerImageName is specified and appservice plan doesn’t exist (appServiceplan == null) we will try to create plan with windows container var farmStrategy = planRG.CreateServerFarmConfig(planResourceGroup, planName, appServiceplan == null && _cmdlet.ContainerImageName != null); return(rgStrategy.CreateSiteConfig(farmStrategy, _cmdlet.Name, this.GetNewConfig(appServiceplan))); }
public async Task <ResourceConfig <Site> > CreateConfigAsync() { _cmdlet.ResourceGroupName = _cmdlet.ResourceGroupName ?? _cmdlet.Name; _cmdlet.AppServicePlan = _cmdlet.AppServicePlan ?? _cmdlet.Name; var planResourceGroup = _cmdlet.ResourceGroupName; var planName = _cmdlet.AppServicePlan; var rgStrategy = ResourceGroupStrategy.CreateResourceGroupConfig(_cmdlet.ResourceGroupName); var planRG = rgStrategy; if (_cmdlet.MyInvocation.BoundParameters.ContainsKey(nameof(AppServicePlan))) { if (!_cmdlet.TryGetServerFarmFromResourceId(_cmdlet.AppServicePlan, out planResourceGroup, out planName)) { planResourceGroup = _cmdlet.ResourceGroupName; planName = _cmdlet.AppServicePlan; } planRG = ResourceGroupStrategy.CreateResourceGroupConfig(planResourceGroup); } else { var farm = await _cmdlet.GetDefaultServerFarm(Location); if (farm != null) { planResourceGroup = farm.ResourceGroup; planName = farm.Name; planRG = ResourceGroupStrategy.CreateResourceGroupConfig(planResourceGroup); } } var farmStrategy = planRG.CreateServerFarmConfig(planResourceGroup, planName); return(rgStrategy.CreateSiteConfig(farmStrategy, _cmdlet.Name)); }
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()); var proximityPlacementGroup = resourceGroup.CreateProximityPlacementGroupSubResourceFunc(_cmdlet.ProximityPlacementGroupId); 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, priority: _cmdlet.Priority, evictionPolicy: _cmdlet.EvictionPolicy, maxPrice: _cmdlet.IsParameterBound(c => c.MaxPrice) ? _cmdlet.MaxPrice : (double?)null, scaleInPolicy: _cmdlet.ScaleInPolicy, doNotRunExtensionsOnOverprovisionedVMs: _cmdlet.SkipExtensionsOnOverprovisionedVMs.IsPresent )); }
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); } }
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 target = virtualMachine.GetTargetState(current, client.SubscriptionId, 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; asyncCmdlet.WriteVerbose(imageAndOsType.OsType == OperatingSystemTypes.Windows ? "Use 'mstsc /v:" + fqdn + "' to connect to the VM." : "Use 'ssh " + Credential.UserName + "@" + fqdn + "' to connect to the VM."); asyncCmdlet.WriteObject(psResult); } }
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, identity: _cmdlet.GetVMIdentityFromArgs())); } 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, identity: _cmdlet.GetVMIdentityFromArgs())); } }
async Task SimpleParameterSetExecuteCmdlet(IAsyncCmdlet asyncCmdlet) { ResourceGroupName = ResourceGroupName ?? VMScaleSetName; VirtualNetworkName = VirtualNetworkName ?? VMScaleSetName; SubnetName = SubnetName ?? VMScaleSetName; PublicIpAddressName = PublicIpAddressName ?? VMScaleSetName; DomainNameLabel = DomainNameLabel ?? (VMScaleSetName + ResourceGroupName).ToLower(); SecurityGroupName = SecurityGroupName ?? VMScaleSetName; LoadBalancerName = LoadBalancerName ?? VMScaleSetName; FrontendPoolName = FrontendPoolName ?? VMScaleSetName; BackendPoolName = BackendPoolName ?? VMScaleSetName; // get image bool isWindows; Commands.Common.Strategies.Compute.Image image; if (ImageName.Contains(':')) { var imageArray = ImageName.Split(':'); if (imageArray.Length != 4) { throw new Exception("Invalid ImageName"); } image = new Commands.Common.Strategies.Compute.Image { publisher = imageArray[0], offer = imageArray[1], sku = imageArray[2], version = imageArray[3], }; isWindows = image.publisher.ToLower() == "MicrosoftWindowsServer".ToLower(); } else { // get image var osTypeAndImage = Images .Instance .SelectMany(osAndMap => osAndMap .Value .Where(nameAndImage => nameAndImage.Key.ToLower() == ImageName.ToLower()) .Select(nameAndImage => new { OsType = osAndMap.Key, Image = nameAndImage.Value })) .FirstOrDefault(); image = osTypeAndImage.Image; isWindows = osTypeAndImage.OsType == "Windows"; } BackendPort = BackendPort ?? (isWindows ? new[] { 3389, 5985 } : new[] { 22 }); var resourceGroup = ResourceGroupStrategy.CreateResourceGroupConfig(ResourceGroupName); var publicIpAddress = resourceGroup.CreatePublicIPAddressConfig( name: PublicIpAddressName, domainNameLabel: 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, isWindows: isWindows, adminUsername: Credential.UserName, adminPassword: new NetworkCredential(string.Empty, Credential.Password).Password, image: image, vmSize: VmSize, instanceCount: InstanceCount, upgradeMode: (MyInvocation.BoundParameters.ContainsKey("UpgradePolicyMode") == true) ? UpgradePolicyMode : (UpgradeMode?)null); var client = new Client(DefaultProfile.DefaultContext); // get current Azure state var current = await virtualMachineScaleSet.GetStateAsync(client, new CancellationToken()); if (Location == null) { Location = current.GetLocation(virtualMachineScaleSet); if (Location == null) { Location = "eastus"; } } 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 <VirtualMachineScaleSet, PSVirtualMachineScaleSet>(result, psObject); asyncCmdlet.WriteObject(psObject); } }
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 publicIpAddress = resourceGroup.CreatePublicIPAddressConfig( name: _cmdlet.PublicIpAddressName, domainNameLabel: _cmdlet.DomainNameLabel, allocationMethod: _cmdlet.AllocationMethod); 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); var frontendIpConfiguration = loadBalancer.CreateFrontendIPConfiguration( name: _cmdlet.FrontendPoolName, zones: _cmdlet.Zone, 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 inboundNatPools = _cmdlet.NatBackendPort ?.Select((port, i) => { var portRangeStart = FirstPortRangeStart + i * 2000; return(loadBalancer.CreateInboundNatPool( name: inboundNatPoolName + port.ToString(), frontendIpConfiguration: frontendIpConfiguration, frontendPortRangeStart: portRangeStart, frontendPortRangeEnd: portRangeStart + PortRangeSize, backendPort: port)); }) .ToList(); return(resourceGroup.CreateVirtualMachineScaleSetConfig( name: _cmdlet.VMScaleSetName, subnet: subnet, frontendIpConfigurations: new[] { frontendIpConfiguration }, backendAdressPool: backendAddressPool, inboundNatPools: inboundNatPools, 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)); }
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 )); }
public async Task CreateWithSimpleParameters(ICmdletAdapter adapter) { ResourceGroupName = ResourceGroupName ?? Name; AppServicePlan = AppServicePlan ?? Name; string planResourceGroup = ResourceGroupName; string planName = AppServicePlan; var rgStrategy = ResourceGroupStrategy.CreateResourceGroupConfig(ResourceGroupName); ResourceConfig <ResourceGroup> planRG = rgStrategy; if (MyInvocation.BoundParameters.ContainsKey(nameof(AppServicePlan))) { if (!TryGetServerFarmFromResourceId(AppServicePlan, out planResourceGroup, out planName)) { planResourceGroup = ResourceGroupName; planName = AppServicePlan; } planRG = ResourceGroupStrategy.CreateResourceGroupConfig(planResourceGroup); } else { var farm = await GetDefaultServerFarm(Location); if (farm != null) { planResourceGroup = farm.ResourceGroup; planName = farm.Name; planRG = ResourceGroupStrategy.CreateResourceGroupConfig(planResourceGroup); } } var farmStrategy = planRG.CreateServerFarmConfig(planResourceGroup, planName); var siteStrategy = rgStrategy.CreateSiteConfig(farmStrategy, Name); var client = new WebClient(DefaultContext); var current = await siteStrategy.GetStateAsync(client, default(CancellationToken)); if (!MyInvocation.BoundParameters.ContainsKey(nameof(Location))) { Location = current.GetLocation(siteStrategy) ?? "East US"; } var engine = new SdkEngine(DefaultContext.Subscription.Id); var target = siteStrategy.GetTargetState(current, engine, Location); var endState = await siteStrategy.UpdateStateAsync(client, target, default(CancellationToken), adapter, adapter.ReportTaskProgress); var output = endState.Get(siteStrategy) ?? current.Get(siteStrategy); output.SiteConfig = WebsitesClient.WrappedWebsitesClient.WebApps().GetConfiguration(output.ResourceGroup, output.Name).ConvertToSiteConfig(); try { var appSettings = WebsitesClient.WrappedWebsitesClient.WebApps().ListApplicationSettings(output.ResourceGroup, output.Name); output.SiteConfig.AppSettings = appSettings.Properties.Select(s => new NameValuePair { Name = s.Key, Value = s.Value }).ToList(); var connectionStrings = WebsitesClient.WrappedWebsitesClient.WebApps().ListConnectionStrings(output.ResourceGroup, output.Name); output.SiteConfig.ConnectionStrings = connectionStrings .Properties .Select(s => new ConnStringInfo() { Name = s.Key, ConnectionString = s.Value.Value, Type = s.Value.Type }).ToList(); } catch { //ignore if this call fails as it will for reader RBAC } string userName = null, password = null; try { var scmHostName = output.EnabledHostNames.FirstOrDefault(s => s.Contains(".scm.")); if (!string.IsNullOrWhiteSpace(scmHostName)) { var profile = await WebsitesClient.WrappedWebsitesClient.WebApps.ListPublishingProfileXmlWithSecretsAsync(output.ResourceGroup, output.Name, new CsmPublishingProfileOptions { Format = "WebDeploy" }); var doc = new XmlDocument(); doc.Load(profile); userName = doc.SelectSingleNode("//publishProfile[@publishMethod=\"MSDeploy\"]/@userName").Value; password = doc.SelectSingleNode("//publishProfile[@publishMethod=\"MSDeploy\"]/@userPWD").Value; var newOutput = new PSSite(output) { GitRemoteUri = $"https://{scmHostName}", GitRemoteUsername = userName, GitRemotePassword = SecureStringExtensions.ConvertToSecureString(password) }; output = newOutput; var git = new GitCommand(adapter.SessionState.Path, GitRepositoryPath); var repository = await git.VerifyGitRepository(); if (repository != null) { if (!await git.CheckExistence()) { adapter.WriteWarningAsync(git.InstallationInstructions); } else if (!string.IsNullOrWhiteSpace(userName) && !string.IsNullOrWhiteSpace(password)) { await git.AddRemoteRepository("azure", $"https://{userName}:{password}@{scmHostName}"); adapter.WriteVerboseAsync(Microsoft.Azure.Commands.WebApps.Properties.Resources.GitRemoteMessage); newOutput.GitRemoteName = "azure"; } } } } catch (Exception exception) { // do not write errors for problems with adding git repository var repoPath = GitRepositoryPath ?? adapter?.SessionState?.Path?.CurrentFileSystemLocation?.Path; adapter.WriteWarningAsync(String.Format(Microsoft.Azure.Commands.WebApps.Properties.Resources.GitRemoteAddFailure, repoPath, exception.Message)); } adapter.WriteObjectAsync(output); }
async Task StrategyExecuteCmdletAsync(IAsyncCmdlet asyncCmdlet) { ResourceGroupName = ResourceGroupName ?? Name; VirtualNetworkName = VirtualNetworkName ?? Name; SubnetName = SubnetName ?? Name; PublicIpAddressName = PublicIpAddressName ?? Name; DomainNameLabel = DomainNameLabel ?? (Name + '-' + ResourceGroupName).ToLower(); SecurityGroupName = SecurityGroupName ?? Name; bool isWindows; Commands.Common.Strategies.Compute.Image image; if (ImageName.Contains(':')) { var imageArray = ImageName.Split(':'); if (imageArray.Length != 4) { throw new Exception("Invalid ImageName"); } image = new Commands.Common.Strategies.Compute.Image { publisher = imageArray[0], offer = imageArray[1], sku = imageArray[2], version = imageArray[3], }; isWindows = image.publisher.ToLower() == "MicrosoftWindowsServer".ToLower(); } else { // get image var osTypeAndImage = Images .Instance .SelectMany(osAndMap => osAndMap .Value .Where(nameAndImage => nameAndImage.Key.ToLower() == ImageName.ToLower()) .Select(nameAndImage => new { OsType = osAndMap.Key, Image = nameAndImage.Value })) .FirstOrDefault(); image = osTypeAndImage.Image; isWindows = osTypeAndImage.OsType == "Windows"; } OpenPorts = OpenPorts ?? (isWindows ? new[] { 3389, 5985 } : new[] { 22 }); 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, domainNameLabel: DomainNameLabel, allocationMethod: AllocationMethod); var networkSecurityGroup = resourceGroup.CreateNetworkSecurityGroupConfig( name: SecurityGroupName, openPorts: OpenPorts); var networkInterface = resourceGroup.CreateNetworkInterfaceConfig( Name, subnet, publicIpAddress, networkSecurityGroup); var virtualMachine = resourceGroup.CreateVirtualMachineConfig( name: Name, networkInterface: networkInterface, isWindows: isWindows, adminUsername: Credential.UserName, adminPassword: new NetworkCredential(string.Empty, Credential.Password).Password, image: image, size: Size); var client = new Client(DefaultProfile.DefaultContext); // get current Azure state var current = await virtualMachine.GetStateAsync(client, new CancellationToken()); if (Location == null) { Location = current.GetLocation(virtualMachine); if (Location == null) { Location = "eastus"; } } var fqdn = DomainNameLabel + "." + Location + ".cloudapp.azure.com"; // create target state var target = virtualMachine.GetTargetState(current, client.SubscriptionId, Location); // 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; asyncCmdlet.WriteVerbose(isWindows ? "Use 'mstsc /v:" + fqdn + "' to connect to the VM." : "Use 'ssh " + Credential.UserName + "@" + fqdn + "' to connect to the VM."); asyncCmdlet.WriteObject(psResult); } }
async Task StrategyExecuteCmdletAsync(IAsyncCmdlet asyncCmdlet) { ResourceGroupName = ResourceGroupName ?? Name; VirtualNetworkName = VirtualNetworkName ?? Name; SubnetName = SubnetName ?? Name; PublicIpAddressName = PublicIpAddressName ?? Name; DomainNameLabel = DomainNameLabel ?? (Name + '-' + ResourceGroupName).ToLower(); SecurityGroupName = SecurityGroupName ?? Name; bool isWindows; Commands.Common.Strategies.Compute.Image image = null; if (ImageName.Contains(':')) { var imageArray = ImageName.Split(':'); if (imageArray.Length != 4) { throw new Exception("Invalid ImageName"); } image = new Commands.Common.Strategies.Compute.Image { publisher = imageArray[0], offer = imageArray[1], sku = imageArray[2], version = imageArray[3], }; isWindows = image.publisher.ToLower() == "MicrosoftWindowsServer".ToLower(); } else if (!string.IsNullOrEmpty(DiskFile)) { // disk file parameter set requires the OS type input isWindows = !Linux; } else { // get image var osTypeAndImage = Images .Instance .SelectMany(osAndMap => osAndMap .Value .Where(nameAndImage => nameAndImage.Key.ToLower() == ImageName.ToLower()) .Select(nameAndImage => new { OsType = osAndMap.Key, Image = nameAndImage.Value })) .FirstOrDefault(); image = osTypeAndImage.Image; isWindows = osTypeAndImage.OsType == "Windows"; } OpenPorts = OpenPorts ?? (isWindows ? new[] { 3389, 5985 } : new[] { 22 }); 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, domainNameLabel: DomainNameLabel, allocationMethod: AllocationMethod); var networkSecurityGroup = resourceGroup.CreateNetworkSecurityGroupConfig( name: SecurityGroupName, openPorts: OpenPorts); var networkInterface = resourceGroup.CreateNetworkInterfaceConfig( Name, subnet, publicIpAddress, networkSecurityGroup); ResourceConfig <VirtualMachine> virtualMachine = null; if (image != null) { virtualMachine = resourceGroup.CreateVirtualMachineConfig( name: Name, networkInterface: networkInterface, isWindows: isWindows, adminUsername: Credential.UserName, adminPassword: new NetworkCredential(string.Empty, Credential.Password).Password, image: image, size: Size); } else { 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 SM.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, Name.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, isWindows: isWindows, disk: disk, size: Size); } var client = new Client(DefaultProfile.DefaultContext); // get current Azure state var current = await virtualMachine.GetStateAsync(client, new CancellationToken()); if (Location == null) { Location = current.GetLocation(virtualMachine); if (Location == null) { Location = "eastus"; } } var fqdn = DomainNameLabel + "." + Location + ".cloudapp.azure.com"; // create target state var target = virtualMachine.GetTargetState(current, client.SubscriptionId, Location); // 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; asyncCmdlet.WriteVerbose(isWindows ? "Use 'mstsc /v:" + fqdn + "' to connect to the VM." : "Use 'ssh " + Credential.UserName + "@" + fqdn + "' to connect to the VM."); asyncCmdlet.WriteObject(psResult); } }
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); } }
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" }); } } Dictionary <string, List <string> > auxAuthHeader = null; if (!string.IsNullOrEmpty(_cmdlet.ImageReferenceId)) { var resourceId = ResourceId.TryParse(_cmdlet.ImageReferenceId); if (string.Equals(ComputeStrategy.Namespace, resourceId?.ResourceType?.Namespace, StringComparison.OrdinalIgnoreCase) && string.Equals("galleries", resourceId?.ResourceType?.Provider, StringComparison.OrdinalIgnoreCase) && !string.Equals(_cmdlet.ComputeClient?.ComputeManagementClient?.SubscriptionId, resourceId?.SubscriptionId, StringComparison.OrdinalIgnoreCase)) { List <string> resourceIds = new List <string>(); resourceIds.Add(_cmdlet.ImageReferenceId); var auxHeaderDictionary = _cmdlet.GetAuxilaryAuthHeaderFromResourceIds(resourceIds); if (auxHeaderDictionary != null && auxHeaderDictionary.Count > 0) { auxAuthHeader = new Dictionary <string, List <string> >(auxHeaderDictionary); } } } 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, imageReferenceId: _cmdlet.IsParameterBound(c => c.ImageReferenceId) ? _cmdlet.ImageReferenceId : null, auxAuthHeader: auxAuthHeader )); }