/// <summary> /// Inject certificates intot he VM /// </summary> /// <param name="keyVault">Resource Uri to the Azure KeyVault store containing the secrets to inject into the VM</param> public void InjectCertificates(ResourceUri keyVault) { if ((keyVault == null) || (!keyVault.IsValid) || (!keyVault.Is(ResourceUriCompareLevel.Provider, "Microsoft.KeyVault")) || (!keyVault.Is(ResourceUriCompareLevel.Type, "vaults"))) { throw new ArgumentException(nameof(keyVault)); } if (Certificates == null) { Certificates = new List <VMCertificates>(); } // validate if Keyvault is already added string vaultId = keyVault.ToString(); foreach (VMCertificates vault in Certificates) { if (vault.Vault?.ResourceId == vaultId) { throw new ArgumentException($"The vault '{vaultId}' is already injected into this VM."); } } Certificates.Add(new VMCertificates(keyVault)); }
/// <summary> /// Create reference to a source KeyVault /// </summary> /// <param name="vaultUri">ResourceUri to an Azure KeyVault</param> public SourceVault(ResourceUri vaultUri) { if ((vaultUri == null) || (!vaultUri.IsValid) || (!vaultUri.Is(ResourceUriCompareLevel.Provider, "Microsoft.KeyVault")) || (!vaultUri.Is(ResourceUriCompareLevel.Type, "vaults"))) { throw new ArgumentException(nameof(vaultUri)); } KeyVaultResourceId = vaultUri.ToString(); }
/// <summary> /// Initialize the VM certificate store /// </summary> /// <param name="keyVault">Resource Uri to the Azure KeyVault store containing the secrets to inject into the VM</param> public VMCertificates(ResourceUri keyVault) { if ((keyVault == null) || (!keyVault.IsValid) || (!keyVault.Is(ResourceUriCompareLevel.Provider, "Microsoft.KeyVault")) || (!keyVault.Is(ResourceUriCompareLevel.Type, "vaults"))) { throw new ArgumentException(nameof(keyVault)); } Vault = new SubResource(keyVault); Certificates = new List <VMCertificateStoreCertificate>(); }
/// <summary> /// Create a data disk by attaching an unmanaged Vhd /// </summary> /// <param name="name">Name of the disk</param> /// <param name="unmanagedVhdFile">URI to the existing unmanaged Vhd on a Storage Account</param> /// <param name="caching">Type of caching to enable</param> /// <param name="enableWriteAcceleration">Flag indicating whether to enable write acceleration on the disk</param> public static VMOSDisk FromUmanagedVhd(string name, ResourceUri unmanagedVhdFile, CachingTypeNamesEnum caching = CachingTypeNamesEnum.None, bool enableWriteAcceleration = false) { if (string.IsNullOrWhiteSpace(name)) { throw new ArgumentNullException(nameof(name)); } if (!Enum.IsDefined(typeof(CachingTypeNamesEnum), caching)) { throw new ArgumentOutOfRangeException(nameof(caching)); } if ((unmanagedVhdFile == null) || (!unmanagedVhdFile.IsValid) || (!unmanagedVhdFile.Is(ResourceUriCompareLevel.Provider, "Microsoft.Storage")) || (!unmanagedVhdFile.Is(ResourceUriCompareLevel.Type, "storageAccounts"))) { throw new ArgumentException(nameof(unmanagedVhdFile)); } VMOSDisk disk = new VMOSDisk() { Name = name, CreateUsing = DiskCreationOptionsEnum.Copy, VhdFile = new UriResource(unmanagedVhdFile.ToString()), Caching = caching, IsWriteAccelerationEnabled = enableWriteAcceleration }; return(disk); }
/// <summary> /// Stop a web app, or optionally a specific slot of the app /// </summary> /// <param name="bearerToken">Azure bearer token</param> /// <param name="appServiceUri">Resource Uri to the app service</param> /// <param name="slotName">(Optional) Name of the slot to stop -- if unspecified, the entire app is stopped</param> /// <returns>True if the operation was accepted, FALSE if not, NULL if there was a problem</returns> public static async Task <bool?> Stop(string bearerToken, ResourceUri appServiceUri, string?slotName = null) { if (string.IsNullOrWhiteSpace(bearerToken)) { throw new ArgumentNullException(nameof(bearerToken)); } if ((!appServiceUri.IsValid) || (!appServiceUri.Is(ResourceUriCompareLevel.Provider, "Microsoft.Web")) || (!appServiceUri.Is(ResourceUriCompareLevel.Type, "sites"))) { throw new ArgumentException(nameof(appServiceUri)); } string endpoint = "stop"; if (!string.IsNullOrWhiteSpace(slotName)) { endpoint = $"slots/{slotName}/stop"; } RestApiResponse response = await RestApiClient.POST( bearerToken, appServiceUri.ToAbsoluteAzureRMEndpointUri(endpoint), CLIENT_API_VERSION, null, null, new int[] { 200 } ); if (response.WasException) { return(null); } return(response.IsExpectedSuccess); }
/// <summary> /// Remove a virtual machine from the availability set /// </summary> /// <param name="virtualMachine">ResourceUri of the VM to remove</param> public void RemoveVirtualMachine(ResourceUri virtualMachine) { if ((!virtualMachine.Is(ResourceUriCompareLevel.Provider, "Microsoft.Compute")) || (!virtualMachine.Is(ResourceUriCompareLevel.Type, "virtualMachines"))) { throw new ArgumentException($"{nameof(virtualMachine)} does not represent a virtual machine."); } if ((VirtualMachines == null) || (VirtualMachines.Count == 0)) { return; } string resourceUri = virtualMachine.ToString(); SubResource?toRemove = null; foreach (SubResource resource in VirtualMachines) { if (resource.ResourceId.Equals(resourceUri, StringComparison.InvariantCultureIgnoreCase)) { toRemove = resource; break; } } if (toRemove != null) { VirtualMachines.Remove(toRemove); } }
/// <summary> /// Get an instance of a web app /// </summary> /// <param name="bearerToken">Azure bearer token</param> /// <param name="appServiceUri">Resource Uri to the app service</param> /// <param name="slotName">(Optional) Name of the slot to fetch</param> /// <returns>App service or NULL</returns> public static async Task <AppServiceWebApp?> Get(string bearerToken, ResourceUri appServiceUri, string?slotName = null) { if (string.IsNullOrWhiteSpace(bearerToken)) { throw new ArgumentNullException(nameof(bearerToken)); } if ((!appServiceUri.IsValid) || (!appServiceUri.Is(ResourceUriCompareLevel.Provider, "Microsoft.Web")) || (!appServiceUri.Is(ResourceUriCompareLevel.Type, "sites"))) { throw new ArgumentException(nameof(appServiceUri)); } string endpoint = string.Empty; if (!string.IsNullOrWhiteSpace(slotName)) { endpoint = $"slots/{slotName}"; } RestApiResponse response = await RestApiClient.GET( bearerToken, appServiceUri.ToAbsoluteAzureRMEndpointUri(endpoint), CLIENT_API_VERSION, null, null, new int[] { 200, 404 } ); if ((!response.IsExpectedSuccess) || (response.HttpStatus == 404) || response.WasException || string.IsNullOrWhiteSpace(response.Body)) { return(null); } return(JsonConvert.DeserializeObject <AppServiceWebApp>(response.Body)); }
/// <summary> /// Add a virtual machine to the availability set /// </summary> /// <param name="virtualMachine">ResourceUri of the VM to add</param> public void AddVirtualMachine(ResourceUri virtualMachine) { if ((!virtualMachine.Is(ResourceUriCompareLevel.Provider, "Microsoft.Compute")) || (!virtualMachine.Is(ResourceUriCompareLevel.Type, "virtualMachines"))) { throw new ArgumentException($"{nameof(virtualMachine)} does not represent a virtual machine."); } string resourceUri = virtualMachine.ToString(); if (VirtualMachines == null) { VirtualMachines = new List <SubResource>(); } if (VirtualMachines.Count > 0) { foreach (SubResource resource in VirtualMachines) { if (resource.ResourceId.Equals(resourceUri, StringComparison.InvariantCultureIgnoreCase)) { throw new ArgumentException($"A virtual machine with the resource Id '{resourceUri}' is already added to this availability set."); } } } VirtualMachines.Add(new SubResource(resourceUri)); }
/// <summary> /// Issue a certificate /// </summary> /// <param name="bearerToken">The Azure bearer token</param> /// <param name="subscription">Subscription Id for authorization</param> /// <param name="resourceGroupName">Name of the resource group the certificate exists in</param> /// <param name="orderNickname">A nickname for the order, specified during order creation</param> /// <param name="certificateName">A name of the certificate to identify it later</param> /// <param name="keyVaultId">Resource Uri to the KeyVault to hold the private key for the certificate</param> /// <param name="privateKeySecretName">Name of the private key for this certificate in the Azure KeyVault</param> /// <returns>The issued certificate or NULL</returns> public static async Task <IssuedCertificate?> Issue(string bearerToken, Guid subscription, string resourceGroupName, string orderNickname, string certificateName, ResourceUri keyVaultId, string privateKeySecretName) { if (string.IsNullOrWhiteSpace(bearerToken)) { throw new ArgumentNullException(nameof(bearerToken)); } if (subscription == Guid.Empty) { throw new ArgumentNullException(nameof(subscription)); } if (string.IsNullOrWhiteSpace(resourceGroupName)) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (string.IsNullOrWhiteSpace(orderNickname)) { throw new ArgumentNullException(nameof(orderNickname)); } if (string.IsNullOrWhiteSpace(certificateName)) { throw new ArgumentNullException(nameof(certificateName)); } if ((keyVaultId == null) || (!keyVaultId.IsValid) || (!keyVaultId.Is(ResourceUriCompareLevel.Provider, "Microsoft.KeyVault"))) { throw new ArgumentException(nameof(keyVaultId)); } CertificateIssueRequest request = new CertificateIssueRequest() { Kind = "certificates", Location = "global", Properties = new CertificateIssueRequestProperties() { KeyVaultId = keyVaultId.ToString(), KeyVaultSecretName = privateKeySecretName } }; RestApiResponse response = await RestApiClient.PUT( bearerToken, $"https://management.azure.com/subscriptions/{subscription:d}/resourceGroups/{resourceGroupName}/providers/Microsoft.CertificateRegistration/certificateOrders/{orderNickname}/certificates/{certificateName}", CLIENT_API_VERSION, null, request, new int[] { 200, 201 } ); if ((!response.IsExpectedSuccess) || response.WasException || string.IsNullOrWhiteSpace(response.Body)) { return(null); } return(JsonConvert.DeserializeObject <IssuedCertificate>(response.Body)); }
/// <summary> /// Enable boot diagnostics /// </summary> /// <param name="storageAccountBlobUri">Uri to a Azure Storage Blob account where the diagnostics information should be stored.</param> public VMBootDiagnostics(ResourceUri storageAccountBlobUri) { if ((storageAccountBlobUri == null) || (!storageAccountBlobUri.IsValid) || (!storageAccountBlobUri.Is(ResourceUriCompareLevel.Provider, "Microsoft.Storage")) || (!storageAccountBlobUri.Is(ResourceUriCompareLevel.Type, "storageAccounts"))) { throw new ArgumentException(nameof(storageAccountBlobUri)); } IsEnabled = true; StorageUri = storageAccountBlobUri.ToString(); }
/// <summary> /// Create a disk by copying from a VM snapshot /// </summary> /// <param name="sourceSnapshotUri">ResourceUri to the VM's snapshot that is to be copied as a new disk</param> /// <returns>Disk creation metadata</returns> public static DiskCreationMetadata ViaCopy(ResourceUri sourceSnapshotUri) { if ((sourceSnapshotUri == null) || (!sourceSnapshotUri.IsValid) || (!sourceSnapshotUri.Is(ResourceUriCompareLevel.Provider, "Microsoft.Compute")) || (!sourceSnapshotUri.Is(ResourceUriCompareLevel.Type, "snapshots"))) { throw new ArgumentException(nameof(sourceSnapshotUri)); } return(new DiskCreationMetadata() { CreationMode = DiskCreationOptionsEnum.Copy, SourceSnapshotOrDiskResourceId = sourceSnapshotUri.ToString() }); }
/// <summary> /// Use the app service plan. Note that this cannot be changed after the app /// has been created /// </summary> public AppServiceWebAppProperties WithAppServicePlan(ResourceUri appServicePlan) { if (!string.IsNullOrWhiteSpace(PlanResourceId)) { throw new InvalidOperationException($"App is already bound to the app service plan '{PlanResourceId}'."); } if ((!appServicePlan.IsValid) || (!appServicePlan.Is(ResourceUriCompareLevel.Provider, "Microsoft.Web")) || (!appServicePlan.Is(ResourceUriCompareLevel.Type, "serverfarms"))) { throw new ArgumentNullException(); } PlanResourceId = appServicePlan.ToString(); return(this); }
/// <summary> /// Initialize properties for data disk encryption /// </summary> /// <param name="type">Type of encryption</param> /// <param name="encryptionSetId">ResourceUri to the Azure Disk Encryption Set to be used</param> public DiskDataEncryptionProperties(DiskDataEncryptionTypeNamesEnum type, ResourceUri encryptionSetId) { if (!Enum.IsDefined(typeof(DiskDataEncryptionTypeNamesEnum), type)) { throw new ArgumentOutOfRangeException(nameof(type)); } if ((encryptionSetId == null) || (!encryptionSetId.IsValid) || (!encryptionSetId.Is(ResourceUriCompareLevel.Provider, "Microsoft.Compute")) || (!encryptionSetId.Is(ResourceUriCompareLevel.Type, "diskEncryptionSets"))) { throw new ArgumentException(nameof(encryptionSetId)); } Type = type; EncryptionSetResourceId = encryptionSetId.ToString(); }
/// <summary> /// Create a property pointing to an active key /// </summary> /// <param name="keyVaultUri">The Resource Uri to the KeyVault where the key is interned</param> /// <param name="keyVaultKeyUri">The absolute Uri to the key in the KeyVault</param> public DiskEncryptionSetProperties(ResourceUri keyVaultUri, string keyVaultKeyUri) { if ((!keyVaultUri.IsValid) || (!keyVaultUri.Is(ResourceUriCompareLevel.Provider, "Microsoft.KeyVault")) || (!keyVaultUri.Is(ResourceUriCompareLevel.Type, "vaults"))) { throw new ArgumentException(nameof(keyVaultUri)); } ActiveKey = new KeyVaultAndKeyReference() { Vault = new SourceVault() { KeyVaultResourceId = keyVaultUri.ToString() }, KeyUrl = keyVaultKeyUri }; }
/// <summary> /// Create a data disk by attaching an managed disk /// </summary> /// <param name="name">Name of the disk</param> /// <param name="managedDiskUri">URI to the existing unmanaged Vhd on a Storage Account</param> /// <param name="caching">Type of caching to enable</param> /// <param name="enableWriteAcceleration">Flag indicating whether to enable write acceleration on the disk</param> /// <param name="attachToLUN">The LUN to attach the disk to. Set to -1 to automatically pick a LUN (Azure will decide)</param> public static VMDataDisk FromManagedDisk(string name, ResourceUri managedDiskUri, DiskSkuNamesEnum typeOfDisk = DiskSkuNamesEnum.Standard_LRS, CachingTypeNamesEnum caching = CachingTypeNamesEnum.None, bool enableWriteAcceleration = false, int attachToLUN = -1) { if (string.IsNullOrWhiteSpace(name)) { throw new ArgumentNullException(nameof(name)); } if (!Enum.IsDefined(typeof(CachingTypeNamesEnum), caching)) { throw new ArgumentOutOfRangeException(nameof(caching)); } if (!Enum.IsDefined(typeof(DiskSkuNamesEnum), typeOfDisk)) { throw new ArgumentOutOfRangeException(nameof(typeOfDisk)); } if (attachToLUN < -1) { throw new ArgumentOutOfRangeException(nameof(attachToLUN)); } if ((managedDiskUri == null) || (!managedDiskUri.IsValid) || (!managedDiskUri.Is(ResourceUriCompareLevel.Provider, "Microsoft.Storage")) || (!managedDiskUri.Is(ResourceUriCompareLevel.Type, "storageAccounts"))) { throw new ArgumentException(nameof(managedDiskUri)); } VMDataDisk disk = new VMDataDisk() { Name = name, CreateUsing = DiskCreationOptionsEnum.Attach, ManagedDisk = new VMManagedDisk() { Id = managedDiskUri.ToString(), Type = typeOfDisk }, Caching = caching, IsWriteAccelerationEnabled = enableWriteAcceleration }; if (attachToLUN != -1) { disk.LogicalUnitNumber = attachToLUN; } return(disk); }
/// <summary> /// Create a disk by importing an unmanaged disk's blob /// </summary> /// <param name="storageAccountUri">ResourceUri to the storage account containing the umanaged blob</param> /// <param name="vhdUri">Absolute Uri to the .vhd file</param> /// <returns>Disk creation metadata</returns> public static DiskCreationMetadata ViaImportUnmanagedDiskBlob(ResourceUri storageAccountUri, string vhdUri) { if ((storageAccountUri == null) || (!storageAccountUri.IsValid) || (!storageAccountUri.Is(ResourceUriCompareLevel.Provider, "Microsoft.Storage")) || (!storageAccountUri.Is(ResourceUriCompareLevel.Type, "storageAccounts"))) { throw new ArgumentException(nameof(storageAccountUri)); } if ((!Uri.IsWellFormedUriString(vhdUri, UriKind.Absolute)) || (!vhdUri.EndsWith(".vhd", StringComparison.InvariantCultureIgnoreCase))) { throw new ArgumentException(nameof(vhdUri)); } return(new DiskCreationMetadata() { CreationMode = DiskCreationOptionsEnum.Import, SourceBlobStorageAccountId = storageAccountUri.ToString(), SourceBlobUri = vhdUri }); }
/// <summary> /// Restart a web app, or optionally a specific slot of the app /// </summary> /// <param name="bearerToken">Azure bearer token</param> /// <param name="appServiceUri">Resource Uri to the app service</param> /// <param name="slotName">(Optional) Name of the slot to restart -- if unspecified, the entire app is restarted</param> /// <param name="isSoftRestart">If true, performs a soft-restart, otherwise app is reprovisioned</param> /// <param name="blockTillRestarted">If true, call returns only after the app has been restarted</param> /// <returns>True if the operation was accepted, FALSE if not, NULL if there was a problem</returns> public static async Task <bool?> Restart(string bearerToken, ResourceUri appServiceUri, string?slotName = null, bool isSoftRestart = true, bool blockTillRestarted = false) { if (string.IsNullOrWhiteSpace(bearerToken)) { throw new ArgumentNullException(nameof(bearerToken)); } if ((!appServiceUri.IsValid) || (!appServiceUri.Is(ResourceUriCompareLevel.Provider, "Microsoft.Web")) || (!appServiceUri.Is(ResourceUriCompareLevel.Type, "sites"))) { throw new ArgumentException(nameof(appServiceUri)); } string endpoint = "restart"; if (!string.IsNullOrWhiteSpace(slotName)) { endpoint = $"slots/{slotName}/restart"; } RestApiResponse response = await RestApiClient.POST( bearerToken, appServiceUri.ToAbsoluteAzureRMEndpointUri(endpoint), CLIENT_API_VERSION, new Dictionary <string, string>() { { "softRestart", (isSoftRestart ? "true" : "false") }, { "synchronous", (blockTillRestarted ? "true" : "false") } }, null, new int[] { 200 } ); if (response.WasException) { return(null); } return(response.IsExpectedSuccess); }
/// <summary> /// Create a data disk by copying an existing image /// </summary> /// <param name="name">Name of the disk</param> /// <param name="fromImage">URI to the Vhd's blob on a Storage Account</param> /// <param name="caching">Type of caching to enable</param> /// <param name="enableWriteAcceleration">Flag indicating whether to enable write acceleration on the disk</param> /// <param name="attachToLUN">The LUN to attach the disk to. Set to -1 to automatically pick a LUN (Azure will decide)</param> public static VMDataDisk FromImage(string name, ResourceUri fromImage, CachingTypeNamesEnum caching = CachingTypeNamesEnum.None, bool enableWriteAcceleration = false, int attachToLUN = -1) { if (string.IsNullOrWhiteSpace(name)) { throw new ArgumentNullException(nameof(name)); } if (!Enum.IsDefined(typeof(CachingTypeNamesEnum), caching)) { throw new ArgumentOutOfRangeException(nameof(caching)); } if (attachToLUN < -1) { throw new ArgumentOutOfRangeException(nameof(attachToLUN)); } if ((fromImage == null) || (!fromImage.IsValid) || (!fromImage.Is(ResourceUriCompareLevel.Provider, "Microsoft.Storage")) || (!fromImage.Is(ResourceUriCompareLevel.Type, "storageAccounts"))) { throw new ArgumentException(nameof(fromImage)); } VMDataDisk disk = new VMDataDisk() { Name = name, CreateUsing = DiskCreationOptionsEnum.FromImage, CreateModeSourceImage = new UriResource(fromImage.ToString()), Caching = caching, IsWriteAccelerationEnabled = enableWriteAcceleration }; if (attachToLUN != -1) { disk.LogicalUnitNumber = attachToLUN; } return(disk); }