コード例 #1
0
        protected override void ProcessRecord()
        {
            base.ProcessRecord();

            ExecuteClientAction(() =>
            {
                var parameters = new VirtualMachine
                {
                    DiagnosticsProfile = this.VM.DiagnosticsProfile,
                    HardwareProfile = this.VM.HardwareProfile,
                    StorageProfile = this.VM.StorageProfile,
                    NetworkProfile = this.VM.NetworkProfile,
                    OSProfile = this.VM.OSProfile,
                    Plan = this.VM.Plan,
                    AvailabilitySetReference = this.VM.AvailabilitySetReference,
                    Location = this.VM.Location,
                    Name = this.VM.Name,
                    Tags = this.Tags != null ? this.Tags.ToDictionary() : this.VM.Tags
                };

                var op = this.VirtualMachineClient.CreateOrUpdate(this.ResourceGroupName, parameters);
                var result = Mapper.Map<PSComputeLongRunningOperation>(op);
                WriteObject(result);
            });
        }
コード例 #2
0
        public override void ExecuteCmdlet()
        {
            base.ExecuteCmdlet();

            ExecuteClientAction(() =>
            {
                var parameters = new VirtualMachine
                {
                    DiagnosticsProfile = this.VM.DiagnosticsProfile,
                    HardwareProfile = this.VM.HardwareProfile,
                    StorageProfile = this.VM.StorageProfile,
                    NetworkProfile = this.VM.NetworkProfile,
                    OsProfile = this.VM.OSProfile,
                    Plan = this.VM.Plan,
                    AvailabilitySet = this.VM.AvailabilitySetReference,
                    Location = this.VM.Location,
                    Tags = this.Tags != null ? this.Tags.ToDictionary() : this.VM.Tags
                };

                var op = this.VirtualMachineClient.CreateOrUpdateWithHttpMessagesAsync(
                    this.ResourceGroupName,
                    this.VM.Name,
                    parameters).GetAwaiter().GetResult();
                var result = Mapper.Map<PSAzureOperationResponse>(op);
                WriteObject(result);
            });
        }
コード例 #3
0
        public override void ExecuteCmdlet()
        {
            base.ExecuteCmdlet();

            ExecuteClientAction(() =>
            {
                if (! string.IsNullOrEmpty(this.Name))
                {
                    WriteWarning(Properties.Resources.DeprecationOfNewAzureVMNameParameterWarning);
                }

                var parameters = new VirtualMachine
                {
                    HardwareProfile          = this.VM.HardwareProfile,
                    StorageProfile           = this.VM.StorageProfile,
                    NetworkProfile           = this.VM.NetworkProfile,
                    OSProfile                = this.VM.OSProfile,
                    Plan                     = this.VM.Plan,
                    AvailabilitySetReference = this.VM.AvailabilitySetReference,
                    Location                 = !string.IsNullOrEmpty(this.Location) ? this.Location : this.VM.Location,
                    Name                     = !string.IsNullOrEmpty(this.Name) ? this.Name : this.VM.Name,
                    Tags                     = this.Tags != null ? this.Tags.ToDictionary() : this.VM.Tags
                };

                var op = this.VirtualMachineClient.CreateOrUpdate(this.ResourceGroupName, parameters);
                WriteObject(op);
            });
        }
コード例 #4
0
 private DiskEncryptionSettings GetOsVolumeEncryptionSettings(VirtualMachine vmParameters)
 {
     if ((vmParameters != null) &&
         (vmParameters.StorageProfile != null) &&
         (vmParameters.StorageProfile.OSDisk != null))
     {
         return vmParameters.StorageProfile.OSDisk.EncryptionSettings;
     }
     return null;
 }
コード例 #5
0
        public void SetCertificateInfo(VirtualMachine vm)
        {
            SourceVaultReference vault = GetDefaultSourceVault();

            VaultCertificate vmCert = GetDefaultVaultCert();

            var secretGroup = new VaultSecretGroup() {SourceVault = vault, VaultCertificates = new List<VaultCertificate>(){vmCert}};

            vm.OSProfile.Secrets = new List<VaultSecretGroup>() { secretGroup };
        }
コード例 #6
0
        private bool IsOsVolumeEncrypted(VirtualMachine vmParameters)
        {
            var osVolumeEncryptionSettings = GetOsVolumeEncryptionSettings(vmParameters);
            if (osVolumeEncryptionSettings != null)
            {
                return (osVolumeEncryptionSettings.Enabled == true
                    && !string.IsNullOrWhiteSpace(osVolumeEncryptionSettings.DiskEncryptionKey.SecretUrl));
            }

            return false;
        }
コード例 #7
0
 private List<string> GetDiskBlobUris(VirtualMachine virtualMachineResponse)
 {
     List<string> blobUris = new List<string>();
     string osDiskUri = virtualMachineResponse.StorageProfile.OsDisk.Vhd.Uri;
     blobUris.Add(osDiskUri);
     var dataDisks = virtualMachineResponse.StorageProfile.DataDisks;
     for (int i = 0; i < dataDisks.Count; i++)
     {
         blobUris.Add(dataDisks[i].Vhd.Uri);
     }
     return blobUris;
 }
コード例 #8
0
 private void EnableWinRMCustomDataAndUnattendContent(string rgName, string keyVaultName, Uri winRMCertificateUrl, string autoLogonContent, VirtualMachine inputVM)
 {
     OSProfile osProfile = inputVM.OSProfile;
     osProfile.CustomData = CustomData;
     osProfile.WindowsConfiguration = new WindowsConfiguration
     {
         ProvisionVMAgent = true,
         EnableAutomaticUpdates = false,
         TimeZone = PacificStandardTime,
         AdditionalUnattendContents = new List<AdditionalUnattendContent>
             {
                 new AdditionalUnattendContent 
                 {
                     PassName = OOBESystem,
                     ComponentName = MicrosoftWindowsShellSetup,
                     SettingName = AutoLogon,
                     Content = autoLogonContent
                 }
             },
         WinRMConfiguration = new WinRMConfiguration
         {
             Listeners = new List<WinRMListener>
                 {
                     new WinRMListener
                     {
                         Protocol = ProtocolTypes.Http,
                         CertificateUrl = null,
                     },
                     new WinRMListener
                     {
                         Protocol = ProtocolTypes.Https,
                         CertificateUrl = winRMCertificateUrl,
                     }
                 }
         }
     };
     osProfile.Secrets = new List<VaultSecretGroup>
         {
             new VaultSecretGroup
             {
                  SourceVault = SecretVaultHelper.GetVaultId(m_subId, rgName, keyVaultName).Result,
                  VaultCertificates = new List<VaultCertificate>
                  {
                      new VaultCertificate
                      {
                          CertificateStore = "My",
                          CertificateUrl = winRMCertificateUrl.AbsoluteUri
                      }
                  }
             }
         };
 }
コード例 #9
0
 private async Task<VmState> GetVmStateFromInstance(VirtualMachine vm)
 {
     var powerState = vm.InstanceView?.Statuses.FirstOrDefault(s => s.Code.StartsWith("PowerState/"));
     var state = new VmState
     {
         Id = vm.Id,
         Name = vm.Name,
         State = powerState == null ? "Unknown" : powerState.DisplayStatus,
     };
     var snapshotState = await GetSnapshotStateForVm(vm);
     snapshotState.Snapshots.ForEach(s => state.Snapshots.Add(s));
     return state;
 }
コード例 #10
0
        private VirtualMachineExtension GetVmExtensionParameters(VirtualMachine vmParameters, OSType currentOSType)
        {
            Hashtable publicSettings = new Hashtable();
            Hashtable protectedSettings = new Hashtable();

            publicSettings.Add(AzureDiskEncryptionExtensionConstants.encryptionOperationKey, AzureDiskEncryptionExtensionConstants.queryEncryptionStatusOperation);
            publicSettings.Add(AzureDiskEncryptionExtensionConstants.sequenceVersionKey, Guid.NewGuid().ToString());

            if (vmParameters == null)
            {
                ThrowTerminatingError(new ErrorRecord(new ApplicationException(string.Format(CultureInfo.CurrentUICulture, "Get-AzureDiskEncryptionExtension can enable encryption only on a VM that was already created ")),
                                                      "InvalidResult",
                                                      ErrorCategory.InvalidResult,
                                                      null));
            }

            VirtualMachineExtension vmExtensionParameters = null;

            if (OSType.Windows.Equals(currentOSType))
            {
                this.Name = this.Name ?? AzureDiskEncryptionExtensionContext.ExtensionDefaultName;
                vmExtensionParameters = new VirtualMachineExtension
                {
                    Location = vmParameters.Location,
                    Publisher = AzureDiskEncryptionExtensionContext.ExtensionDefaultPublisher,
                    VirtualMachineExtensionType = AzureDiskEncryptionExtensionContext.ExtensionDefaultName,
                    TypeHandlerVersion = AzureDiskEncryptionExtensionContext.ExtensionDefaultVersion,
                    Settings = publicSettings,
                    ProtectedSettings = protectedSettings
                };
            }
            else if (OSType.Linux.Equals(currentOSType))
            {
                this.Name = this.Name ?? AzureDiskEncryptionExtensionContext.LinuxExtensionDefaultName;
                vmExtensionParameters = new VirtualMachineExtension
                {
                    Location = vmParameters.Location,
                    Publisher = AzureDiskEncryptionExtensionContext.LinuxExtensionDefaultPublisher,
                    VirtualMachineExtensionType = AzureDiskEncryptionExtensionContext.LinuxExtensionDefaultName,
                    TypeHandlerVersion = AzureDiskEncryptionExtensionContext.LinuxExtensionDefaultVersion,
                    Settings = publicSettings,
                    ProtectedSettings = protectedSettings
                };
            }

            return vmExtensionParameters;
        }
コード例 #11
0
 private OSType GetOSType(VirtualMachine vmParameters)
 {
     if (vmParameters == null || vmParameters.StorageProfile == null || vmParameters.StorageProfile.OsDisk == null)
     {
         return OSType.Unknown;
     }
     else
     {
         if (OperatingSystemTypes.Linux == vmParameters.StorageProfile.OsDisk.OsType)
         {
             return OSType.Linux;
         }
         if (OperatingSystemTypes.Windows == vmParameters.StorageProfile.OsDisk.OsType)
         {
             return OSType.Windows;
         }
         return OSType.Unknown;
     }
 }
コード例 #12
0
        protected override void ProcessRecord()
        {
            base.ProcessRecord();

            if (this.VM.DiagnosticsProfile == null)
            {
                var storageUri = GetOrCreateStorageAccountForBootDiagnostics();

                if (storageUri != null)
                {
                    this.VM.DiagnosticsProfile = new DiagnosticsProfile
                    {
                        BootDiagnostics = new BootDiagnostics
                        {
                            Enabled = true,
                            StorageUri = storageUri,
                        }
                    };
                }
            }

            ExecuteClientAction(() =>
            {
                var parameters = new VirtualMachine
                {
                    DiagnosticsProfile       = this.VM.DiagnosticsProfile,
                    HardwareProfile          = this.VM.HardwareProfile,
                    StorageProfile           = this.VM.StorageProfile,
                    NetworkProfile           = this.VM.NetworkProfile,
                    OSProfile                = this.VM.OSProfile,
                    Plan                     = this.VM.Plan,
                    AvailabilitySetReference = this.VM.AvailabilitySetReference,
                    Location                 = !string.IsNullOrEmpty(this.Location) ? this.Location : this.VM.Location,
                    Name                     = this.VM.Name,
                    Tags                     = this.Tags != null ? this.Tags.ToDictionary() : this.VM.Tags
                };

                var op = this.VirtualMachineClient.CreateOrUpdate(this.ResourceGroupName, parameters);
                var result = Mapper.Map<PSComputeLongRunningOperation>(op);
                WriteObject(result);
            });
        }
コード例 #13
0
        private EncryptionStatus IsOsVolumeEncrypted(VirtualMachine vmParameters)
        {
            OSType osType = this.GetOSType(vmParameters);
            switch (osType)
            {
                case OSType.Windows:
                    DiskEncryptionSettings osEncryptionSettings = GetOsVolumeEncryptionSettings(vmParameters);

                    if (osEncryptionSettings != null
                        && osEncryptionSettings.DiskEncryptionKey != null
                        && !String.IsNullOrEmpty(osEncryptionSettings.DiskEncryptionKey.SecretUrl)
                        && osEncryptionSettings.Enabled == true)
                    {
                        return EncryptionStatus.Encrypted;
                    }
                    else
                    {
                        return EncryptionStatus.NotEncrypted;
                    }
                default:
                    return EncryptionStatus.Unknown;
            }
        }
コード例 #14
0
        public override void ExecuteCmdlet()
        {
            base.ExecuteCmdlet();

            ExecuteClientAction(() =>
            {
                var parameters = new VirtualMachine
                {
                    HardwareProfile = this.VM.HardwareProfile,
                    StorageProfile = this.VM.StorageProfile,
                    NetworkProfile = this.VM.NetworkProfile,
                    OSProfile = this.VM.OSProfile,
                    Plan = this.VM.Plan,
                    AvailabilitySetReference = this.VM.AvailabilitySetReference,
                    Location = this.VM.Location,
                    Name = this.VM.Name,
                    Tags = this.Tags != null ? this.Tags.ToDictionary() : this.VM.Tags
                };

                var op = this.VirtualMachineClient.CreateOrUpdate(this.ResourceGroupName, parameters);
                WriteObject(op);
            });
        }
コード例 #15
0
 internal VirtualMachineExtension GetExtension(VirtualMachine vm, string type, string publisher)
 {
     if (vm.Resources != null)
     {
         return vm.Resources.FirstOrDefault(ext =>
            ext.VirtualMachineExtensionType.Equals(type)
            && ext.Publisher.Equals(publisher));
     }
     return null;
 }
コード例 #16
0
        internal AzureSLA GetVMSLA(VirtualMachine virtualMachine)
        {
            var result = new AzureSLA();
            result.HasSLA = false;
            switch (virtualMachine.HardwareProfile.VmSize)
            {
                case "Standard_DS1":
                case "Standard_DS1_v2":
                    result.HasSLA = true;
                    result.IOPS = "3200";
                    result.TP = "32";
                    break;
                case "Standard_DS2":
                case "Standard_DS2_v2":
                    result.HasSLA = true;
                    result.IOPS = "6400";
                    result.TP = "64";
                    break;
                case "Standard_DS3":
                case "Standard_DS3_v2":
                    result.HasSLA = true;
                    result.IOPS = "12800";
                    result.TP = "128";
                    break;
                case "Standard_DS4":
                case "Standard_DS4_v2":
                    result.HasSLA = true;
                    result.IOPS = "25600";
                    result.TP = "256";
                    break;
                case "Standard_DS11":
                case "Standard_DS11_v2":
                    result.HasSLA = true;
                    result.IOPS = "6400";
                    result.TP = "64";
                    break;
                case "Standard_DS12":
                case "Standard_DS12_v2":
                    result.HasSLA = true;
                    result.IOPS = "12800";
                    result.TP = "128";
                    break;
                case "Standard_DS13":
                case "Standard_DS13_v2":
                    result.HasSLA = true;
                    result.IOPS = "25600";
                    result.TP = "256";
                    break;
                case "Standard_DS14":
                case "Standard_DS14_v2":
                    result.HasSLA = true;
                    result.IOPS = "50000";
                    result.TP = "512";
                    break;
                case "Standard_GS1":
                    result.HasSLA = true;
                    result.IOPS = "5000";
                    result.TP = "125";
                    break;
                case "Standard_GS2":
                    result.HasSLA = true;
                    result.IOPS = "10000";
                    result.TP = "250";
                    break;
                case "Standard_GS3":
                    result.HasSLA = true;
                    result.IOPS = "20000";
                    result.TP = "500";
                    break;
                case "Standard_GS4":
                    result.HasSLA = true;
                    result.IOPS = "40000";
                    result.TP = "1000";
                    break;
                case "Standard_GS5":
                    result.HasSLA = true;
                    result.IOPS = "80000";
                    result.TP = "2000";
                    break;
                default:
                    break;
            }

            return result;
        }
コード例 #17
0
        private void ValidateWinRMCustomDataAndUnattendContent(string rgName, string keyVaultName, Uri winRMCertificateUrl, string autoLogonContent, VirtualMachine outputVM)
        {
            OSProfile osProfile = outputVM.OSProfile;
            // CustomData:
            Assert.Equal(osProfile.CustomData, CustomData);

            Assert.Null(osProfile.LinuxConfiguration);
            Assert.NotNull(osProfile.WindowsConfiguration);

            Assert.True(osProfile.WindowsConfiguration.ProvisionVMAgent != null && osProfile.WindowsConfiguration.ProvisionVMAgent.Value);
            Assert.True(osProfile.WindowsConfiguration.EnableAutomaticUpdates != null && !osProfile.WindowsConfiguration.EnableAutomaticUpdates.Value);

            // TimeZone
            Assert.Equal(PacificStandardTime, osProfile.WindowsConfiguration.TimeZone);

            // WinRM
            Assert.NotNull(osProfile.WindowsConfiguration.WinRMConfiguration);
            var listeners = osProfile.WindowsConfiguration.WinRMConfiguration.Listeners;
            Assert.NotNull(listeners);
            Assert.Equal(2, listeners.Count);

            if (listeners[0].Protocol.Equals(ProtocolTypes.Http, StringComparison.InvariantCultureIgnoreCase))
            {
                Assert.Null(listeners[0].CertificateUrl);

                Assert.True(listeners[1].Protocol.Equals(ProtocolTypes.Https, StringComparison.InvariantCultureIgnoreCase));
                Assert.True(listeners[1].CertificateUrl.AbsoluteUri.Equals(winRMCertificateUrl.AbsoluteUri, StringComparison.OrdinalIgnoreCase));
            }
            else if (listeners[0].Protocol.Equals(ProtocolTypes.Https, StringComparison.InvariantCultureIgnoreCase))
            {
                Assert.True(listeners[0].CertificateUrl.AbsoluteUri.Equals(winRMCertificateUrl.AbsoluteUri, StringComparison.OrdinalIgnoreCase));

                Assert.True(listeners[1].Protocol.Equals(ProtocolTypes.Http, StringComparison.InvariantCultureIgnoreCase));
                Assert.Null(listeners[1].CertificateUrl);
            }
            else
            {
                // Unexpected value for winRM Listener protocol
                Assert.True(false);
            }

            // AdditionalUnattendContent
            var additionalContents = osProfile.WindowsConfiguration.AdditionalUnattendContents;
            Assert.NotNull(additionalContents);
            Assert.Equal(1, additionalContents.Count);
            Assert.Equal(OOBESystem, additionalContents[0].PassName);
            Assert.Equal(MicrosoftWindowsShellSetup, additionalContents[0].ComponentName);
            Assert.Equal(AutoLogon, additionalContents[0].SettingName);
            Assert.Equal(autoLogonContent, additionalContents[0].Content);
        }
コード例 #18
0
        private VirtualMachine SetAzureVMDiagnosticsExtensionC(VirtualMachine selectedVM, string storageAccountName, string storageAccountKey)
        {
            System.Xml.XmlDocument xpublicConfig = null;

            var extensionName = AEMExtensionConstants.WADExtensionDefaultName[this.OSType];

            var extTemp = this._Helper.GetExtension(selectedVM,
                AEMExtensionConstants.WADExtensionType[this.OSType], AEMExtensionConstants.WADExtensionPublisher[OSType]);
            object publicConf = null;
            if (extTemp != null)
            {
                publicConf = extTemp.Settings;
                extensionName = extTemp.Name;
            }

            if (publicConf != null)
            {
                var jpublicConf = publicConf as Newtonsoft.Json.Linq.JObject;
                if (jpublicConf == null)
                {
                    throw new ArgumentException();
                }

                var base64 = jpublicConf["xmlCfg"] as Newtonsoft.Json.Linq.JValue;
                if (base64 == null)
                {
                    throw new ArgumentException();
                }

                System.Xml.XmlDocument xDoc = new System.Xml.XmlDocument();
                xDoc.LoadXml(Encoding.UTF8.GetString(System.Convert.FromBase64String(base64.Value.ToString())));

                if (xDoc.SelectSingleNode("/WadCfg/DiagnosticMonitorConfiguration/PerformanceCounters") != null)
                {
                    xDoc.SelectSingleNode("WadCfg/DiagnosticMonitorConfiguration").Attributes["overallQuotaInMB"].Value = "4096";
                    xDoc.SelectSingleNode("WadCfg/DiagnosticMonitorConfiguration/PerformanceCounters").Attributes["scheduledTransferPeriod"].Value = "PT1M";

                    xpublicConfig = xDoc;
                }
            }

            if (xpublicConfig == null)
            {
                xpublicConfig = new System.Xml.XmlDocument();
                xpublicConfig.LoadXml(AEMExtensionConstants.WADConfigXML);
            }

            foreach (var perfCounter in AEMExtensionConstants.PerformanceCounters[OSType])
            {
                var currentCounter = xpublicConfig.
                            SelectSingleNode("WadCfg/DiagnosticMonitorConfiguration/PerformanceCounters/PerformanceCounterConfiguration[@counterSpecifier = '" + perfCounter.counterSpecifier + "']");
                if (currentCounter == null)
                {
                    var node = xpublicConfig.CreateElement("PerformanceCounterConfiguration");
                    xpublicConfig.SelectSingleNode("WadCfg/DiagnosticMonitorConfiguration/PerformanceCounters").AppendChild(node);
                    node.SetAttribute("counterSpecifier", perfCounter.counterSpecifier);
                    node.SetAttribute("sampleRate", perfCounter.sampleRate);
                }
            }

            var endpoint = this._Helper.GetCoreEndpoint(storageAccountName);
            endpoint = "https://" + endpoint;

            Newtonsoft.Json.Linq.JObject jPublicConfig = new Newtonsoft.Json.Linq.JObject();
            jPublicConfig.Add("xmlCfg", new Newtonsoft.Json.Linq.JValue(System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(xpublicConfig.InnerXml))));

            Newtonsoft.Json.Linq.JObject jPrivateConfig = new Newtonsoft.Json.Linq.JObject();
            jPrivateConfig.Add("storageAccountName", new Newtonsoft.Json.Linq.JValue(storageAccountName));
            jPrivateConfig.Add("storageAccountKey", new Newtonsoft.Json.Linq.JValue(storageAccountKey));
            jPrivateConfig.Add("storageAccountEndPoint", new Newtonsoft.Json.Linq.JValue(endpoint));

            WriteVerbose("Installing WAD extension");
            VirtualMachineExtension vmExtParameters = new VirtualMachineExtension();

            vmExtParameters.Publisher = AEMExtensionConstants.WADExtensionPublisher[this.OSType];
            vmExtParameters.VirtualMachineExtensionType = AEMExtensionConstants.WADExtensionType[this.OSType];
            vmExtParameters.TypeHandlerVersion = AEMExtensionConstants.WADExtensionVersion[this.OSType];
            vmExtParameters.Settings = jPublicConfig;
            vmExtParameters.ProtectedSettings = jPrivateConfig;
            vmExtParameters.Location = selectedVM.Location;

            this.VirtualMachineExtensionClient.CreateOrUpdate(ResourceGroupName, selectedVM.Name, extensionName, vmExtParameters);

            return this.ComputeClient.ComputeManagementClient.VirtualMachines.Get(ResourceGroupName, selectedVM.Name);
        }
コード例 #19
0
 private async Task SaveSnapshotStateForVm(SnapshotState snapshotState, VirtualMachine vm)
 {
     var snapshotStateUri = vm.StorageProfile.OSDisk.VirtualHardDisk.Uri + ".snapshotstate";
     var storageCred = await GetStorageCredentialsForUri(snapshotStateUri);
     var blob = new CloudBlockBlob(new Uri(snapshotStateUri), storageCred);
     await blob.UploadTextAsync(JsonConvert.SerializeObject(snapshotState));
 }
コード例 #20
0
 private async Task<SnapshotState> GetSnapshotStateForVm(VirtualMachine vm)
 {
     var snapshotStateUri = vm.StorageProfile.OSDisk.VirtualHardDisk.Uri + ".snapshotstate";
     var storageCred = await GetStorageCredentialsForUri(snapshotStateUri);
     var blob = new CloudBlockBlob(new Uri(snapshotStateUri), storageCred);
     var snapshotState = new SnapshotState();
     if (await blob.ExistsAsync())
     {
         snapshotState = JsonConvert.DeserializeObject<SnapshotState>(await blob.DownloadTextAsync());
     }
     return snapshotState;
 }
コード例 #21
0
 private static bool IsVmRunning(VirtualMachine vm)
 {
     var powerState = vm.InstanceView?.Statuses.FirstOrDefault(s => s.Code.StartsWith("PowerState/"));
     return (powerState == null ? "Unknown" : powerState.DisplayStatus) == "VM running";
 }
コード例 #22
0
        /// <summary>
        /// This function gets the VM model, fills in the OSDisk properties with encryptionSettings and does an UpdateVM
        /// </summary>
        private ComputeLongRunningOperationResponse UpdateVmEncryptionSettings()
        {
            string statusMessage = GetExtensionStatusMessage();

            VirtualMachine vmParameters = (this.ComputeClient.ComputeManagementClient.VirtualMachines.Get(this.ResourceGroupName, this.VMName)).VirtualMachine;
            if ((vmParameters == null) ||
                (vmParameters.StorageProfile == null) ||
                (vmParameters.StorageProfile.OSDisk == null))
            {
                //VM should have been created and have valid storageProfile and OSDisk by now
                ThrowTerminatingError(new ErrorRecord(new ApplicationException(string.Format(CultureInfo.CurrentUICulture, "Set-AzureDiskEncryptionExtension can enable encryption only on a VM that was already created and has appropriate storageProfile and OS disk")),
                                                      "InvalidResult",
                                                      ErrorCategory.InvalidResult,
                                                      null));
            }

            DiskEncryptionSettings encryptionSettings = new DiskEncryptionSettings();
            encryptionSettings.DiskEncryptionKey = new KeyVaultSecretReference();
            encryptionSettings.DiskEncryptionKey.SourceVault = new SourceVaultReference();
            encryptionSettings.DiskEncryptionKey.SourceVault.ReferenceUri = this.DiskEncryptionKeyVaultId;
            encryptionSettings.DiskEncryptionKey.SecretUrl = statusMessage;
            if (this.KeyEncryptionKeyUrl != null)
            {
                encryptionSettings.KeyEncryptionKey = new KeyVaultKeyReference();
                encryptionSettings.KeyEncryptionKey.SourceVault = new SourceVaultReference();
                encryptionSettings.KeyEncryptionKey.SourceVault.ReferenceUri = this.KeyEncryptionKeyVaultId;
                encryptionSettings.KeyEncryptionKey.KeyUrl = this.KeyEncryptionKeyUrl;
            }
            vmParameters.StorageProfile.OSDisk.EncryptionSettings = encryptionSettings;
            var parameters = new VirtualMachine
            {
                DiagnosticsProfile = vmParameters.DiagnosticsProfile,
                HardwareProfile = vmParameters.HardwareProfile,
                StorageProfile = vmParameters.StorageProfile,
                NetworkProfile = vmParameters.NetworkProfile,
                OSProfile = vmParameters.OSProfile,
                Plan = vmParameters.Plan,
                AvailabilitySetReference = vmParameters.AvailabilitySetReference,
                Location = vmParameters.Location,
                Name = vmParameters.Name,
                Tags = vmParameters.Tags
            };
            return this.ComputeClient.ComputeManagementClient.VirtualMachines.CreateOrUpdate(this.ResourceGroupName, parameters);
        }
コード例 #23
0
        public override void ExecuteCmdlet()
        {
            base.ExecuteCmdlet();

            if (this.VM.DiagnosticsProfile == null)
            {
                var storageUri = GetOrCreateStorageAccountForBootDiagnostics();

                if (storageUri != null)
                {
                    this.VM.DiagnosticsProfile = new DiagnosticsProfile
                    {
                        BootDiagnostics = new BootDiagnostics
                        {
                            Enabled = true,
                            StorageUri = storageUri.ToString(),
                        }
                    };
                }
            }

            ExecuteClientAction(() =>
            {
                var parameters = new VirtualMachine
                {
                    DiagnosticsProfile       = this.VM.DiagnosticsProfile,
                    HardwareProfile          = this.VM.HardwareProfile,
                    StorageProfile           = this.VM.StorageProfile,
                    NetworkProfile           = this.VM.NetworkProfile,
                    OsProfile                = this.VM.OSProfile,
                    Plan                     = this.VM.Plan,
                    LicenseType              = this.LicenseType,
                    AvailabilitySet = this.VM.AvailabilitySetReference,
                    Location                 = !string.IsNullOrEmpty(this.Location) ? this.Location : this.VM.Location,
                    Tags                     = this.Tags != null ? this.Tags.ToDictionary() : this.VM.Tags
                };

                var op = this.VirtualMachineClient.CreateOrUpdateWithHttpMessagesAsync(
                    this.ResourceGroupName,
                    this.VM.Name,
                    parameters);
                var wait = op.GetAwaiter();
                var resultop = wait.GetResult();
                var result = Mapper.Map<PSAzureOperationResponse>(resultop);

                if (!(this.DisableBginfoExtension.IsPresent || IsLinuxOs()))
                {

                    var currentBginfoVersion = GetBginfoExtension();

                    if (!string.IsNullOrEmpty(currentBginfoVersion))
                    {
                        var extensionParameters = new VirtualMachineExtension
                        {
                            Location = this.Location,
                            Publisher = VirtualMachineBGInfoExtensionContext.ExtensionDefaultPublisher,
                            VirtualMachineExtensionType = VirtualMachineBGInfoExtensionContext.ExtensionDefaultName,
                            TypeHandlerVersion = currentBginfoVersion,
                            AutoUpgradeMinorVersion = true,
                        };

                        typeof(Resource).GetRuntimeProperty("Name").SetValue(extensionParameters, VirtualMachineBGInfoExtensionContext.ExtensionDefaultName);
                        typeof(Resource).GetRuntimeProperty("Type")
                            .SetValue(extensionParameters, VirtualMachineExtensionType);

                        var op2 = ComputeClient.ComputeManagementClient.VirtualMachineExtensions.CreateOrUpdateWithHttpMessagesAsync(
                            this.ResourceGroupName,
                            this.VM.Name,
                            VirtualMachineBGInfoExtensionContext.ExtensionDefaultName,
                            extensionParameters).GetAwaiter().GetResult();
                        result = Mapper.Map<PSAzureOperationResponse>(op2);
                    }
                }
                WriteObject(result);
            });
        }
コード例 #24
0
        protected void ValidateVMInstanceView(VirtualMachine vmIn, VirtualMachine vmOut)
        {
            Assert.NotNull(vmOut.InstanceView);
            Assert.True(vmOut.InstanceView.Statuses.Any(s => !string.IsNullOrEmpty(s.Code)));

            var instanceView = vmOut.InstanceView;
            Assert.NotNull(instanceView.Disks);
            Assert.True(instanceView.Disks.Any());

            if (vmIn.StorageProfile.OSDisk != null)
            {
                Assert.True(instanceView.Disks.Any(x => x.Name == vmIn.StorageProfile.OSDisk.Name));
            }

            DiskInstanceView diskInstanceView = instanceView.Disks.First();
            Assert.NotNull(diskInstanceView);
            Assert.NotNull(diskInstanceView.Statuses[0].DisplayStatus);
            Assert.NotNull(diskInstanceView.Statuses[0].Code);
            Assert.NotNull(diskInstanceView.Statuses[0].Level);
            //Assert.NotNull(diskInstanceView.Statuses[0].Message); // TODO: it's null somtimes.
            //Assert.NotNull(diskInstanceView.Statuses[0].Time);    // TODO: it's null somtimes.
            if (vmIn.DiagnosticsProfile != null && vmIn.DiagnosticsProfile.BootDiagnostics != null &&
                vmIn.DiagnosticsProfile.BootDiagnostics.Enabled.HasValue &&
                vmIn.DiagnosticsProfile.BootDiagnostics.Enabled.Value)
            {
                BootDiagnosticsInstanceView bootDiagnostics = vmOut.InstanceView.BootDiagnostics;
                Assert.NotNull(bootDiagnostics);
                Assert.NotNull(bootDiagnostics.ConsoleScreenshotBlobUri);
                //TODO: validate serialConsoleLog for Linux OsType
            }
        }
コード例 #25
0
        protected void ValidateVM(VirtualMachine vm, VirtualMachine vmOut, string expectedVMReferenceId)
        {
            Assert.True(!string.IsNullOrEmpty(vmOut.ProvisioningState));

            Assert.True(vmOut.HardwareProfile.VirtualMachineSize
                     == vm.HardwareProfile.VirtualMachineSize);

            Assert.NotNull(vmOut.StorageProfile.OSDisk);

            if (vm.StorageProfile.OSDisk != null)
            {
                Assert.True(vmOut.StorageProfile.OSDisk.Name
                         == vm.StorageProfile.OSDisk.Name);

                Assert.True(vmOut.StorageProfile.OSDisk.VirtualHardDisk.Uri
                == vm.StorageProfile.OSDisk.VirtualHardDisk.Uri);

                Assert.True(vmOut.StorageProfile.OSDisk.Caching
                         == vm.StorageProfile.OSDisk.Caching);

                Assert.True(vmOut.StorageProfile.OSDisk.DiskSizeGB
                    == vm.StorageProfile.OSDisk.DiskSizeGB);

                if (vm.StorageProfile.OSDisk.EncryptionSettings != null)
                {
                    var encryptionSettings = vm.StorageProfile.OSDisk.EncryptionSettings;
                    Assert.NotNull(vmOut.StorageProfile.OSDisk.EncryptionSettings);
                    var actualEncryptionSettings = vmOut.StorageProfile.OSDisk.EncryptionSettings;
                    Assert.Equal(encryptionSettings.DiskEncryptionKey.SourceVault.ReferenceUri, actualEncryptionSettings.DiskEncryptionKey.SourceVault.ReferenceUri);
                    Assert.Equal(encryptionSettings.DiskEncryptionKey.SecretUrl, actualEncryptionSettings.DiskEncryptionKey.SecretUrl);

                    if (encryptionSettings.KeyEncryptionKey != null)
                    {
                        Assert.NotNull(encryptionSettings.KeyEncryptionKey);
                        Assert.Equal(encryptionSettings.KeyEncryptionKey.SourceVault.ReferenceUri, actualEncryptionSettings.KeyEncryptionKey.SourceVault.ReferenceUri);
                        Assert.Equal(encryptionSettings.KeyEncryptionKey.KeyUrl, actualEncryptionSettings.KeyEncryptionKey.KeyUrl);
                    }
                }
            }

            if (vm.StorageProfile.DataDisks != null &&
                vm.StorageProfile.DataDisks.Any())
            {
                foreach (var dataDisk in vm.StorageProfile.DataDisks)
                {
                    var dataDiskOut = vmOut.StorageProfile.DataDisks.FirstOrDefault(
                            d => string.Equals(dataDisk.Name, d.Name, StringComparison.OrdinalIgnoreCase));
                    Assert.NotNull(dataDiskOut);

                    // Disabling resharper null-ref check as it doesn't seem to understand the not-null assert above.
                    // ReSharper disable PossibleNullReferenceException

                    Assert.NotNull(dataDiskOut.VirtualHardDisk);
                    Assert.NotNull(dataDiskOut.VirtualHardDisk.Uri);

                    if (dataDisk.SourceImage != null && dataDisk.SourceImage.Uri != null)
                    {
                        Assert.NotNull(dataDiskOut.SourceImage);
                        Assert.Equal(dataDisk.SourceImage.Uri, dataDiskOut.SourceImage.Uri);
                    }
                    // ReSharper enable PossibleNullReferenceException

                    Assert.True(dataDiskOut.DiskSizeGB == dataDisk.DiskSizeGB);
                }
            }

            if(vm.OSProfile != null &&
               vm.OSProfile.Secrets != null &&
               vm.OSProfile.Secrets.Any())
            {
                foreach (var secret in vm.OSProfile.Secrets)
                {
                    Assert.NotNull(secret.VaultCertificates);
                    var secretOut = vmOut.OSProfile.Secrets.FirstOrDefault( s => string.Equals(secret.SourceVault.ReferenceUri, s.SourceVault.ReferenceUri));
                    Assert.NotNull(secretOut);

                    // Disabling resharper null-ref check as it doesn't seem to understand the not-null assert above.
                    // ReSharper disable PossibleNullReferenceException

                    Assert.NotNull(secretOut.VaultCertificates);
                    var VaultCertComparer = new VaultCertComparer();
                    Assert.True(secretOut.VaultCertificates.SequenceEqual(secret.VaultCertificates, VaultCertComparer));

                    // ReSharper enable PossibleNullReferenceException
                }
            }

            if (vm.DiagnosticsProfile != null)
            {
                Assert.Equal(vm.DiagnosticsProfile.BootDiagnostics.Enabled, vmOut.DiagnosticsProfile.BootDiagnostics.Enabled);
                Assert.Equal(vm.DiagnosticsProfile.BootDiagnostics.StorageUri, vmOut.DiagnosticsProfile.BootDiagnostics.StorageUri);
            }

            Assert.NotNull(vmOut.AvailabilitySetReference);
            Assert.True(vm.AvailabilitySetReference.ReferenceUri.ToLowerInvariant() == vmOut.AvailabilitySetReference.ReferenceUri.ToLowerInvariant());
            ValidatePlan(vm.Plan, vmOut.Plan);
            // TODO: it's null somtimes.
            //Assert.NotNull(vmOut.Properties.Id);
            //Assert.True(expectedVMReferenceId.ToLowerInvariant() == vmOut.Properties.Id.ToLowerInvariant());
        }
コード例 #26
0
        internal Version GetExtensionVersion(VirtualMachine vm, VirtualMachineInstanceView vmStatus, string osType, string type, string publisher)
        {
            Version version = new Version();
            if (AEMExtensionConstants.AEMExtensionPublisher[osType].Equals(publisher, StringComparison.InvariantCultureIgnoreCase)
                && AEMExtensionConstants.AEMExtensionType[osType].Equals(type, StringComparison.InvariantCultureIgnoreCase))
            {
                version = AEMExtensionConstants.AEMExtensionVersion[osType];
            }
            else if (AEMExtensionConstants.WADExtensionPublisher[osType].Equals(publisher, StringComparison.InvariantCultureIgnoreCase)
                && AEMExtensionConstants.WADExtensionType[osType].Equals(type, StringComparison.InvariantCultureIgnoreCase))
            {
                version = AEMExtensionConstants.WADExtensionVersion[osType];
            }

            if (vm.Resources != null && vmStatus.Extensions != null)
            {
                var extension = vm.Resources.FirstOrDefault(ext =>
                   ext.VirtualMachineExtensionType.Equals(type)
                   && ext.Publisher.Equals(publisher));

                if (extension != null)
                {
                    var extensionStatus = vmStatus.Extensions.FirstOrDefault(ext => ext.Name.Equals(extension.Name));

                    if (extensionStatus != null)
                    {
                        string strExtVersion = extensionStatus.TypeHandlerVersion;
                        Version extVersion;
                        if (Version.TryParse(strExtVersion, out extVersion))
                        {
                            version = extVersion;
                        }
                    }
                }
            }
            return version;
        }
コード例 #27
0
        private EncryptionStatus AreDataVolumesEncrypted(VirtualMachine vmParameters)
        {
            if (vmParameters == null || vmParameters.Resources == null)
            {
                return EncryptionStatus.Unknown;
            }

            OSType osType = this.GetOSType(vmParameters);
            foreach (VirtualMachineExtension vmExtension in vmParameters.Resources)
            {
                switch (osType)
                {
                    case OSType.Windows:
                    case OSType.Linux:
                        if (IsAzureDiskEncryptionExtension(osType, vmExtension))
                        {
                            AzureDiskEncryptionExtensionContext adeExtension = new AzureDiskEncryptionExtensionContext(vmExtension.ToPSVirtualMachineExtension(this.ResourceGroupName, this.VMName));
                            if (DataVolumeInExtensionConfig(adeExtension))
                            {
                                if (adeExtension.EncryptionOperation.Equals(AzureDiskEncryptionExtensionConstants.enableEncryptionOperation, StringComparison.InvariantCultureIgnoreCase))
                                {
                                    if (ExtensionProvisioningSucceeded(adeExtension))
                                    {
                                        return EncryptionStatus.Encrypted;
                                    }
                                }
                            }
                        }
                        break;
                    case OSType.Unknown:
                        return EncryptionStatus.Unknown;
                    default:
                        return EncryptionStatus.Unknown;
                }
            }
            return EncryptionStatus.NotEncrypted;
        }
コード例 #28
0
        private VirtualMachineExtension GetVmExtensionParameters(VirtualMachine vmParameters)
        {
            string SettingString = GetExtensionPublicSettings();
            string ProtectedSettingString = GetExtensionProtectedSettings();

            if (vmParameters == null)
            {
                ThrowTerminatingError(new ErrorRecord(new ApplicationException(string.Format(CultureInfo.CurrentUICulture, "Set-AzureDiskEncryptionExtension can enable encryption only on a VM that was already created ")),
                                                      "InvalidResult",
                                                      ErrorCategory.InvalidResult,
                                                      null));
            }

            VirtualMachineExtension vmExtensionParameters = null;
            if (string.Equals(currentOSType, "Windows", StringComparison.InvariantCultureIgnoreCase))
            {
                this.Name = this.Name ?? AzureDiskEncryptionExtensionContext.ExtensionDefaultName;
                vmExtensionParameters = new VirtualMachineExtension
                {
                    Location = vmParameters.Location,
                    Name = this.Name,
                    Type = VirtualMachineExtensionType,
                    Publisher = AzureDiskEncryptionExtensionContext.ExtensionDefaultPublisher,
                    ExtensionType = AzureDiskEncryptionExtensionContext.ExtensionDefaultName,
                    TypeHandlerVersion = (this.TypeHandlerVersion) ?? AzureDiskEncryptionExtensionContext.ExtensionDefaultVersion,
                    Settings = SettingString,
                    ProtectedSettings = ProtectedSettingString,
                };
            }
            else if (string.Equals(currentOSType, "Linux", StringComparison.InvariantCultureIgnoreCase))
            {
                this.Name = this.Name ?? AzureDiskEncryptionExtensionContext.LinuxExtensionDefaultName;
                vmExtensionParameters = new VirtualMachineExtension
                {
                    Location = vmParameters.Location,
                    Name = this.Name,
                    Type = VirtualMachineExtensionType,
                    Publisher = AzureDiskEncryptionExtensionContext.LinuxExtensionDefaultPublisher,
                    ExtensionType = AzureDiskEncryptionExtensionContext.LinuxExtensionDefaultName,
                    TypeHandlerVersion = (this.TypeHandlerVersion) ?? AzureDiskEncryptionExtensionContext.LinuxExtensionDefaultVersion,
                    Settings = SettingString,
                    ProtectedSettings = ProtectedSettingString,
                };
            }

            return vmExtensionParameters;
        }
コード例 #29
0
        internal VirtualMachineExtensionInstanceView GetExtension(VirtualMachine vm, VirtualMachineInstanceView vmStatus, string type, string publisher)
        {
            var ext = this.GetExtension(vm, type, publisher);
            if (ext == null)
            {
                return null;
            }

            if (vmStatus.Extensions == null)
            {
                return null;
            }
            return vmStatus.Extensions.FirstOrDefault(extSt => extSt.Name.Equals(ext.Name));
        }
コード例 #30
0
        protected VirtualMachine CreateVM_NoAsyncTracking(
            string rgName, string asName, StorageAccount storageAccount, ImageReference imageRef, 
            out VirtualMachine inputVM,
            Action<VirtualMachine> vmCustomizer = null,
            bool createWithPublicIpAddress = false)
        {
            try
            {
                // Create the resource Group, it might have been already created during StorageAccount creation.
                var resourceGroup = m_ResourcesClient.ResourceGroups.CreateOrUpdate(
                    rgName,
                    new ResourceGroup
                    {
                        Location = m_location
                    });

                PublicIpAddressGetResponse getPublicIpAddressResponse = createWithPublicIpAddress ? null : CreatePublicIP(rgName);
                
                SubnetGetResponse subnetResponse = CreateVNET(rgName);

                NetworkInterfaceGetResponse nicResponse = CreateNIC(
                    rgName, 
                    subnetResponse.Subnet, 
                    getPublicIpAddressResponse != null ? getPublicIpAddressResponse.PublicIpAddress : null);

                string asetId = CreateAvailabilitySet(rgName, asName);

                inputVM = CreateDefaultVMInput(rgName, storageAccount.Name, imageRef, asetId, nicResponse.NetworkInterface.Id);
                if (vmCustomizer != null)
                {
                    vmCustomizer(inputVM);
                }

                string expectedVMReferenceId = Helpers.GetVMReferenceId(m_subId, rgName, inputVM.Name);
                var createOrUpdateResponse = m_CrpClient.VirtualMachines.BeginCreatingOrUpdating(
                    rgName, inputVM);

                Assert.True(createOrUpdateResponse.StatusCode == HttpStatusCode.Created);

                Assert.True(createOrUpdateResponse.VirtualMachine.Name == inputVM.Name);
                Assert.True(createOrUpdateResponse.VirtualMachine.Location == inputVM.Location.ToLower().Replace(" ", "") ||
                            createOrUpdateResponse.VirtualMachine.Location.ToLower() == inputVM.Location.ToLower());

                Assert.True(
                    createOrUpdateResponse.VirtualMachine.AvailabilitySetReference.ReferenceUri
                        .ToLowerInvariant() == asetId.ToLowerInvariant());
                ValidateVM(inputVM, createOrUpdateResponse.VirtualMachine, expectedVMReferenceId);

                var operationUri = new Uri(createOrUpdateResponse.AzureAsyncOperation);
                string operationId = operationUri.Segments.LastOrDefault();
                var lroResponse =
                    m_CrpClient.GetLongRunningOperationStatus(createOrUpdateResponse.AzureAsyncOperation.ToString());
                ValidateLROResponse(lroResponse, operationId);

                // CONSIDER dropping this Get and ValidateVM call. Nothing changes in the VM model after it's accepted.
                // There might have been intent to track the async operation to completion and then check the VM is
                // still this and okay, but that's not what the code above does and still doesn't make much sense.
                var getResponse = m_CrpClient.VirtualMachines.Get(rgName, inputVM.Name);
                Assert.True(getResponse.StatusCode == HttpStatusCode.OK);
                ValidateVM(inputVM, getResponse.VirtualMachine, expectedVMReferenceId);
                return getResponse.VirtualMachine;
            }
            catch
            {
                var deleteRg1Response = m_ResourcesClient.ResourceGroups.Delete(rgName);
                Assert.True(deleteRg1Response.StatusCode == HttpStatusCode.OK);
                throw;
            }
        }