Exemple #1
0
        public override void ExecuteCmdlet()
        {
            if (ParameterSetName == ObjectParameterSet)
            {
                ResourceGroupName = CdnProfile.ResourceGroupName;
                ProfileName       = CdnProfile.Name;
            }

            var existingProfile = CdnManagementClient.Profiles.ListBySubscriptionId().Select(p => p.ToPsProfile())
                                  .Where(p => p.Name.ToLower() == ProfileName.ToLower())
                                  .Where(p => p.ResourceGroupName.ToLower() == ResourceGroupName.ToLower())
                                  .FirstOrDefault();

            if (existingProfile == null)
            {
                throw new PSArgumentException(string.Format(
                                                  Resources.Error_DeleteNonExistingProfile,
                                                  ProfileName,
                                                  ResourceGroupName));
            }


            ConfirmAction(Force,
                          string.Format(Resources.Confirm_RemoveProfile, ProfileName),
                          this.MyInvocation.InvocationName,
                          ProfileName,
                          () => CdnManagementClient.Profiles.DeleteIfExists(ProfileName, ResourceGroupName),
                          () => ContainsEndpoints());

            if (PassThru)
            {
                WriteObject(true);
            }
        }
        public override void ExecuteCmdlet()
        {
            var existingProfile = CdnManagementClient.Profiles.ListBySubscriptionId().Select(p => p.ToPsProfile())
                                  .Where(p => p.Name.ToLower() == ProfileName.ToLower())
                                  .Where(p => p.ResourceGroupName.ToLower() == ResourceGroupName.ToLower())
                                  .FirstOrDefault();

            if (existingProfile != null)
            {
                throw new PSArgumentException(string.Format(Resources.Error_CreateExistingProfile, ProfileName,
                                                            ResourceGroupName));
            }

            ConfirmAction(MyInvocation.InvocationName,
                          ProfileName,
                          NewProfile);
        }
Exemple #3
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);
            }
        }
Exemple #4
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);
            }
        }