public static ResourceConfig <VirtualMachine> CreateVirtualMachineConfig( this ResourceConfig <ResourceGroup> resourceGroup, string name, ResourceConfig <NetworkInterface> networkInterface, ImageAndOsType imageAndOsType, string adminUsername, string adminPassword, string size, ResourceConfig <AvailabilitySet> availabilitySet, VirtualMachineIdentity identity, IEnumerable <int> dataDisks, IList <string> zones, Func <IEngine, SubResource> proximityPlacementGroup, string hostId, string hostGroupId, string capacityReservationGroupId, string VmssId, string priority, string evictionPolicy, double?maxPrice, bool encryptionAtHostPresent, List <SshPublicKey> sshPublicKeys, int?platformFaultDomain = null, string networkInterfaceDeleteOption = null, string osDiskDeleteOption = null, string dataDiskDeleteOption = null, string userData = null, AdditionalCapabilities additionalCapabilities = null ) => Strategy.CreateResourceConfig( resourceGroup: resourceGroup, name: name, createModel: engine => new VirtualMachine { OsProfile = new OSProfile { ComputerName = name, WindowsConfiguration = imageAndOsType?.CreateWindowsConfiguration(), LinuxConfiguration = (imageAndOsType?.OsType != OperatingSystemTypes.Linux) ? null : new LinuxConfiguration { Ssh = new SshConfiguration(sshPublicKeys) }, AdminUsername = adminUsername, AdminPassword = adminPassword, }, Identity = identity, NetworkProfile = new Azure.Management.Compute.Models.NetworkProfile { NetworkInterfaces = new[] { engine.GetReference(networkInterface, networkInterfaceDeleteOption) } }, HardwareProfile = new HardwareProfile { VmSize = size }, StorageProfile = new StorageProfile { ImageReference = imageAndOsType?.Image, DataDisks = DataDiskStrategy.CreateDataDisks( imageAndOsType?.DataDiskLuns, dataDisks, dataDiskDeleteOption) }, AvailabilitySet = engine.GetReference(availabilitySet), Zones = zones, AdditionalCapabilities = additionalCapabilities, ProximityPlacementGroup = proximityPlacementGroup(engine), Host = string.IsNullOrEmpty(hostId) ? null : new SubResource(hostId), VirtualMachineScaleSet = string.IsNullOrEmpty(VmssId) ? null : new SubResource(VmssId), HostGroup = string.IsNullOrEmpty(hostGroupId) ? null : new SubResource(hostGroupId), Priority = priority, EvictionPolicy = evictionPolicy, BillingProfile = (maxPrice == null) ? null : new BillingProfile(maxPrice), SecurityProfile = (encryptionAtHostPresent == true) ? new SecurityProfile(encryptionAtHost: encryptionAtHostPresent) : null, CapacityReservation = string.IsNullOrEmpty(capacityReservationGroupId) ? null : new CapacityReservationProfile { CapacityReservationGroup = new SubResource(capacityReservationGroupId) }, UserData = userData, PlatformFaultDomain = platformFaultDomain });
private void LoadResourceConfig(string configFile) { if (!string.IsNullOrEmpty(configFile)) { ResourceConfig config = new ResourceConfig(); XmlReader reader = XmlReader.Create(configFile); config.ReadXml(reader); reader.Close(); lock (this) { if (configs.ContainsKey(config.Culture)) { configs[config.Culture] = config; } else { configs.Add(config.Culture, config); } } } }
internal static ResourceConfig <VirtualMachineScaleSet> CreateVirtualMachineScaleSetConfig( this ResourceConfig <ResourceGroup> resourceGroup, string name, NestedResourceConfig <Subnet, VirtualNetwork> subnet, IEnumerable <NestedResourceConfig <FrontendIPConfiguration, LoadBalancer> > frontendIpConfigurations, NestedResourceConfig <BackendAddressPool, LoadBalancer> backendAdressPool, IEnumerable <NestedResourceConfig <InboundNatPool, LoadBalancer> > inboundNatPools, ImageAndOsType imageAndOsType, string adminUsername, string adminPassword, string vmSize, int instanceCount, UpgradeMode?upgradeMode, IEnumerable <int> dataDisks) => Strategy.CreateResourceConfig( resourceGroup: resourceGroup, name: name, createModel: engine => new VirtualMachineScaleSet() { Zones = frontendIpConfigurations ?.Select(f => f.CreateModel(engine)) ?.Where(z => z?.Zones != null) .SelectMany(z => z.Zones) .Where(z => z != null) .ToList(), UpgradePolicy = new UpgradePolicy { Mode = upgradeMode ?? UpgradeMode.Manual }, Sku = new Azure.Management.Compute.Models.Sku() { Capacity = instanceCount, Name = vmSize, }, VirtualMachineProfile = new VirtualMachineScaleSetVMProfile { OsProfile = new VirtualMachineScaleSetOSProfile { ComputerNamePrefix = name.Substring(0, Math.Min(name.Length, 9)), WindowsConfiguration = imageAndOsType.CreateWindowsConfiguration(), LinuxConfiguration = imageAndOsType.CreateLinuxConfiguration(), AdminUsername = adminUsername, AdminPassword = adminPassword, }, StorageProfile = new VirtualMachineScaleSetStorageProfile { ImageReference = imageAndOsType?.Image, DataDisks = DataDiskStrategy.CreateVmssDataDisks( imageAndOsType?.DataDiskLuns, dataDisks) }, NetworkProfile = new VirtualMachineScaleSetNetworkProfile { NetworkInterfaceConfigurations = new[] { new VirtualMachineScaleSetNetworkConfiguration { Name = name, IpConfigurations = new [] { new VirtualMachineScaleSetIPConfiguration { Name = name, LoadBalancerBackendAddressPools = new [] { engine.GetReference(backendAdressPool) }, Subnet = engine.GetReference(subnet), LoadBalancerInboundNatPools = inboundNatPools ?.Select(engine.GetReference) .ToList() } }, Primary = true } } } } });
public static ResourceConfig <VirtualMachine> CreateVirtualMachineConfig( this ResourceConfig <ResourceGroup> resourceGroup, string name, ResourceConfig <NetworkInterface> networkInterface, OperatingSystemTypes osType, ResourceConfig <Disk> disk, string size, ResourceConfig <AvailabilitySet> availabilitySet, VirtualMachineIdentity identity, IEnumerable <int> dataDisks, IList <string> zones, bool ultraSSDEnabled, Func <IEngine, SubResource> proximityPlacementGroup, string hostId, string hostGroupId, string capacityReservationGroupId, string VmssId, string priority, string evictionPolicy, double?maxPrice, bool encryptionAtHostPresent, int?platformFaultDomain, string networkInterfaceDeleteOption = null, string osDiskDeleteOption = null, string dataDiskDeleteOption = null, string userData = null, AdditionalCapabilities additionalCapabilities = null ) => Strategy.CreateResourceConfig( resourceGroup: resourceGroup, name: name, createModel: engine => new VirtualMachine { NetworkProfile = new Microsoft.Azure.Management.Compute.Models.NetworkProfile { NetworkInterfaces = new[] { engine.GetReference(networkInterface, networkInterfaceDeleteOption) } }, HardwareProfile = new HardwareProfile { VmSize = size }, StorageProfile = new StorageProfile { OsDisk = new OSDisk { Name = disk.Name, CreateOption = DiskCreateOptionTypes.Attach, OsType = osType, ManagedDisk = engine.GetReference(disk, ultraSSDEnabled ? StorageAccountTypes.UltraSSDLRS : StorageAccountTypes.PremiumLRS), DeleteOption = osDiskDeleteOption }, DataDisks = DataDiskStrategy.CreateDataDisks(null, dataDisks, dataDiskDeleteOption) }, Identity = identity, AvailabilitySet = engine.GetReference(availabilitySet), Zones = zones, AdditionalCapabilities = additionalCapabilities, ProximityPlacementGroup = proximityPlacementGroup(engine), Host = string.IsNullOrEmpty(hostId) ? null : new SubResource(hostId), VirtualMachineScaleSet = string.IsNullOrEmpty(VmssId) ? null : new SubResource(VmssId), HostGroup = string.IsNullOrEmpty(hostGroupId) ? null : new SubResource(hostGroupId), Priority = priority, EvictionPolicy = evictionPolicy, BillingProfile = (maxPrice == null) ? null : new BillingProfile(maxPrice), SecurityProfile = (encryptionAtHostPresent == true) ? new SecurityProfile(encryptionAtHost: encryptionAtHostPresent) : null, CapacityReservation = string.IsNullOrEmpty(capacityReservationGroupId) ? null : new CapacityReservationProfile { CapacityReservationGroup = new SubResource(capacityReservationGroupId) }, UserData = userData, PlatformFaultDomain = platformFaultDomain });
internal static ResourceConfig <VirtualMachineScaleSet> CreateVirtualMachineScaleSetConfig( this ResourceConfig <ResourceGroup> resourceGroup, string name, NestedResourceConfig <Subnet, VirtualNetwork> subnet, NestedResourceConfig <BackendAddressPool, LoadBalancer> backendAdressPool, IEnumerable <NestedResourceConfig <InboundNatPool, LoadBalancer> > inboundNatPools, ResourceConfig <NetworkSecurityGroup> networkSecurityGroup, ImageAndOsType imageAndOsType, string adminUsername, string adminPassword, string vmSize, int instanceCount, VirtualMachineScaleSetIdentity identity, bool singlePlacementGroup, UpgradeMode?upgradeMode, IEnumerable <int> dataDisks, IList <string> zones, bool ultraSSDEnabled, Func <IEngine, SubResource> proximityPlacementGroup, Func <IEngine, SubResource> hostGroup, string priority, string evictionPolicy, double?maxPrice, string[] scaleInPolicy, bool doNotRunExtensionsOnOverprovisionedVMs, bool encryptionAtHost, int?platformFaultDomainCount ) => Strategy.CreateResourceConfig( resourceGroup: resourceGroup, name: name, createModel: engine => new VirtualMachineScaleSet() { Zones = zones, UpgradePolicy = new UpgradePolicy { Mode = upgradeMode ?? UpgradeMode.Manual }, Sku = new Azure.Management.Compute.Models.Sku() { Capacity = instanceCount, Name = vmSize, }, Identity = identity, SinglePlacementGroup = singlePlacementGroup, AdditionalCapabilities = ultraSSDEnabled ? new AdditionalCapabilities(true) : null, PlatformFaultDomainCount = platformFaultDomainCount, VirtualMachineProfile = new VirtualMachineScaleSetVMProfile { SecurityProfile = (encryptionAtHost == true) ? new SecurityProfile(encryptionAtHost: encryptionAtHost) : null, OsProfile = new VirtualMachineScaleSetOSProfile { ComputerNamePrefix = name.Substring(0, Math.Min(name.Length, 9)), WindowsConfiguration = imageAndOsType.CreateWindowsConfiguration(), LinuxConfiguration = imageAndOsType.CreateLinuxConfiguration(), AdminUsername = adminUsername, AdminPassword = adminPassword, }, StorageProfile = new VirtualMachineScaleSetStorageProfile { ImageReference = imageAndOsType?.Image, DataDisks = DataDiskStrategy.CreateVmssDataDisks( imageAndOsType?.DataDiskLuns, dataDisks) }, NetworkProfile = new VirtualMachineScaleSetNetworkProfile { NetworkInterfaceConfigurations = new[] { new VirtualMachineScaleSetNetworkConfiguration { Name = name, IpConfigurations = new [] { new VirtualMachineScaleSetIPConfiguration { Name = name, LoadBalancerBackendAddressPools = new [] { engine.GetReference(backendAdressPool) }, Subnet = engine.GetReference(subnet), LoadBalancerInboundNatPools = inboundNatPools ?.Select(engine.GetReference) .ToList() } }, Primary = true, NetworkSecurityGroup = engine.GetReference(networkSecurityGroup) } } }, Priority = priority, EvictionPolicy = evictionPolicy, BillingProfile = (maxPrice == null) ? null : new BillingProfile(maxPrice) }, ProximityPlacementGroup = proximityPlacementGroup(engine), HostGroup = hostGroup(engine), ScaleInPolicy = (scaleInPolicy == null) ? null : new ScaleInPolicy { Rules = scaleInPolicy }, DoNotRunExtensionsOnOverprovisionedVMs = doNotRunExtensionsOnOverprovisionedVMs ? true : (bool?)null });
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); } }
public static ResourceConfig <VirtualMachine> CreateVirtualMachineConfig( this ResourceConfig <ResourceGroup> resourceGroup, string name, ResourceConfig <NetworkInterface> networkInterface, ImageAndOsType imageAndOsType, string adminUsername, string adminPassword, string size, ResourceConfig <AvailabilitySet> availabilitySet, VirtualMachineIdentity identity, IEnumerable <int> dataDisks, IList <string> zones, bool ultraSSDEnabled, Func <IEngine, SubResource> proximityPlacementGroup, string hostId, string hostGroupId, string VmssId, string priority, string evictionPolicy, double?maxPrice, bool encryptionAtHostPresent) => Strategy.CreateResourceConfig( resourceGroup: resourceGroup, name: name, createModel: engine => new VirtualMachine { OsProfile = new OSProfile { ComputerName = name, WindowsConfiguration = imageAndOsType.CreateWindowsConfiguration(), LinuxConfiguration = imageAndOsType.CreateLinuxConfiguration(), AdminUsername = adminUsername, AdminPassword = adminPassword, }, Identity = identity, NetworkProfile = new NetworkProfile { NetworkInterfaces = new[] { engine.GetReference(networkInterface) } }, HardwareProfile = new HardwareProfile { VmSize = size }, StorageProfile = new StorageProfile { ImageReference = imageAndOsType?.Image, DataDisks = DataDiskStrategy.CreateDataDisks( imageAndOsType?.DataDiskLuns, dataDisks) }, AvailabilitySet = engine.GetReference(availabilitySet), Zones = zones, AdditionalCapabilities = ultraSSDEnabled ? new AdditionalCapabilities(true) : null, ProximityPlacementGroup = proximityPlacementGroup(engine), Host = string.IsNullOrEmpty(hostId) ? null : new SubResource(hostId), VirtualMachineScaleSet = string.IsNullOrEmpty(VmssId) ? null : new SubResource(VmssId), HostGroup = string.IsNullOrEmpty(hostGroupId) ? null : new SubResource(hostGroupId), Priority = priority, EvictionPolicy = evictionPolicy, BillingProfile = (maxPrice == null) ? null : new BillingProfile(maxPrice), SecurityProfile = (encryptionAtHostPresent == true) ? new SecurityProfile(encryptionAtHostPresent) : null });
public static ResourceConfig <ProximityPlacementGroup> CreateProximityPlacementGroupConfig( this ResourceConfig <ResourceGroup> resourceGroup, string name) => Strategy.CreateNoncreatableResourceConfig(resourceGroup: resourceGroup, name: name);
public static ResourceConfig <AvailabilitySet> CreateAvailabilitySetConfig( this ResourceConfig <ResourceGroup> resourceGroup, string name, Func <IEngine, SubResource> proximityPlacementGroup) => Strategy.CreateNoncreatableResourceConfig(resourceGroup: resourceGroup, name: name);
public Task <decimal> GetValue(StateMachineListItem resource, ResourceConfig config, string property) { throw new NotImplementedException(); }
public static TModel GetReference <TModel>(this IEngine engine, ResourceConfig <TModel> config) where TModel : Resource, new() => new TModel { Id = engine.GetId(config) };
public static SubResource GetReference( this IEngine engine, ResourceConfig <N.NetworkSecurityGroup> networkSecurityGroup) => engine.GetSubResourceReference(networkSecurityGroup);
public static SubResource GetReference( this IEngine engine, ResourceConfig <DedicatedHostGroup> dedicatedHostGroup) => engine.GetSubResourceReference(dedicatedHostGroup);
public static SubResource GetReference( this IEngine engine, ResourceConfig <ProximityPlacementGroup> proximityPlacementGroup) => engine.GetSubResourceReference(proximityPlacementGroup);
public static SubResource GetReference( this IEngine engine, ResourceConfig <AvailabilitySet> availabilitySet) => engine.GetSubResourceReference(availabilitySet);