public static async Task <TModel> RunAsync <TModel>(
            Client client,
            IParameters <TModel> parameters,
            IAsyncCmdlet asyncCmdlet,
            CancellationToken cancellationToken)
            where TModel : class
        {
            // create a DAG of configs.
            var config = await parameters.CreateConfigAsync();

            // reade current Azure state.
            var current = await config.GetStateAsync(client, cancellationToken);

            // update location.
            parameters.Location = current.UpdateLocation(parameters.Location, config);

            // update a DAG of configs.
            config = await parameters.CreateConfigAsync();

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

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

            return(newState.Get(config) ?? current.Get(config));
        }
示例#2
0
        async Task SimpleParameterSetExecuteCmdlet(IAsyncCmdlet asyncCmdlet)
        {
            bool loadBalancerNamePassedIn = !String.IsNullOrWhiteSpace(LoadBalancerName);

            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 client = new Client(DefaultProfile.DefaultContext);

            var parameters = new Parameters(this, client);

            // If the user did not specify a load balancer name, mark the LB setting to ignore
            // preexisting check. The most common scenario is users will let the cmdlet create and name the LB for them with the default
            // config. We do not want to block that scenario in case the cmdlet failed mid operation and tthe user kicks it off again.
            if (!loadBalancerNamePassedIn)
            {
                LoadBalancerStrategy.IgnorePreExistingConfigCheck = true;
            }
            else
            {
                LoadBalancerStrategy.IgnorePreExistingConfigCheck = false;
            }

            var result = await client.RunAsync(client.SubscriptionId, parameters, asyncCmdlet);


            if (result != null)
            {
                var fqdn = PublicIPAddressStrategy.Fqdn(DomainNameLabel, Location);

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

                var port             = "<port>";
                var connectionString = parameters.ImageAndOsType.GetConnectionString(
                    fqdn,
                    Credential.UserName,
                    port);
                var range =
                    FirstPortRangeStart.ToString() +
                    ".." +
                    (FirstPortRangeStart + InstanceCount * 2 - 1).ToString();

                asyncCmdlet.WriteVerbose(
                    Resources.VmssUseConnectionString,
                    connectionString);
                asyncCmdlet.WriteVerbose(
                    Resources.VmssPortRange,
                    port,
                    range);
                asyncCmdlet.WriteObject(psObject);
            }
        }
        async Task SimpleExecuteCmdlet(IAsyncCmdlet asyncCmdlet)
        {
            var client = new Client(DefaultProfile.DefaultContext);

            var parameters = new Parameters(this);

            var result = await client.RunAsync(
                client.SubscriptionId, parameters, asyncCmdlet);

            if (result != null)
            {
                var psResult = new PSSignalRResource(result);
                asyncCmdlet.WriteObject(psResult);
            }
        }
示例#4
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 client = new Client(DefaultProfile.DefaultContext);

            var parameters = new Parameters(this, client);

            var result = await StrategyCmdlet.RunAsync(
                client, parameters, asyncCmdlet, new CancellationToken());

            if (result != null)
            {
                var fqdn = PublicIPAddressStrategy.Fqdn(DomainNameLabel, Location);

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

                var port             = "<port>";
                var connectionString = parameters.ImageAndOsType.GetConnectionString(
                    fqdn,
                    Credential.UserName,
                    port);
                var range =
                    FirstPortRangeStart.ToString() +
                    ".." +
                    (FirstPortRangeStart + InstanceCount * 2).ToString();

                asyncCmdlet.WriteVerbose(
                    Resources.VmssUseConnectionString,
                    connectionString);
                asyncCmdlet.WriteVerbose(
                    Resources.VmssPortRange,
                    port,
                    range);
                asyncCmdlet.WriteObject(psObject);
            }
        }
示例#5
0
        /// <summary>
        /// The function read current Azure state and update it according to the `parameters`.
        /// </summary>
        /// <typeparam name="TModel">A resource model type.</typeparam>
        /// <param name="client">Azure SDK client.</param>
        /// <param name="subscriptionId">Subbscription Id.</param>
        /// <param name="parameters">Cmdlet parameters.</param>
        /// <param name="asyncCmdlet">Asynchronous cmdlet interface.</param>
        /// <param name="cancellationToken">Cancellation token.</param>
        /// <returns></returns>
        public static async Task <TModel> RunAsync <TModel>(
            this IClient client,
            string subscriptionId,
            IParameters <TModel> parameters,
            IAsyncCmdlet asyncCmdlet)
            where TModel : class
        {
            // create a DAG of configs.
            var config = await parameters.CreateConfigAsync();

            // read current Azure state.
            var current = await config.GetStateAsync(client, asyncCmdlet.CancellationToken);

            // update location.
            parameters.Location =
                parameters.Location ?? current.GetLocation(config) ?? parameters.DefaultLocation;
            // update a DAG of configs.
            config = await parameters.CreateConfigAsync();

            // create a target.
            var target = config.GetTargetState(
                current, new SdkEngine(subscriptionId), parameters.Location);

            // print paramaters to a verbose stream.
            foreach (var p in asyncCmdlet.Parameters)
            {
                asyncCmdlet.WriteVerbose(p.Key + " = " + ToPowerShellString(p.Value));
            }

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

            // return a resource model
            return(newState.Get(config) ?? current.Get(config));
        }
示例#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,
                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);
            }
        }
示例#7
0
        async Task StrategyExecuteCmdletAsync(IAsyncCmdlet asyncCmdlet)
        {
            var client = new Client(DefaultProfile.DefaultContext);

            ResourceGroupName   = ResourceGroupName ?? Name;
            VirtualNetworkName  = VirtualNetworkName ?? Name;
            SubnetName          = SubnetName ?? Name;
            PublicIpAddressName = PublicIpAddressName ?? Name;
            SecurityGroupName   = SecurityGroupName ?? Name;

            var resourceClient = AzureSession.Instance.ClientFactory.CreateArmClient <ResourceManagementClient>(
                DefaultProfile.DefaultContext,
                AzureEnvironment.Endpoint.ResourceManager);

            var parameters = new Parameters(this, client, resourceClient);


            if (DiskFile != null)
            {
                if (!resourceClient.ResourceGroups.CheckExistence(ResourceGroupName))
                {
                    Location = Location ?? parameters.DefaultLocation;
                    var st0 = resourceClient.ResourceGroups.CreateOrUpdate(
                        ResourceGroupName,
                        new ResourceGroup
                    {
                        Location = Location,
                        Name     = ResourceGroupName
                    });
                }
                parameters.ImageAndOsType = new ImageAndOsType(
                    Linux ? OperatingSystemTypes.Linux : OperatingSystemTypes.Windows,
                    null,
                    null);
                var storageClient = AzureSession.Instance.ClientFactory.CreateArmClient <StorageManagementClient>(
                    DefaultProfile.DefaultContext,
                    AzureEnvironment.Endpoint.ResourceManager);
                var st1 = storageClient.StorageAccounts.Create(
                    ResourceGroupName,
                    Name,
                    new StorageAccountCreateParameters
                {
                    Sku = new Microsoft.Azure.Management.Storage.Version2017_10_01.Models.Sku
                    {
                        Name = SkuName.PremiumLRS
                    },
                    Location = Location
                });
                var filePath = new FileInfo(SessionState.Path.GetUnresolvedProviderPathFromPSPath(DiskFile));
                using (var vds = new VirtualDiskStream(filePath.FullName))
                {
                    // 2 ^ 9 == 512
                    if (vds.DiskType == DiskType.Fixed && filePath.Length % 512 != 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 parameters.DestinationUri);
                if (parameters.DestinationUri?.Uri == null)
                {
                    throw new ArgumentNullException("destinationUri");
                }
                var storageCredentialsFactory = new StorageCredentialsFactory(
                    ResourceGroupName, storageClient, DefaultContext.Subscription);
                var uploadParameters = new UploadParameters(parameters.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(uploadParameters);
                }
            }

            var result = await client.RunAsync(client.SubscriptionId, parameters, asyncCmdlet);

            if (result != null)
            {
                var fqdn     = PublicIPAddressStrategy.Fqdn(DomainNameLabel, Location);
                var psResult = ComputeAutoMapperProfile.Mapper.Map <PSVirtualMachine>(result);
                psResult.FullyQualifiedDomainName = fqdn;
                var connectionString = parameters.ImageAndOsType.GetConnectionString(
                    fqdn,
                    Credential?.UserName);
                asyncCmdlet.WriteVerbose(
                    Resources.VirtualMachineUseConnectionString,
                    connectionString);
                asyncCmdlet.WriteObject(psResult);
            }
        }
示例#8
0
        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 ShouldProcess(IAsyncCmdlet cmdlet)
 {
     _Cmdlet = cmdlet;
 }
示例#10
0
 /// <summary>
 /// WriteVerbose function with formatting.
 /// </summary>
 /// <param name="cmdlet">Cmdlet</param>
 /// <param name="message">message with formatting</param>
 /// <param name="p">message parameters</param>
 public static void WriteVerbose(this IAsyncCmdlet cmdlet, string message, params object[] p)
 => cmdlet.WriteVerbose(string.Format(message, p));
示例#11
0
        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);
            }
        }
示例#12
0
        public async Task CreateWithSimpleParameters(IAsyncCmdlet adapter)
        {
            var parameters = new Parameters(this);
            var client     = new WebClient(DefaultContext);
            var output     = await client.RunAsync(client.SubscriptionId, parameters, adapter);

            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(SessionState.Path, GitRepositoryPath);
                    var repository = await git.VerifyGitRepository();

                    if (repository != null)
                    {
                        if (!await git.CheckExistence())
                        {
                            adapter.WriteWarning(git.InstallationInstructions);
                        }
                        else if (!string.IsNullOrWhiteSpace(userName) && !string.IsNullOrWhiteSpace(password))
                        {
                            await git.AddRemoteRepository("azure", $"https://{userName}:{password}@{scmHostName}");

                            adapter.WriteVerbose(Properties.Resources.GitRemoteMessage);
                            newOutput.GitRemoteName = "azure";
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                // do not write errors for problems with adding git repository
                var repoPath = GitRepositoryPath ?? SessionState?.Path?.CurrentFileSystemLocation?.Path;
                adapter.WriteWarning(string.Format(
                                         Properties.Resources.GitRemoteAddFailure,
                                         repoPath,
                                         exception.Message));
            }
            adapter.WriteObject(output);
        }
示例#13
0
 private AsyncCmdletContext(
     [NotNull] IAsyncCmdlet cmdlet)
 {
     this._cmdlet = cmdlet;
 }
示例#14
0
        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);
            }
        }
示例#15
0
 public ProgressReport(IAsyncCmdlet cmdlet)
 {
     _Cmdlet = cmdlet;
 }
示例#16
0
        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);
            }
        }
示例#17
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);
            }
        }