コード例 #1
0
        private VirtualMachineCreateDeploymentParameters CreateVMParameters(VirtualMachineOSImageGetResponse image, string serviceName)
        {
            string blobDiskFormat = "http://{1}.blob.core.windows.net/myvhds/{0}.vhd";

            Uri blobUrl = new Uri(string.Format(blobDiskFormat, serviceName, fixture.NewStorageAccountName));

            VirtualMachineCreateDeploymentParameters parameters = new VirtualMachineCreateDeploymentParameters
            {
                DeploymentSlot = DeploymentSlot.Production,
                Label          = fixture.DeploymentLabel,
                Name           = serviceName
            };

            parameters.Roles.Add(new Role
            {
                OSVirtualHardDisk = new OSVirtualHardDisk
                {
                    HostCaching     = VirtualHardDiskHostCaching.ReadWrite,
                    MediaLink       = blobUrl,
                    SourceImageName = image.Name
                },
                ProvisionGuestAgent = true,
                RoleName            = serviceName,
                RoleType            = VirtualMachineRoleType.PersistentVMRole.ToString(),
                RoleSize            = VirtualMachineRoleSize.Large.ToString(),
            });

            return(parameters);
        }
コード例 #2
0
        public static void CreateAzureVirtualMachine(ComputeManagementClient computeClient, string serviceName, string deploymentName, string storageAccountName, string blobUrl)
        {
            VirtualMachineOSImageListResponse imagesList = computeClient.VirtualMachineOSImages.List();

            VirtualMachineOSImageListResponse.VirtualMachineOSImage imageToGet =
                imagesList.Images.FirstOrDefault(i => string.Equals(i.OperatingSystemType, "Windows", StringComparison.OrdinalIgnoreCase));

            VirtualMachineOSImageGetResponse gottenImage = computeClient.VirtualMachineOSImages.Get(imageToGet.Name);

            VirtualMachineCreateDeploymentParameters parameters = CreateVMParameters(gottenImage, deploymentName, storageAccountName, "SampleLabel", blobUrl);

            parameters.Roles[0].ConfigurationSets.Add(new ConfigurationSet
            {
                AdminUserName          = "******",
                AdminPassword          = "******",
                ConfigurationSetType   = ConfigurationSetTypes.WindowsProvisioningConfiguration,
                ComputerName           = serviceName,
                HostName               = string.Format("{0}.cloudapp.net", serviceName),
                EnableAutomaticUpdates = false,
                TimeZone               = "Pacific Standard Time"
            });

            OperationStatusResponse opResp =
                computeClient.VirtualMachines.CreateDeployment(serviceName, parameters);

            Assert.Equal(opResp.Status, OperationStatus.Succeeded);
        }
コード例 #3
0
        protected PSArgument[] CreateVirtualMachineCreateDeploymentParameters()
        {
            string serviceName = string.Empty;
            VirtualMachineCreateDeploymentParameters parameters = new VirtualMachineCreateDeploymentParameters();

            return(ConvertFromObjectsToArguments(new string[] { "ServiceName", "Parameters" }, new object[] { serviceName, parameters }));
        }
コード例 #4
0
        public static VirtualMachineCreateDeploymentParameters CreateVMParameters(VirtualMachineOSImageGetResponse image, string deploymentName, string storageAccount, string deploymentLabel, string blobUri)
        {
            var    blobUrl  = GetUriForVMVhd(deploymentName, storageAccount, blobUri);
            string roleName = AZT.TestUtilities.GenerateName("role");
            VirtualMachineCreateDeploymentParameters parameters = new VirtualMachineCreateDeploymentParameters
            {
                DeploymentSlot = DeploymentSlot.Production,
                Label          = deploymentLabel,
                Name           = deploymentName
            };

            parameters.Roles.Add(new Role
            {
                OSVirtualHardDisk = new OSVirtualHardDisk
                {
                    HostCaching     = VirtualHardDiskHostCaching.ReadWrite,
                    MediaLink       = blobUrl,
                    SourceImageName = image.Name
                },
                ProvisionGuestAgent = true,
                RoleName            = roleName,
                RoleType            = VirtualMachineRoleType.PersistentVMRole.ToString(),
                RoleSize            = VirtualMachineRoleSize.Large.ToString(),
            });

            return(parameters);
        }
コード例 #5
0
        public void CanAbortVirtualMachineDeployment()
        {
            TestUtilities.StartTest();
            using (fixture.ComputeClient = fixture.GetComputeManagementClient())
            {
                var serviceName = TestUtilities.GenerateName();

                var result = fixture.ComputeClient.HostedServices.Create(new HostedServiceCreateParameters
                {
                    Location    = fixture.Location,
                    Label       = serviceName,
                    ServiceName = serviceName
                });

                // assert that the call worked
                Assert.Equal(result.StatusCode, HttpStatusCode.Created);

                VirtualMachineOSImageListResponse imagesList = fixture.ComputeClient.VirtualMachineOSImages.List();

                VirtualMachineOSImageListResponse.VirtualMachineOSImage imageToGet =
                    imagesList.Images.FirstOrDefault(i => string.Equals(i.OperatingSystemType, "Windows", StringComparison.OrdinalIgnoreCase));

                VirtualMachineOSImageGetResponse gottenImage = fixture.ComputeClient.VirtualMachineOSImages.Get(imageToGet.Name);

                VirtualMachineCreateDeploymentParameters parameters = CreateVMParameters(gottenImage, serviceName);

                parameters.Roles[0].ConfigurationSets.Add(new ConfigurationSet
                {
                    AdminUserName          = "******",
                    AdminPassword          = ComputeTestsUtilities.GenerateRandomPassword(),
                    ConfigurationSetType   = ConfigurationSetTypes.WindowsProvisioningConfiguration,
                    ComputerName           = serviceName,
                    HostName               = string.Format("{0}.cloudapp.net", serviceName),
                    EnableAutomaticUpdates = false,
                    TimeZone               = "Pacific Standard Time"
                });

                OperationStatusResponse opResp =
                    fixture.ComputeClient.VirtualMachines.CreateDeployment(serviceName, parameters);

                Assert.Equal(opResp.Status, OperationStatus.Succeeded);

                var prepareParameters = new PrepareDeploymentMigrationParameters
                {
                    DestinationVirtualNetwork = "New",
                    ResourceGroupName         = string.Empty,
                    SubNetName         = string.Empty,
                    VirtualNetworkName = string.Empty
                };

                opResp = fixture.ComputeClient.Deployments.PrepareMigration(serviceName, parameters.Name, prepareParameters);
                Assert.Equal(opResp.Status, OperationStatus.Succeeded);

                opResp = fixture.ComputeClient.Deployments.AbortMigration(serviceName, parameters.Name);
                Assert.Equal(opResp.Status, OperationStatus.Succeeded);
            }

            TestUtilities.EndTest();
        }
コード例 #6
0
        protected void ExecuteVirtualMachineCreateDeploymentMethod(object[] invokeMethodInputParameters)
        {
            string serviceName = (string)ParseParameter(invokeMethodInputParameters[0]);
            VirtualMachineCreateDeploymentParameters parameters = (VirtualMachineCreateDeploymentParameters)ParseParameter(invokeMethodInputParameters[1]);

            var result = VirtualMachineClient.CreateDeployment(serviceName, parameters);

            WriteObject(result);
        }
コード例 #7
0
ファイル: NewAzureVM.cs プロジェクト: mteper/azure-sdk-tools
        public void NewAzureVMProcess()
        {
            WindowsAzureSubscription currentSubscription = CurrentSubscription;
            CloudStorageAccount      currentStorage      = null;

            try
            {
                currentStorage = currentSubscription.GetCloudStorageAccount();
            }
            catch (Exception ex) // couldn't access
            {
                throw new ArgumentException(Resources.CurrentStorageAccountIsNotAccessible, ex);
            }
            if (currentStorage == null) // not set
            {
                throw new ArgumentException(Resources.CurrentStorageAccountIsNotSet);
            }

            try
            {
                if (this.ParameterSetName.Equals("CreateService", StringComparison.OrdinalIgnoreCase))
                {
                    var parameter = new HostedServiceCreateParameters
                    {
                        AffinityGroup = this.AffinityGroup,
                        Location      = this.Location,
                        ServiceName   = this.ServiceName,
                        Description   = this.ServiceDescription ??
                                        String.Format("Implicitly created hosted service{0}", DateTime.Now.ToUniversalTime().ToString("yyyy-MM-dd HH:mm")),
                        Label = this.ServiceLabel ?? this.ServiceName
                    };
                    ExecuteClientActionNewSM(
                        parameter,
                        CommandRuntime + " - Create Cloud Service",
                        () => this.ComputeClient.HostedServices.Create(parameter));
                }
            }
            catch (CloudException ex)
            {
                this.WriteExceptionDetails(ex);
                return;
            }

            foreach (var vm in from v in VMs let configuration = v.ConfigurationSets.OfType <Model.PersistentVMModel.WindowsProvisioningConfigurationSet>().FirstOrDefault() where configuration != null select v)
            {
                if (vm.WinRMCertificate != null)
                {
                    if (!CertUtilsNewSM.HasExportablePrivateKey(vm.WinRMCertificate))
                    {
                        throw new ArgumentException(Resources.WinRMCertificateDoesNotHaveExportablePrivateKey);
                    }
                    var operationDescription = string.Format(Resources.AzureVMUploadingWinRMCertificate, CommandRuntime, vm.WinRMCertificate.Thumbprint);
                    var parameters           = CertUtilsNewSM.Create(vm.WinRMCertificate);
                    ExecuteClientActionNewSM(
                        null,
                        operationDescription,
                        () => this.ComputeClient.ServiceCertificates.Create(this.ServiceName, parameters),
                        (s, r) => ContextFactory <ComputeOperationStatusResponse, ManagementOperationContext>(r, s));
                }
                var certificateFilesWithThumbprint = from c in vm.X509Certificates
                                                     select new
                {
                    c.Thumbprint,
                    CertificateFile = CertUtilsNewSM.Create(c, vm.NoExportPrivateKey)
                };
                foreach (var current in certificateFilesWithThumbprint.ToList())
                {
                    var operationDescription = string.Format(Resources.AzureVMCommandUploadingCertificate, CommandRuntime, current.Thumbprint);
                    ExecuteClientActionNewSM(
                        null,
                        operationDescription,
                        () => this.ComputeClient.ServiceCertificates.Create(this.ServiceName, current.CertificateFile),
                        (s, r) => ContextFactory <ComputeOperationStatusResponse, ManagementOperationContext>(r, s));
                }
            }

            var persistentVMs = this.VMs.Select(vm => CreatePersistentVMRole(vm, currentStorage)).ToList();

            // If the current deployment doesn't exist set it create it
            if (CurrentDeploymentNewSM == null)
            {
                try
                {
                    var parameters = new VirtualMachineCreateDeploymentParameters
                    {
                        DeploymentSlot     = DeploymentSlot.Production,
                        Name               = this.DeploymentName ?? this.ServiceName,
                        Label              = this.DeploymentLabel ?? this.ServiceName,
                        VirtualNetworkName = this.VNetName,
                        Roles              = { persistentVMs[0] }
                    };

                    if (this.DnsSettings != null)
                    {
                        parameters.DnsSettings = new Management.Compute.Models.DnsSettings();

                        foreach (var dns in this.DnsSettings)
                        {
                            parameters.DnsSettings.DnsServers.Add(new Microsoft.WindowsAzure.Management.Compute.Models.DnsServer()
                            {
                                Name = dns.Name, Address = dns.Address
                            });
                        }
                    }

                    var operationDescription = string.Format(Resources.AzureVMCommandCreateDeploymentWithVM, CommandRuntime, persistentVMs[0].RoleName);
                    ExecuteClientActionNewSM(
                        parameters,
                        operationDescription,
                        () => this.ComputeClient.VirtualMachines.CreateDeployment(this.ServiceName, parameters));

                    if (this.WaitForBoot.IsPresent)
                    {
                        WaitForRoleToBoot(persistentVMs[0].RoleName);
                    }
                }
                catch (CloudException ex)
                {
                    if (ex.Response.StatusCode == HttpStatusCode.NotFound)
                    {
                        throw new Exception(Resources.ServiceDoesNotExistSpecifyLocationOrAffinityGroup);
                    }
                    else
                    {
                        this.WriteExceptionDetails(ex);
                    }
                    return;
                }

                this.createdDeployment = true;
            }
            else
            {
                if (this.VNetName != null || this.DnsSettings != null || !string.IsNullOrEmpty(this.DeploymentLabel) || !string.IsNullOrEmpty(this.DeploymentName))
                {
                    WriteWarning(Resources.VNetNameDnsSettingsDeploymentLabelDeploymentNameCanBeSpecifiedOnNewDeployments);
                }
            }

            if (this.createdDeployment == false && CurrentDeploymentNewSM != null)
            {
                this.DeploymentName = CurrentDeploymentNewSM.Name;
            }

            int startingVM = this.createdDeployment ? 1 : 0;

            for (int i = startingVM; i < persistentVMs.Count; i++)
            {
                var operationDescription = string.Format(Resources.AzureVMCommandCreateVM, CommandRuntime, persistentVMs[i].RoleName);

                var parameter = new VirtualMachineCreateParameters
                {
                    AvailabilitySetName = persistentVMs[i].AvailabilitySetName,
                    OSVirtualHardDisk   = persistentVMs[i].OSVirtualHardDisk,
                    RoleName            = persistentVMs[i].RoleName,
                    RoleSize            = persistentVMs[i].RoleSize
                };

                persistentVMs[i].DataVirtualHardDisks.ForEach(c => parameter.DataVirtualHardDisks.Add(c));
                persistentVMs[i].ConfigurationSets.ForEach(c => parameter.ConfigurationSets.Add(c));

                ExecuteClientActionNewSM(
                    persistentVMs[i],
                    operationDescription,
                    () => this.ComputeClient.VirtualMachines.Create(this.ServiceName, this.DeploymentName ?? this.ServiceName, parameter));
            }

            if (this.WaitForBoot.IsPresent)
            {
                for (int i = startingVM; i < persistentVMs.Count; i++)
                {
                    WaitForRoleToBoot(persistentVMs[i].RoleName);
                }
            }
        }
コード例 #8
0
        public void NewAzureVMProcess()
        {
            WindowsAzureSubscription currentSubscription = CurrentSubscription;
            CloudStorageAccount currentStorage = null;
            try
            {
                currentStorage = currentSubscription.GetCloudStorageAccount();
            }
            catch (Exception ex) // couldn't access
            {
                throw new ArgumentException(Resources.CurrentStorageAccountIsNotAccessible, ex);
            }
            if (currentStorage == null) // not set
            {
                throw new ArgumentException(Resources.CurrentStorageAccountIsNotSet);
            }

            bool serviceExists = DoesCloudServiceExist(this.ServiceName);

            if(!string.IsNullOrEmpty(this.Location))
            {
                if(serviceExists)
                {
                    throw new ApplicationException(Resources.ServiceExistsLocationCanNotBeSpecified);
                }
            }

            if (!string.IsNullOrEmpty(this.AffinityGroup))
            {
                if (serviceExists)
                {
                    throw new ApplicationException(Resources.ServiceExistsAffinityGroupCanNotBeSpecified);
                }
            }

            if (!serviceExists)
            {
                try
                {
                    //Implicitly created hosted service2012-05-07 23:12 

                    // Create the Cloud Service when
                    // Location or Affinity Group is Specified
                    // or VNET is specified and the service doesn't exist
                    var parameter = new HostedServiceCreateParameters
                    {
                        AffinityGroup = this.AffinityGroup,
                        Location = this.Location,
                        ServiceName = this.ServiceName,
                        Description = String.Format("Implicitly created hosted service{0}", DateTime.Now.ToUniversalTime().ToString("yyyy-MM-dd HH:mm")),
                        Label = this.ServiceName
                    };
                    ExecuteClientActionNewSM(
                        parameter,
                        CommandRuntime + Resources.QuickVMCreateCloudService,
                        () => this.ComputeClient.HostedServices.Create(parameter));

                }

                catch (CloudException ex)
                {
                    this.WriteExceptionDetails(ex);
                    return;
                }
            }

            if (ParameterSetName.Equals("Windows", StringComparison.OrdinalIgnoreCase))
            {
                if (WinRMCertificate != null)
                {
                    if (!CertUtilsNewSM.HasExportablePrivateKey(WinRMCertificate))
                    {
                        throw new ArgumentException(Resources.WinRMCertificateDoesNotHaveExportablePrivateKey);
                    }
                    var operationDescription = string.Format(Resources.QuickVMUploadingWinRMCertificate, CommandRuntime, WinRMCertificate.Thumbprint);
                    var parameters = CertUtilsNewSM.Create(WinRMCertificate);
                    ExecuteClientActionNewSM(
                        null,
                        operationDescription,
                        () => this.ComputeClient.ServiceCertificates.Create(this.ServiceName, parameters),
                        (s, r) => ContextFactory<ComputeOperationStatusResponse, ManagementOperationContext>(r, s));
                }

                if (X509Certificates != null)
                {
                    var certificateFilesWithThumbprint = from c in X509Certificates
                                                         select new
                                                         {
                                                             c.Thumbprint,
                                                             CertificateFile = CertUtilsNewSM.Create(c, this.NoExportPrivateKey.IsPresent)
                                                         };
                    foreach (var current in certificateFilesWithThumbprint.ToList())
                    {
                        var operationDescription = string.Format(Resources.QuickVMUploadingCertificate, CommandRuntime, current.Thumbprint);
                        ExecuteClientActionNewSM(
                            null,
                            operationDescription,
                            () => this.ComputeClient.ServiceCertificates.Create(this.ServiceName, current.CertificateFile),
                            (s, r) => ContextFactory<ComputeOperationStatusResponse, ManagementOperationContext>(r, s));
                    }
                }
            }

            var vm = CreatePersistenVMRole(currentStorage);

            // If the current deployment doesn't exist set it create it
            if (CurrentDeploymentNewSM == null)
            {
                try
                {
                    var parameters = new VirtualMachineCreateDeploymentParameters
                    {
                        DeploymentSlot = DeploymentSlot.Production,
                        Name = this.ServiceName,
                        Label = this.ServiceName,
                        VirtualNetworkName = this.VNetName,
                        Roles = {vm}
                    };

                    if (this.DnsSettings != null)
                    {
                        parameters.DnsSettings = new Management.Compute.Models.DnsSettings();

                        foreach (var dns in this.DnsSettings)
                        {
                            parameters.DnsSettings.DnsServers.Add(new Microsoft.WindowsAzure.Management.Compute.Models.DnsServer() { Name = dns.Name, Address = dns.Address });
                        }
                    }

                    var operationDescription = string.Format(Resources.QuickVMCreateDeploymentWithVM, CommandRuntime, vm.RoleName);
                    ExecuteClientActionNewSM(
                        parameters,
                        operationDescription,
                        () => this.ComputeClient.VirtualMachines.CreateDeployment(this.ServiceName, parameters));
                        
                    if (WaitForBoot.IsPresent)
                    {
                        WaitForRoleToBoot(vm.RoleName);
                    }
                }
                catch (CloudException ex)
                {
                    if (ex.Response.StatusCode == HttpStatusCode.NotFound)
                    {
                        throw new Exception(Resources.ServiceDoesNotExistSpecifyLocationOrAffinityGroup);
                    }
                    this.WriteExceptionDetails(ex);
                    return;
                }

                _createdDeployment = true;
            }
            else
            {
                if (VNetName != null || DnsSettings != null)
                {
                    WriteWarning(Resources.VNetNameOrDnsSettingsCanOnlyBeSpecifiedOnNewDeployments);
                }
            }


            // Only create the VM when a new VM was added and it was not created during the deployment phase.
            if ((_createdDeployment == false))
            {
                try
                {
                    var operationDescription = string.Format(Resources.QuickVMCreateVM, CommandRuntime, vm.RoleName);

                    var parameter = new VirtualMachineCreateParameters
                    {
                        AvailabilitySetName = vm.AvailabilitySetName,
                        OSVirtualHardDisk = Mapper.Map(vm.OSVirtualHardDisk, new Management.Compute.Models.OSVirtualHardDisk()),
                        RoleName = vm.RoleName,
                        RoleSize = vm.RoleSize,
                    };

                    vm.DataVirtualHardDisks.ForEach(c => parameter.DataVirtualHardDisks.Add(c));
                    vm.ConfigurationSets.ForEach(c => parameter.ConfigurationSets.Add(c));

                    ExecuteClientActionNewSM(
                        vm,
                        operationDescription,
                        () => this.ComputeClient.VirtualMachines.Create(this.ServiceName, this.ServiceName, parameter));

                    if(WaitForBoot.IsPresent)
                    {
                        WaitForRoleToBoot(vm.RoleName);
                    }
                }
                catch (CloudException ex)
                {
                    this.WriteExceptionDetails(ex);
                    return;
                }
            }
        }
コード例 #9
0
        /// <summary>
        /// Create the Virtual Machine
        /// </summary>
        /// <param name="imageName">The OS image name to use</param>
        /// <returns></returns>
        internal async Task CreateVirtualMachine(string imageName)
        {
            // Get the details of the selected OS image
            var image = await _computeManagementClient.VirtualMachineOSImages.GetAsync(imageName);

            // The Deployment where the Virtual Machine will be hosted
            var parameters = new VirtualMachineCreateDeploymentParameters
            {
                DeploymentSlot = DeploymentSlot.Production,
                Name           = _parameters.CloudServiceName,
                Label          = String.Format("CloudService{0}", _parameters.CloudServiceName),
            };

            // The Role defines the details of the VM parameters
            parameters.Roles.Add(new Role
            {
                OSVirtualHardDisk = new OSVirtualHardDisk
                {
                    HostCaching = VirtualHardDiskHostCaching.ReadWrite,
                    MediaLink   = new Uri(string.Format("https://{0}.blob.core.windows.net/vhds/{1}",
                                                        _parameters.StorageAccountName, _parameters.VMName)),
                    SourceImageName = image.Name
                },
                // You could use DataVirtualHardDisks here to add additional persistent data disks
                RoleName            = _parameters.VMName,
                RoleType            = VirtualMachineRoleType.PersistentVMRole.ToString(),
                RoleSize            = VirtualMachineRoleSize.Small,
                ProvisionGuestAgent = true
            });

            // Add a ConfigurationSet for the Windows specific configuration
            parameters.Roles[0].ConfigurationSets.Add(new ConfigurationSet
            {
                ConfigurationSetType   = ConfigurationSetTypes.WindowsProvisioningConfiguration,
                ComputerName           = _parameters.VMName, // TODO: HostName for Linux
                AdminUserName          = _parameters.AdminUsername,
                AdminPassword          = _parameters.AdminPassword,
                EnableAutomaticUpdates = false,
                TimeZone = "Pacific Standard Time"
            });

            // Add a ConfigurationSet describing the ports to open to the outside
            parameters.Roles[0].ConfigurationSets.Add(new ConfigurationSet
            {
                ConfigurationSetType = ConfigurationSetTypes.NetworkConfiguration,
                InputEndpoints       = new List <InputEndpoint>()
                {
                    // Open the RDP port using a non-standard external port
                    new InputEndpoint()
                    {
                        Name      = "RDP",
                        Protocol  = InputEndpointTransportProtocol.Tcp,
                        LocalPort = 3389,
                        Port      = _parameters.RDPPort
                    }
                }
            });

            // Create the Virtual Machine
            var response = await _computeManagementClient.VirtualMachines.CreateDeploymentAsync(_parameters.CloudServiceName, parameters);
        }
コード例 #10
0
        public void DNSServerOperationsTest()
        {
            TestUtilities.StartTest();
            using (fixture.ComputeClient = fixture.GetComputeManagementClient())
            {
                var serviceName = TestUtilities.GenerateName();
                var result      = fixture.ComputeClient.HostedServices.Create(new HostedServiceCreateParameters
                {
                    Location    = fixture.Location,
                    Label       = serviceName,
                    ServiceName = serviceName
                });

                // assert that the call worked
                Assert.Equal(result.StatusCode, HttpStatusCode.Created);
                // Create the deployment with a VM
                VirtualMachineCreateDeploymentParameters parameters = CreateVMParameters(FindVMImage("Ubuntu Server 14"), serviceName);

                string customdataBase64 = Convert.ToBase64String(File.ReadAllBytes(@"SampleService\CustomData.sh"));

                parameters.Roles[0].ConfigurationSets.Add(new ConfigurationSet
                {
                    UserName                         = "******",
                    UserPassword                     = "******",
                    ConfigurationSetType             = ConfigurationSetTypes.LinuxProvisioningConfiguration,
                    ComputerName                     = serviceName,
                    HostName                         = string.Format("{0}.cloudapp.net", serviceName),
                    EnableAutomaticUpdates           = false,
                    TimeZone                         = "Pacific Standard Time",
                    CustomData                       = customdataBase64,
                    DisableSshPasswordAuthentication = false
                });

                parameters.Roles[0].ConfigurationSets.Add(new ConfigurationSet
                {
                    ConfigurationSetType = ConfigurationSetTypes.NetworkConfiguration,
                    InputEndpoints       = new List <InputEndpoint>
                    {
                        new InputEndpoint()
                        {
                            LocalPort = 22,
                            Name      = "SSH",
                            Port      = 52222,
                            Protocol  = InputEndpointTransportProtocol.Tcp
                        }
                    }
                });

                OperationStatusResponse opResp =
                    fixture.ComputeClient.VirtualMachines.CreateDeployment(serviceName, parameters);
                Assert.Equal(opResp.Status, OperationStatus.Succeeded);

                // Verify that there are no DNS servers present
                var deploymentResponse = fixture.ComputeClient.Deployments.GetByName(serviceName,
                                                                                     parameters.Name);
                Assert.Null(deploymentResponse.DnsSettings);

                const string dnsServerName    = "DnsServer";
                const string dnsServerAddress = "10.1.1.4";
                // Add a DNS server
                fixture.ComputeClient.DnsServer.AddDNSServer(serviceName,
                                                             parameters.Name,
                                                             new DNSAddParameters
                {
                    Address = dnsServerAddress,
                    Name    = dnsServerName
                });

                // Get the DNS server added above
                deploymentResponse = fixture.ComputeClient.Deployments.GetByName(serviceName,
                                                                                 parameters.Name);

                Assert.NotNull(deploymentResponse.DnsSettings);
                Assert.Equal(1, deploymentResponse.DnsSettings.DnsServers.Count());

                Assert.Equal(dnsServerName, deploymentResponse.DnsSettings.DnsServers.First().Name);
                Assert.Equal(dnsServerAddress, deploymentResponse.DnsSettings.DnsServers.First().Address);

                // Update the DNS server
                fixture.ComputeClient.DnsServer.UpdateDNSServer(serviceName,
                                                                parameters.Name,
                                                                dnsServerName,
                                                                new DNSUpdateParameters
                {
                    Address = "10.1.1.6",
                    Name    = dnsServerName
                });

                // Get the updated DNS server
                deploymentResponse = fixture.ComputeClient.Deployments.GetByName(serviceName,
                                                                                 parameters.Name);

                Assert.NotNull(deploymentResponse.DnsSettings);
                Assert.Equal(1, deploymentResponse.DnsSettings.DnsServers.Count());

                Assert.Equal(dnsServerName, deploymentResponse.DnsSettings.DnsServers.First().Name);
                Assert.Equal("10.1.1.6", deploymentResponse.DnsSettings.DnsServers.First().Address);

                // Delete the DNS server
                fixture.ComputeClient.DnsServer.DeleteDNSServer(serviceName,
                                                                parameters.Name,
                                                                dnsServerName);

                // Verify the Delete op
                deploymentResponse = fixture.ComputeClient.Deployments.GetByName(serviceName,
                                                                                 parameters.Name);
                Assert.Null(deploymentResponse.DnsSettings);
            }

            TestUtilities.EndTest();
        }
コード例 #11
0
        public void CanCreateVMWithPublicIPDnsName()
        {
            const string loadBalancerDistribution = "sourceIP";

            TestUtilities.StartTest();
            string dnsName = TestUtilities.GenerateName();

            using (fixture.ComputeClient = fixture.GetComputeManagementClient())
            {
                var serviceName = TestUtilities.GenerateName();
                var result      = fixture.ComputeClient.HostedServices.Create(new HostedServiceCreateParameters
                {
                    Location    = fixture.Location,
                    Label       = serviceName,
                    ServiceName = serviceName
                });

                // assert that the call worked
                Assert.Equal(result.StatusCode, HttpStatusCode.Created);
                VirtualMachineCreateDeploymentParameters parameters = CreateVMParameters(FindVMImage("Ubuntu Server 14"), serviceName);

                string customdataBase64 = Convert.ToBase64String(File.ReadAllBytes(@"SampleService\CustomData.sh"));

                parameters.Roles[0].ConfigurationSets.Add(new ConfigurationSet
                {
                    UserName                         = "******",
                    UserPassword                     = "******",
                    ConfigurationSetType             = ConfigurationSetTypes.LinuxProvisioningConfiguration,
                    ComputerName                     = serviceName,
                    HostName                         = string.Format("{0}.cloudapp.net", serviceName),
                    EnableAutomaticUpdates           = false,
                    TimeZone                         = "Pacific Standard Time",
                    CustomData                       = customdataBase64,
                    DisableSshPasswordAuthentication = false
                });

                parameters.Roles[0].ConfigurationSets.Add(new ConfigurationSet
                {
                    ConfigurationSetType = ConfigurationSetTypes.NetworkConfiguration,
                    InputEndpoints       = new List <InputEndpoint>
                    {
                        new InputEndpoint()
                        {
                            LocalPort = 22,
                            Name      = "SSH",
                            Port      = 52222,
                            Protocol  = InputEndpointTransportProtocol.Tcp,
                            LoadBalancerDistribution = loadBalancerDistribution
                        }
                    },
                    PublicIPs = new List <ConfigurationSet.PublicIP>()
                    {
                        new ConfigurationSet.PublicIP()
                        {
                            Name            = "publicip1",
                            DomainNameLabel = dnsName,
                        }
                    }
                });

                OperationStatusResponse opResp =
                    fixture.ComputeClient.VirtualMachines.CreateDeployment(serviceName, parameters);

                Assert.Equal(opResp.Status, OperationStatus.Succeeded);

                #region IdleTimeoutVerifications
                var deploymentResponse = fixture.ComputeClient.Deployments.GetByName(serviceName,
                                                                                     parameters.Name);

                var configrationSet = deploymentResponse.Roles.First().ConfigurationSets.First();

                // Verify the dns name for PublicIP
                Assert.Equal("publicip1", configrationSet.PublicIPs.First().Name);
                Assert.Equal(dnsName, configrationSet.PublicIPs.First().DomainNameLabel);

                var instanceRole = deploymentResponse.RoleInstances.First();

                Assert.Equal("publicip1", instanceRole.PublicIPs.First().Name);
                Assert.Equal(dnsName, instanceRole.PublicIPs.First().DomainNameLabel);

                Assert.Equal(string.Format("{0}.{1}.cloudapp.net", dnsName, serviceName), instanceRole.PublicIPs.First().Fqdns[0]);
                Assert.Equal(string.Format("{0}.0.{1}.cloudapp.net", dnsName, serviceName), instanceRole.PublicIPs.First().Fqdns[1]);
                #endregion
            }

            TestUtilities.EndTest();
        }
コード例 #12
0
        public void NewAzureVMProcess()
        {
            WindowsAzureSubscription currentSubscription = CurrentSubscription;
            CloudStorageAccount currentStorage = null;
            try
            {
                currentStorage = currentSubscription.GetCloudStorageAccount();
            }
            catch (Exception ex) // couldn't access
            {
                throw new ArgumentException(Resources.CurrentStorageAccountIsNotAccessible, ex);
            }
            if (currentStorage == null) // not set
            {
                throw new ArgumentException(Resources.CurrentStorageAccountIsNotSet);
            }

            try
            {
                if (this.ParameterSetName.Equals("CreateService", StringComparison.OrdinalIgnoreCase))
                {
                    var parameter = new HostedServiceCreateParameters
                    {
                        AffinityGroup = this.AffinityGroup,
                        Location = this.Location,
                        ServiceName = this.ServiceName,
                        Description = this.ServiceDescription ??
                                        String.Format("Implicitly created hosted service{0}",DateTime.Now.ToUniversalTime().ToString("yyyy-MM-dd HH:mm")),
                        Label = this.ServiceLabel ?? this.ServiceName
                    };
                    ExecuteClientActionNewSM(
                        parameter,
                        CommandRuntime + " - Create Cloud Service",
                        () => this.ComputeClient.HostedServices.Create(parameter));
                }
            }
            catch (CloudException ex)
            {
                this.WriteExceptionDetails(ex);
                return;
            }

            foreach (var vm in from v in VMs let configuration = v.ConfigurationSets.OfType<Model.PersistentVMModel.WindowsProvisioningConfigurationSet>().FirstOrDefault() where configuration != null select v)
            {
                if (vm.WinRMCertificate != null)
                {
                    if(!CertUtilsNewSM.HasExportablePrivateKey(vm.WinRMCertificate))
                    {
                        throw new ArgumentException(Resources.WinRMCertificateDoesNotHaveExportablePrivateKey);
                    }
                    var operationDescription = string.Format(Resources.AzureVMUploadingWinRMCertificate, CommandRuntime, vm.WinRMCertificate.Thumbprint);
                    var parameters = CertUtilsNewSM.Create(vm.WinRMCertificate);
                    ExecuteClientActionNewSM(
                        null,
                        operationDescription,
                        () => this.ComputeClient.ServiceCertificates.Create(this.ServiceName, parameters),
                        (s, r) => ContextFactory<ComputeOperationStatusResponse, ManagementOperationContext>(r, s));

                }
                var certificateFilesWithThumbprint = from c in vm.X509Certificates
                    select new
                           {
                               c.Thumbprint,
                               CertificateFile = CertUtilsNewSM.Create(c, vm.NoExportPrivateKey)
                           };
                foreach (var current in certificateFilesWithThumbprint.ToList())
                {
                    var operationDescription = string.Format(Resources.AzureVMCommandUploadingCertificate, CommandRuntime, current.Thumbprint);
                    ExecuteClientActionNewSM(
                        null,
                        operationDescription,
                        () => this.ComputeClient.ServiceCertificates.Create(this.ServiceName, current.CertificateFile),
                        (s, r) => ContextFactory<ComputeOperationStatusResponse, ManagementOperationContext>(r, s));
                }
            }

            var persistentVMs = this.VMs.Select(vm => CreatePersistentVMRole(vm, currentStorage)).ToList();

            // If the current deployment doesn't exist set it create it
            if (CurrentDeploymentNewSM == null)
            {
                try
                {
                    var parameters = new VirtualMachineCreateDeploymentParameters
                    {
                        DeploymentSlot = DeploymentSlot.Production,
                        Name = this.DeploymentName ?? this.ServiceName,
                        Label = this.DeploymentLabel ?? this.ServiceName,
                        VirtualNetworkName = this.VNetName,
                        Roles = { persistentVMs[0] }
                    };

                    if (this.DnsSettings != null)
                    {
                        parameters.DnsSettings = new Management.Compute.Models.DnsSettings();

                        foreach (var dns in this.DnsSettings)
                        {
                            parameters.DnsSettings.DnsServers.Add(new Microsoft.WindowsAzure.Management.Compute.Models.DnsServer() { Name = dns.Name, Address = dns.Address });
                        }
                    }

                    var operationDescription = string.Format(Resources.AzureVMCommandCreateDeploymentWithVM, CommandRuntime, persistentVMs[0].RoleName);
                    ExecuteClientActionNewSM(
                        parameters,
                        operationDescription,
                        () => this.ComputeClient.VirtualMachines.CreateDeployment(this.ServiceName, parameters));

                    if(this.WaitForBoot.IsPresent)
                    {
                        WaitForRoleToBoot(persistentVMs[0].RoleName);
                    }
                }
                catch (CloudException ex)
                {
                    if (ex.Response.StatusCode == HttpStatusCode.NotFound)
                    {
                        throw new Exception(Resources.ServiceDoesNotExistSpecifyLocationOrAffinityGroup);
                    }
                    else
                    {
                        this.WriteExceptionDetails(ex);
                    }
                    return;
                }

                this.createdDeployment = true;
            }
            else
            {
                if (this.VNetName != null || this.DnsSettings != null || !string.IsNullOrEmpty(this.DeploymentLabel) || !string.IsNullOrEmpty(this.DeploymentName))
                {
                    WriteWarning(Resources.VNetNameDnsSettingsDeploymentLabelDeploymentNameCanBeSpecifiedOnNewDeployments);
                }
            }

            if (this.createdDeployment == false && CurrentDeploymentNewSM != null)
            {
                this.DeploymentName = CurrentDeploymentNewSM.Name;
            }

            int startingVM = this.createdDeployment ? 1 : 0;

            for (int i = startingVM; i < persistentVMs.Count; i++)
            {
                var operationDescription = string.Format(Resources.AzureVMCommandCreateVM, CommandRuntime, persistentVMs[i].RoleName);
                
                var parameter = new VirtualMachineCreateParameters
                {
                    AvailabilitySetName = persistentVMs[i].AvailabilitySetName,
                    OSVirtualHardDisk = persistentVMs[i].OSVirtualHardDisk,
                    RoleName = persistentVMs[i].RoleName,
                    RoleSize = persistentVMs[i].RoleSize
                };

                persistentVMs[i].DataVirtualHardDisks.ForEach(c => parameter.DataVirtualHardDisks.Add(c));
                persistentVMs[i].ConfigurationSets.ForEach(c => parameter.ConfigurationSets.Add(c));

                ExecuteClientActionNewSM(
                    persistentVMs[i],
                    operationDescription,
                    () => this.ComputeClient.VirtualMachines.Create(this.ServiceName, this.DeploymentName ?? this.ServiceName, parameter));
            }

            if(this.WaitForBoot.IsPresent)
            {
                for (int i = startingVM; i < persistentVMs.Count; i++)
                {
                    WaitForRoleToBoot(persistentVMs[i].RoleName);
                }
            }
        }
コード例 #13
0
ファイル: NewAzureVM.cs プロジェクト: vreddi/azure-powershell
        public void NewAzureVMProcess()
        {
            AzureSubscription   currentSubscription = Profile.Context.Subscription;
            CloudStorageAccount currentStorage      = null;

            try
            {
                currentStorage = currentSubscription.GetCloudStorageAccount(Profile);
            }
            catch (Exception ex) // couldn't access
            {
                throw new ArgumentException(Resources.CurrentStorageAccountIsNotAccessible, ex);
            }

            if (currentStorage == null) // not set
            {
                throw new ArgumentException(Resources.CurrentStorageAccountIsNotSet);
            }

            if (this.ParameterSetName.Equals("CreateService", StringComparison.OrdinalIgnoreCase))
            {
                var parameter = new HostedServiceCreateParameters
                {
                    AffinityGroup = this.AffinityGroup,
                    Location      = this.Location,
                    ServiceName   = this.ServiceName,
                    Description   = this.ServiceDescription ?? String.Format(
                        "Implicitly created hosted service{0}",
                        DateTime.Now.ToUniversalTime().ToString("yyyy-MM-dd HH:mm")),
                    Label          = this.ServiceLabel ?? this.ServiceName,
                    ReverseDnsFqdn = this.ReverseDnsFqdn
                };

                try
                {
                    this.ComputeClient.HostedServices.Create(parameter);
                }
                catch (CloudException ex)
                {
                    if (string.Equals(ex.Error.Code, "ConflictError"))
                    {
                        HostedServiceGetResponse existingService = this.ComputeClient.HostedServices.Get(this.ServiceName);

                        if (existingService == null || existingService.Properties == null)
                        {
                            // The same service name is already used by another subscription.
                            WriteExceptionError(ex);
                            return;
                        }
                        else if ((string.IsNullOrEmpty(existingService.Properties.Location) &&
                                  string.Compare(existingService.Properties.AffinityGroup, this.AffinityGroup, StringComparison.InvariantCultureIgnoreCase) == 0) ||
                                 (string.IsNullOrEmpty(existingService.Properties.AffinityGroup) &&
                                  string.Compare(existingService.Properties.Location, this.Location, StringComparison.InvariantCultureIgnoreCase) == 0))
                        {
                            // The same service name is already created under the same subscription,
                            // and its affinity group or location is matched with the given parameter.
                            this.WriteWarning(ex.Error.Message);
                        }
                        else
                        {
                            // The same service name is already created under the same subscription,
                            // but its affinity group or location is not matched with the given parameter.
                            this.WriteWarning("Location or AffinityGroup name is not matched with the existing service");
                            WriteExceptionError(ex);
                            return;
                        }
                    }
                    else
                    {
                        WriteExceptionError(ex);
                        return;
                    }
                }
            }

            foreach (var vm in from v in VMs let configuration = v.ConfigurationSets.OfType <Model.WindowsProvisioningConfigurationSet>().FirstOrDefault() where configuration != null select v)
            {
                if (vm.WinRMCertificate != null)
                {
                    if (!CertUtilsNewSM.HasExportablePrivateKey(vm.WinRMCertificate))
                    {
                        throw new ArgumentException(Resources.WinRMCertificateDoesNotHaveExportablePrivateKey);
                    }

                    var operationDescription = string.Format(Resources.AzureVMUploadingWinRMCertificate, CommandRuntime, vm.WinRMCertificate.Thumbprint);
                    var parameters           = CertUtilsNewSM.Create(vm.WinRMCertificate);

                    ExecuteClientActionNewSM(
                        null,
                        operationDescription,
                        () => this.ComputeClient.ServiceCertificates.Create(this.ServiceName, parameters),
                        (s, r) => ContextFactory <OperationStatusResponse, ManagementOperationContext>(r, s));
                }

                var certificateFilesWithThumbprint = from c in vm.X509Certificates
                                                     select new
                {
                    c.Thumbprint,
                    CertificateFile = CertUtilsNewSM.Create(c, vm.NoExportPrivateKey)
                };

                foreach (var current in certificateFilesWithThumbprint.ToList())
                {
                    var operationDescription = string.Format(Resources.AzureVMCommandUploadingCertificate, CommandRuntime, current.Thumbprint);
                    ExecuteClientActionNewSM(
                        null,
                        operationDescription,
                        () => this.ComputeClient.ServiceCertificates.Create(this.ServiceName, current.CertificateFile),
                        (s, r) => ContextFactory <OperationStatusResponse, ManagementOperationContext>(r, s));
                }
            }

            var persistentVMs = this.VMs.Select((vm, index) => CreatePersistentVMRole(VMTuples[index], currentStorage)).ToList();

            // If the current deployment doesn't exist set it create it
            if (CurrentDeploymentNewSM == null)
            {
                try
                {
                    var parameters = new VirtualMachineCreateDeploymentParameters
                    {
                        DeploymentSlot     = DeploymentSlot.Production,
                        Name               = this.DeploymentName ?? this.ServiceName,
                        Label              = this.DeploymentLabel ?? this.ServiceName,
                        VirtualNetworkName = this.VNetName,
                        Roles              = { persistentVMs[0] },
                        ReservedIPName     = ReservedIPName
                    };

                    if (this.DnsSettings != null)
                    {
                        parameters.DnsSettings = new Management.Compute.Models.DnsSettings();

                        foreach (var dns in this.DnsSettings)
                        {
                            parameters.DnsSettings.DnsServers.Add(
                                new Microsoft.WindowsAzure.Management.Compute.Models.DnsServer
                            {
                                Name    = dns.Name,
                                Address = dns.Address
                            });
                        }
                    }

                    if (this.InternalLoadBalancerConfig != null)
                    {
                        parameters.LoadBalancers = new LoadBalancer[1]
                        {
                            new LoadBalancer
                            {
                                Name = this.InternalLoadBalancerConfig.InternalLoadBalancerName,
                                FrontendIPConfiguration = new FrontendIPConfiguration
                                {
                                    Type       = FrontendIPConfigurationType.Private,
                                    SubnetName = this.InternalLoadBalancerConfig.SubnetName,
                                    StaticVirtualNetworkIPAddress = this.InternalLoadBalancerConfig.IPAddress
                                }
                            }
                        };
                    }

                    var operationDescription = string.Format(Resources.AzureVMCommandCreateDeploymentWithVM, CommandRuntime, persistentVMs[0].RoleName);
                    ExecuteClientActionNewSM(
                        parameters,
                        operationDescription,
                        () => this.ComputeClient.VirtualMachines.CreateDeployment(this.ServiceName, parameters));

                    if (this.WaitForBoot.IsPresent)
                    {
                        WaitForRoleToBoot(persistentVMs[0].RoleName);
                    }
                }
                catch (CloudException ex)
                {
                    if (ex.Response.StatusCode == HttpStatusCode.NotFound)
                    {
                        throw new Exception(Resources.ServiceDoesNotExistSpecifyLocationOrAffinityGroup);
                    }
                    else
                    {
                        WriteExceptionError(ex);
                    }

                    return;
                }

                this.createdDeployment = true;
            }
            else
            {
                if (this.VNetName != null || this.DnsSettings != null || !string.IsNullOrEmpty(this.DeploymentLabel) || !string.IsNullOrEmpty(this.DeploymentName))
                {
                    WriteWarning(Resources.VNetNameDnsSettingsDeploymentLabelDeploymentNameCanBeSpecifiedOnNewDeployments);
                }
            }

            if (this.createdDeployment == false && CurrentDeploymentNewSM != null)
            {
                this.DeploymentName = CurrentDeploymentNewSM.Name;
            }

            int startingVM = this.createdDeployment ? 1 : 0;

            for (int i = startingVM; i < persistentVMs.Count; i++)
            {
                var operationDescription = string.Format(Resources.AzureVMCommandCreateVM, CommandRuntime, persistentVMs[i].RoleName);

                var parameter = new VirtualMachineCreateParameters
                {
                    AvailabilitySetName         = persistentVMs[i].AvailabilitySetName,
                    OSVirtualHardDisk           = VMTuples[i].Item3 ? null : persistentVMs[i].OSVirtualHardDisk,
                    RoleName                    = persistentVMs[i].RoleName,
                    RoleSize                    = persistentVMs[i].RoleSize,
                    ProvisionGuestAgent         = persistentVMs[i].ProvisionGuestAgent,
                    ResourceExtensionReferences = persistentVMs[i].ProvisionGuestAgent != null && persistentVMs[i].ProvisionGuestAgent.Value ? persistentVMs[i].ResourceExtensionReferences : null,
                    VMImageName                 = VMTuples[i].Item3 ? persistentVMs[i].VMImageName : null,
                    MediaLocation               = VMTuples[i].Item3 ? persistentVMs[i].MediaLocation : null
                };

                if (parameter.OSVirtualHardDisk != null)
                {
                    parameter.OSVirtualHardDisk.IOType = null;
                }

                if (persistentVMs[i].DataVirtualHardDisks != null && persistentVMs[i].DataVirtualHardDisks.Any())
                {
                    persistentVMs[i].DataVirtualHardDisks.ForEach(c => parameter.DataVirtualHardDisks.Add(c));
                    parameter.DataVirtualHardDisks.ForEach(d => d.IOType = null);
                }

                persistentVMs[i].ConfigurationSets.ForEach(c => parameter.ConfigurationSets.Add(c));

                ExecuteClientActionNewSM(
                    persistentVMs[i],
                    operationDescription,
                    () => this.ComputeClient.VirtualMachines.Create(this.ServiceName, this.DeploymentName ?? this.ServiceName, parameter));
            }

            if (this.WaitForBoot.IsPresent)
            {
                for (int i = startingVM; i < persistentVMs.Count; i++)
                {
                    WaitForRoleToBoot(persistentVMs[i].RoleName);
                }
            }
        }
コード例 #14
0
        public void NewAzureVMProcess()
        {
            AzureSubscription   currentSubscription = Profile.Context.Subscription;
            CloudStorageAccount currentStorage      = null;

            try
            {
                currentStorage = currentSubscription.GetCloudStorageAccount(Profile);
            }
            catch (Exception ex) // couldn't access
            {
                throw new ArgumentException(Resources.CurrentStorageAccountIsNotAccessible, ex);
            }
            if (currentStorage == null) // not set
            {
                throw new ArgumentException(Resources.CurrentStorageAccountIsNotSet);
            }

            bool serviceExists = DoesCloudServiceExist(this.ServiceName);

            if (!string.IsNullOrEmpty(this.Location))
            {
                if (serviceExists)
                {
                    throw new ApplicationException(Resources.ServiceExistsLocationCanNotBeSpecified);
                }
            }

            if (!string.IsNullOrEmpty(this.AffinityGroup))
            {
                if (serviceExists)
                {
                    throw new ApplicationException(Resources.ServiceExistsAffinityGroupCanNotBeSpecified);
                }
            }

            if (!string.IsNullOrEmpty(this.ReverseDnsFqdn))
            {
                if (serviceExists)
                {
                    throw new ApplicationException(Resources.ServiceExistsReverseDnsFqdnCanNotBeSpecified);
                }
            }

            if (!serviceExists)
            {
                try
                {
                    //Implicitly created hosted service2012-05-07 23:12

                    // Create the Cloud Service when
                    // Location or Affinity Group is Specified
                    // or VNET is specified and the service doesn't exist
                    var parameter = new HostedServiceCreateParameters
                    {
                        AffinityGroup  = this.AffinityGroup,
                        Location       = this.Location,
                        ServiceName    = this.ServiceName,
                        Description    = String.Format("Implicitly created hosted service{0}", DateTime.Now.ToUniversalTime().ToString("yyyy-MM-dd HH:mm")),
                        Label          = this.ServiceName,
                        ReverseDnsFqdn = this.ReverseDnsFqdn
                    };

                    ExecuteClientActionNewSM(
                        parameter,
                        CommandRuntime + Resources.QuickVMCreateCloudService,
                        () => this.ComputeClient.HostedServices.Create(parameter));
                }
                catch (CloudException ex)
                {
                    WriteExceptionError(ex);
                    return;
                }
            }

            if (ParameterSetName.Equals(WindowsParamSet, StringComparison.OrdinalIgnoreCase))
            {
                if (WinRMCertificate != null)
                {
                    if (!CertUtilsNewSM.HasExportablePrivateKey(WinRMCertificate))
                    {
                        throw new ArgumentException(Resources.WinRMCertificateDoesNotHaveExportablePrivateKey);
                    }

                    var operationDescription = string.Format(Resources.QuickVMUploadingWinRMCertificate, CommandRuntime, WinRMCertificate.Thumbprint);
                    var parameters           = CertUtilsNewSM.Create(WinRMCertificate);

                    ExecuteClientActionNewSM(
                        null,
                        operationDescription,
                        () => this.ComputeClient.ServiceCertificates.Create(this.ServiceName, parameters),
                        (s, r) => ContextFactory <OperationStatusResponse, ManagementOperationContext>(r, s));
                }

                if (X509Certificates != null)
                {
                    var certificateFilesWithThumbprint = from c in X509Certificates
                                                         select new
                    {
                        c.Thumbprint,
                        CertificateFile = CertUtilsNewSM.Create(c, this.NoExportPrivateKey.IsPresent)
                    };
                    foreach (var current in certificateFilesWithThumbprint.ToList())
                    {
                        var operationDescription = string.Format(Resources.QuickVMUploadingCertificate, CommandRuntime, current.Thumbprint);
                        ExecuteClientActionNewSM(
                            null,
                            operationDescription,
                            () => this.ComputeClient.ServiceCertificates.Create(this.ServiceName, current.CertificateFile),
                            (s, r) => ContextFactory <OperationStatusResponse, ManagementOperationContext>(r, s));
                    }
                }
            }

            var vm = CreatePersistenVMRole(currentStorage);

            try
            {
                if (CurrentDeploymentNewSM == null)
                {
                    // If the current deployment doesn't exist set it create it
                    var parameters = new VirtualMachineCreateDeploymentParameters
                    {
                        DeploymentSlot     = DeploymentSlot.Production,
                        Name               = this.ServiceName,
                        Label              = this.ServiceName,
                        VirtualNetworkName = this.VNetName,
                        Roles              = { vm },
                        ReservedIPName     = this.ReservedIPName,
                        DnsSettings        = this.DnsSettings == null ? null : new Microsoft.WindowsAzure.Management.Compute.Models.DnsSettings
                        {
                            DnsServers = (from dns in this.DnsSettings
                                          select new Management.Compute.Models.DnsServer
                            {
                                Name = dns.Name,
                                Address = dns.Address
                            }).ToList()
                        }
                    };

                    ExecuteClientActionNewSM(
                        parameters,
                        string.Format(Resources.QuickVMCreateDeploymentWithVM, CommandRuntime, vm.RoleName),
                        () => this.ComputeClient.VirtualMachines.CreateDeployment(this.ServiceName, parameters));
                }
                else
                {
                    if (!string.IsNullOrEmpty(VNetName) || DnsSettings != null)
                    {
                        WriteWarning(Resources.VNetNameOrDnsSettingsCanOnlyBeSpecifiedOnNewDeployments);
                    }

                    // Only create the VM when a new VM was added and it was not created during the deployment phase.
                    ExecuteClientActionNewSM(
                        vm,
                        string.Format(Resources.QuickVMCreateVM, CommandRuntime, vm.RoleName),
                        () => this.ComputeClient.VirtualMachines.Create(
                            this.ServiceName,
                            this.ServiceName,
                            new VirtualMachineCreateParameters
                    {
                        AvailabilitySetName         = vm.AvailabilitySetName,
                        OSVirtualHardDisk           = vm.OSVirtualHardDisk,
                        DataVirtualHardDisks        = vm.DataVirtualHardDisks,
                        RoleName                    = vm.RoleName,
                        RoleSize                    = vm.RoleSize,
                        VMImageName                 = vm.VMImageName,
                        MediaLocation               = vm.MediaLocation,
                        ProvisionGuestAgent         = vm.ProvisionGuestAgent,
                        ResourceExtensionReferences = vm.ResourceExtensionReferences,
                        ConfigurationSets           = vm.ConfigurationSets
                    }));
                }

                if (WaitForBoot.IsPresent)
                {
                    WaitForRoleToBoot(vm.RoleName);
                }
            }
            catch (CloudException ex)
            {
                if (ex.Response.StatusCode == HttpStatusCode.NotFound)
                {
                    throw new Exception(Resources.ServiceDoesNotExistSpecifyLocationOrAffinityGroup);
                }

                WriteExceptionError(ex);
            }
        }
コード例 #15
0
        public async Task <string> CreateVirtualMachine(string virtualMachineName, string cloudServiceName, string storageAccountName, string username, string password, string imageFilter, string virtualMachineSize, int rdpPort, bool isCloudServiceAlreadyCreated)
        {
            using (var computeClient = new ComputeManagementClient(_credentials))
            {
                // get the list of images from the api
                var operatingSystemImageListResult =
                    await computeClient.VirtualMachineOSImages.ListAsync();

                // find the one i want
                var virtualMachineOsImage = operatingSystemImageListResult
                                            .Images
                                            .FirstOrDefault(x =>
                                                            x.Name.Contains(imageFilter));


                if (virtualMachineOsImage == null)
                {
                    throw new Exception("OS Image Name Not Foud");
                }
                var imageName =
                    virtualMachineOsImage.Name;


                // set up the configuration set for the windows image
                var windowsConfigSet = new ConfigurationSet
                {
                    ConfigurationSetType = ConfigurationSetTypes.WindowsProvisioningConfiguration,
                    AdminPassword        = password,
                    AdminUserName        = username,
                    ComputerName         = virtualMachineName,
                    HostName             = string.Format("{0}.cloudapp.net", cloudServiceName)
                };

                // make sure i enable powershell & rdp access
                var endpoints = new ConfigurationSet
                {
                    ConfigurationSetType = "NetworkConfiguration",
                    InputEndpoints       = new List <InputEndpoint>
                    {
                        //new InputEndpoint
                        //{
                        //    Name = "PowerShell", LocalPort = 5986, Protocol = "tcp", Port = 5986,
                        //},
                        new InputEndpoint
                        {
                            Name      = "Remote Desktop",
                            LocalPort = 3389,
                            Protocol  = "tcp",
                            Port      = rdpPort,
                        }
                    }
                };

                // set up the hard disk with the os
                var vhd = SetOsVirtualHardDisk(virtualMachineName, storageAccountName, imageName);
                // create the role for the vm in the cloud service
                var role = new Role
                {
                    RoleName            = virtualMachineName,
                    RoleSize            = virtualMachineSize,
                    RoleType            = VirtualMachineRoleType.PersistentVMRole.ToString(),
                    OSVirtualHardDisk   = vhd,
                    ProvisionGuestAgent = true,

                    ConfigurationSets = new List <ConfigurationSet>
                    {
                        windowsConfigSet,
                        endpoints
                    }
                };
                var isDeploymentCreated = false;
                if (isCloudServiceAlreadyCreated)
                {
                    var vm = await computeClient.HostedServices.GetDetailedAsync(cloudServiceName);

                    isDeploymentCreated = vm.Deployments.ToList().Any(x => x.Name == cloudServiceName);
                }

                if (isDeploymentCreated)
                {
                    AddRole(cloudServiceName, cloudServiceName, role, DeploymentSlot.Production);
                }
                else
                {
                    // create the deployment parameters
                    var createDeploymentParameters = new VirtualMachineCreateDeploymentParameters
                    {
                        Name           = cloudServiceName,
                        Label          = cloudServiceName,
                        DeploymentSlot = DeploymentSlot.Production,
                        Roles          = new List <Role> {
                            role
                        }
                    };


                    // deploy the virtual machine
                    var deploymentResult = await computeClient.VirtualMachines.CreateDeploymentAsync(
                        cloudServiceName,
                        createDeploymentParameters);
                }

                // return the name of the virtual machine
                return(virtualMachineName);
            }
        }