I need to Specify OS Disk Name while Creating Azure VMSS using PowerShell - azure

I want to Specify OS Disk Name while Creating VMSS using PowerShell to overcome the random OS Disk name like "VMSSNAME_1686_disk1_b5f021da0ba7409fbe7d028bdd50".
Command :
Set-AzVmssStorageProfile $vmssConfig `
-OsDiskCreateOption "FromImage" `
-ImageReferenceId $galleryImage.Id -OsDiskName $OSDiskName
# Set up information for authenticating with the virtual machine
Set-AzVmssOsProfile $vmssConfig `
-AdminUsername $username `
-AdminPassword $Password `
-ComputerNamePrefix "UKSSPAG"
# Attach the virtual network to the config object
Add-AzVmssNetworkInterfaceConfiguration -VirtualMachineScaleSet $vmssConfig -Name "NICConfig" -Primary $true -IPConfiguration $ipConfig
# Create the scale set with the config object (this step might take a few minutes)
New-AzVmss -ResourceGroupName $resourceGroup -VMScaleSetName $scaleSetName -VirtualMachineScaleSet $vmssConfig
Error :
New-AzVmss : Parameter 'osDisk.name' is not allowed.
ErrorCode: InvalidParameter
ErrorMessage: Parameter 'osDisk.name' is not allowed.
ErrorTarget: osDisk.name
StatusCode: 400
ReasonPhrase: Bad Request
OperationID : e97450a3-ed89-46f8-84fa-6779a002a3e9
At line:1 char:1
+ New-AzVmss -ResourceGroupName $resourceGroup -VMScaleSetName $scaleSe ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [New-AzVmss], ComputeCloudException
+ FullyQualifiedErrorId : Microsoft.Azure.Commands.Compute.Automation.NewAzureRmVmss

Related

Disk not found error when trying to create a VM from a saved disk

I am getting a disk not found error when trying to create a VM from a saved disk.
I can go on the azure portal and see the disk, so it is there.
here is relevant code:
$vmConfig = New-AzVMConfig -VMName $vmName -VMSize "Standard_A2"
$vm = Add-AzVMNetworkInterface -VM $vmConfig -Id $nic.Id
$vm = Set-AzVMOSDisk -VM $vm -ManagedDiskId $disk.Id -StorageAccountType Standard_LRS `
-DiskSizeInGB 128 -CreateOption Attach -Windows
New-AzVM -ResourceGroupName $ResourceGroupName -Location $LocationName -VM $vm #FAILS HERE
Here is the error:
New-AzVM : Disk python3disk20210616a is not found.
ErrorCode: NotFound
ErrorMessage: Disk python3disk20210616a is not found.
ErrorTarget: /subscriptions/XXXXXXXXXXXXXXXXXXXXXXXXX/resourceGroups/rg-comphydro/providers/Microsoft.Compute/disks/python3disk20210616a
StatusCode: 404
ReasonPhrase: Not Found
OperationID : 3fe239be-5af4-4231-aaec-b77e9cd77fb7
At line:1 char:1
+ New-AzVM -ResourceGroupName $ResourceGroupName -Location $LocationNam ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [New-AzVM], ComputeCloudException
+ FullyQualifiedErrorId : Microsoft.Azure.Commands.Compute.NewAzureVMCommand
if I print $disk, this is what is displayed:
ResourceGroupName : rg-comphydro
ManagedBy :
ManagedByExtended : {}
Sku : Microsoft.Azure.Management.Compute.Models.DiskSku
Zones :
TimeCreated : 6/16/2021 4:20:06 PM
OsType : Windows
HyperVGeneration : V1
CreationData : Microsoft.Azure.Management.Compute.Models.CreationData
DiskSizeGB : 128
DiskSizeBytes : 137438953472
UniqueId : 085da610-953d-4f9c-8303-ad4b2b7e7e50
EncryptionSettingsCollection :
ProvisioningState : Succeeded
DiskIOPSReadWrite : 500
DiskMBpsReadWrite : 60
DiskIOPSReadOnly :
DiskMBpsReadOnly :
DiskState : Unattached
Encryption : Microsoft.Azure.Management.Compute.Models.Encryption
MaxShares :
ShareInfo : {}
Id : /subscriptions/XXXXXXX/resourceGroups/rg-comphydro/providers/Microsoft.Compute/disks/py
thon3disk20210616a
Name : python3disk20210616a
Type : Microsoft.Compute/disks
Location : northcentralus
Tags : {}
NetworkAccessPolicy : AllowAll
DiskAccessId :
Tier :
BurstingEnabled :
I have successfully created the virtual machine from PowerShell by using the below list of commands
$resourceGroupName = "resourcegroupName"
$location = "westus"
$vmName = "name of the VM"
$disk= Get-AzDisk -ResourceGroupName $resourceGroupName -DiskName "diskname"
$nic= Get-AzNetworkInterface -ResourceGroupName $resourceGroupName -Name "Networkinterfacename"
$vmConfig = New-AzVMConfig -VMName $vmName -VMSize "Standard_D2s_v3"
$vm = Add-AzVMNetworkInterface -VM $vmConfig -Id $nic.Id
$vm = Set-AzVMOSDisk -VM $vm -ManagedDiskId $disk.Id -StorageAccountType Standard_LRS -DiskSizeInGB 128 -CreateOption Attach -Windows
New-AzVM -ResourceGroupName $resourceGroupName -Location $location -VM $vm

Availability Set in Availability Zone Arm Configuration

I'm trying to build out a script which deploys a vm into an availability set within an Azure availability zone.
However I keep getting the following error. I think (guessing) that it's to do with the fact the av set is not deployed to the same zone as the vm, but cannot find anywhere to set the zone on the availability set.
Error:
New-AzResourceGroupDeployment : 22:41:38 - Error: Code=InvalidRequestContent; Message=The request content was invalid and could not be deserialized: 'Could not find member 'zone' on
object of type 'TemplateResource'. Path 'properties.template.resources[3].zone', line 217, position 17.'.
At C:\ps\test-vm-build.ps1:182 char:7
+ New-AzResourceGroupDeployment -Name "SapTestDeploy" -ResourceGr ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [New-AzResourceGroupDeployment], Exception
+ FullyQualifiedErrorId : Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation.NewAzureResourceGroupDeploymentCmdlet
The ARM template has been uploaded to:
https://pastebin.com/embed_js/5Afn6Pip
Hoping someone has ome across this and can point me in the right direction, Thanks in advance :)
Create an availability set:
New-AzAvailabilitySet `
-Location "EastUS" `
-Name "myAvailabilitySet" `
-ResourceGroupName "myResourceGroupAvailability" `
-Sku aligned `
-PlatformFaultDomainCount 2 `
-PlatformUpdateDomainCount 2
Create a Virtual Machine inside the availability set:
New-AzVm `
-ResourceGroupName "myResourceGroupAvailability" `
-Name "myVM$i" `
-Location "East US" `
-VirtualNetworkName "myVnet" `
-SubnetName "mySubnet" `
-SecurityGroupName "myNetworkSecurityGroup" `
-PublicIpAddressName "myPublicIpAddress$i" `
-AvailabilitySetName "myAvailabilitySet" `
-Credential $cred
UPDATE (Location/UpdateDomain/FaultDomain):
New-AzAvailabilitySet
[-ResourceGroupName] <String>
[-Name] <String>
[-Location] <String>
[[-PlatformUpdateDomainCount] <Int32>]
[[-PlatformFaultDomainCount] <Int32>]
[[-Sku] <String>]
[-ProximityPlacementGroupId <String>]
[-Tag <Hashtable>]
[-AsJob]
[-DefaultProfile <IAzureContextContainer>]
[<CommonParameters>]
UPDATE:
Powershell to move a VM to an Availability Zone:
https://github.com/kpantos/azure-automation/blob/master/powershell/change-vm-zone.ps1

Set-AzVMCustomScriptExtension in catch?

Attempting to add an extension when not detected but keep failing to find the secret sauce to get this to work. Mind you I am a BASH guy and this is a first foray into PowerShell..
#requires -version 2
# Required parameter $subscription: name of the subscription to enable Custom Script Extensions in
param (
# NOTE: See below for reason...
# [Parameter(Mandatory = $true)] [String] $subscription
# NOTE: Prompting is great for using the script interactively, but if this will also be executed
# from a build server or ...
# NOTE: Once the parameter is marked as mandatory PowerShell it will prompt for value. That said,
# if you remove the mandatory attribute then you can set a default value as a T_THROW ...
# NOTE: This _does_ contain shortcomings if this will be used as a pipeline param ...
# https://stackoverflow.com/questions/33600279/is-it-possible-to-force-powershell-script-to-throw-if-a-required-pipeline-para
[Parameter()]
[ValidateNotNullOrEmpty()]
[String]$SubscriptionName=$(Throw "`SubscriptionName` is mandatory, please provide a value...")
)
# Connect to the current Azure account
Write-Output "Pulling Azure account credentials..."
Start-Process "https://microsoft.com/devicelogin" # steals focus...
# Login to Azure account
Connect-AzAccount
# Set the active subscription
$null = Get-AzSubscription -SubscriptionName "$SubscriptionName" |Set-AzContext
# TODO: error handling
$vms = Get-AzVM
$cseName = "VulnerabilityManagementTools"
ForEach ($vm in $vms) {
try {
$cseStatus = Get-AzVMCustomScriptExtension `
-ResourceGroupName $vm.ResourceGroupName `
-VMName $vm.Name `
-Name $cseName `
-Status
}
catch {
Write-Output "Enabling Custom Script Extension for $vm."
Set-AzVMCustomScriptExtension `
-ResourceGroupName $vm.ResourceGroup `
-Location $vm.Location `
-VMName $vm.Name `
-Name $cseName `
-TypeHandlerVersion "1.1" `
-StorageAccountName "VulnerabilityManagementTools" `
-FileName "VulnerabilityManagementInstaller.ps1" `
-ContainerName "VulnerabilityManagementTools"
}
}
End up err'ing out with
PS /.../automation-scripts> ./EnableCustomScriptExtension.ps1 SubscriptionName
Pulling Azure account credentials...
WARNING: To sign in, use a web browser to open the page https://microsoft.com/devicelogin and enter the code XXXXXX to authenticate.
Account SubscriptionName TenantId Environment
------- ---------------- -------- -----------
XXXX#analytics.com SubName XXXXXX-XXXX AzureCloud
Get-AzVMCustomScriptExtension : The Resource 'Microsoft.Compute/virtualMachines/XXXX/extensions/VulnerabilityManagementTools' under resource group '{NAME}' was not found.
ErrorCode: ResourceNotFound
ErrorMessage: The Resource 'Microsoft.Compute/virtualMachines/XXXX/extensions/VulnerabilityManagementTools' under resource group '{NAME}' was not found.
ErrorTarget:
StatusCode: 404
ReasonPhrase: Not Found
At /.../automation-scripts/EnableCustomScriptExtension.ps1:59 char:18
+ $cseStatus = Get-AzVMCustomScriptExtension `
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [Get-AzVMCustomScriptExtension], ComputeCloudException
+ FullyQualifiedErrorId : Microsoft.Azure.Commands.Compute.GetAzureVMCustomScriptExtensionCommand
Get-AzVMCustomScriptExtension : The Resource 'Microsoft.Compute/virtualMachines/XXXXX/extensions/VulnerabilityManagementTools' under resource group '{RESOURCE_GROUPNAME}' was not found.
ErrorCode: ResourceNotFound
ErrorMessage: The Resource 'Microsoft.Compute/virtualMachines/XXXX/extensions/VulnerabilityManagementTools' under resource group '{RESOURCE_GROUPNAME}' was not found.
ErrorTarget:
StatusCode: 404
ReasonPhrase: Not Found
At /.../automation-scripts/EnableCustomScriptExtension.ps1:59 char:18
+ $cseStatus = Get-AzVMCustomScriptExtension `
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [Get-AzVMCustomScriptExtension], ComputeCloudException
+ FullyQualifiedErrorId : Microsoft.Azure.Commands.Compute.GetAzureVMCustomScriptExtensionCommand
Get-AzVMCustomScriptExtension : The Resource 'Microsoft.Compute/virtualMachines/{VMName}/extensions/VulnerabilityManagementTools' under resource group '{RESOURCEX_GROUPNAME}' was not found.
ErrorCode: ResourceNotFound
ErrorMessage: The Resource 'Microsoft.Compute/virtualMachines/{VMName}/extensions/VulnerabilityManagementTools' under resource group '{RESOURCEX_GROUPNAME}' was not found.
ErrorTarget:
StatusCode: 404
ReasonPhrase: Not Found
At /.../automation-scripts/EnableCustomScriptExtension.ps1:59 char:18
+ $cseStatus = Get-AzVMCustomScriptExtension `
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [Get-AzVMCustomScriptExtension], ComputeCloudException
+ FullyQualifiedErrorId : Microsoft.Azure.Commands.Compute.GetAzureVMCustomScriptExtensionCommand`
In your case, you just need to use the if(){}else{} statement, try the script as below instead of the ForEach part of yours, it works fine on my side.
ForEach ($vm in $vms) {
$cseStatus = Get-AzVMCustomScriptExtension `
-ResourceGroupName $vm.ResourceGroupName `
-VMName $vm.Name `
-Name $cseName `
-Status `
-ErrorAction SilentlyContinue
if ($cseStatus){
Write-Host "The extension has been set for" $vm.Name
}else{
Write-Host "Enabling Custom Script Extension for" $vm.Name
Set-AzVMCustomScriptExtension `
-ResourceGroupName $vm.ResourceGroup `
-Location $vm.Location `
-VMName $vm.Name `
-Name $cseName `
-TypeHandlerVersion "1.1" `
-StorageAccountName "VulnerabilityManagementTools" `
-FileName "VulnerabilityManagementInstaller.ps1" `
-ContainerName "VulnerabilityManagementTools"
}
}
Test result:
You'll need to create an Azure AD Service Principal using password authentication and use the credentials of this to pass to the Connect-AzAccount cmdlet as follows:
$credentials = Get-Credential
Connect-AzAccount -ServicePrincipal -Credentials $credentials
The service account will need to have the necessary permissions to use the Set-AzVMCustomScriptExtensions cmdlet.
More information on creating the service account here:
https://learn.microsoft.com/en-us/powershell/azure/create-azure-service-principal-azureps?view=azps-2.8.0

Why am i getting "New-AzSqlDatabaseImport : Not found: Entity not found to invoke import"

I have a script to handle some parameters and deploy an arm template with those parameters, and then create a database using a bacpac file in my storage account. When my script is trying to invoke the cmdlet "New-AzSqlDatabaseImport" i'm getting "NotFound: Entity not found to invoke import"
I have trying updating all of my Az modules, and tried to run the cmdlet manually and fill in the parameters manually.
Write-Host "Creating database and importing data"
$bloblink = (Get-AzStorageAccount -ResourceGroupName $ResourceGroup -Name $StorageName).PrimaryEndpoints.Blob
$uri = $bloblink + $containerName + "/" + $bacpacFile
$importRequest = New-AzSqlDatabaseImport `
-ResourceGroupName $ResourceGroup `
-ServerName $SQLServer `
-DatabaseName $database_ql_name `
-DatabaseMaxSizeBytes $databaseMaxSizeBytes `
-StorageKeyType "StorageAccessKey" `
-StorageKey $(Get-AzStorageAccountKey -ResourceGroupName $ResourceGroup -StorageAccountName $StorageName).Value[0] `
-StorageUri $uri `
-Edition $DatabaseEdition `
-ServiceObjectiveName $DatabaseSize `
-AdministratorLogin $dbUsername `
-AdministratorLoginPassword $dbPassword
I expect it to start a job on Azure to create the database and start the import job.
This is the error im getting instead (i replaced the full path).
At *PATH*/Deployment.ps1:262 char:18
+ $importRequest = New-AzSqlDatabaseImport `
+ ~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [New-AzSqlDatabaseImport], CloudException
+ FullyQualifiedErrorId : Microsoft.Azure.Commands.Sql.ImportExport.Cmdlet.NewAzureSqlDatabaseImport
I just encountered the same error. I found that the -ServerName argument is case-sensitive. So check your $SQLServer-variable.

Why is the ID for a subnet created using Azure Resource Manager Powershell cmdlets null?

I am trying to provision some network resources in Azure and I am running into a blocker with a step that tries to reference a previously created subnet's Id property.
Here's the command to retrieve the subnet details:
$gwsubnet = Get-AzureRmVirtualNetworkSubnetConfig -Name 'GatewaySubnet' -VirtualNetwork $vnet
And then outputting the value of $gwsubnet in the console:
Name : GatewaySubnet
Id :
Etag :
ProvisioningState :
AddressPrefix : 10.1.1.0/24
IpConfigurations : null
NetworkSecurityGroup : null
RouteTable : null
Note that the Id property is null. This causes an error for a future step, e.g.:
$gwipconfig = New-AzureRmVirtualNetworkGatewayIpConfig -Name config1 -SubnetId $gwsubnet.Id -PublicIpAddressId $gwpip.Id
Gives the following error:
New-AzureRmVirtualNetworkGatewayIpConfig : Cannot validate argument on parameter 'SubnetId'. The argument is null or empty. Supply an argument that is not null or empty and then try the
command again.
At line:1 char:99
+ ... nfig -SubnetId $gwsubnet.Id -PublicIpAddressId $gwpip.Id
+ ~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [New-AzureRmVirtualNetworkGatewayIpConfig], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.Azure.Commands.Network.NewAzureVirtualNetworkGatewayIpConfigCommand
I'm struggling with how to have my subnet have an Id assigned to it. Is this something that I need to logout/login again to see? thanks for the help.
The problem you are having is that the subnet Id isn't created until you have created the virtual network.
When you run Get-AzureRmVirtualNetworkSubnetConfig all you create is a configuration to attach to New-AzureRmVirtualNetwork Once you have run that command it will connect to Azure, deploy the Vnet, create the subnet and at that state it will create a subnet Id.
The following code will show you what I mean...
$DNSNameLabel = "mydnsname"
$NetworkName = "MyNet"
$NICName = "MyNIC"
$PublicIPAddressName = "MyPIP"
$SubnetName = "MySubnet"
$SubnetAddressPrefix = "10.0.0.0/24"
$VnetAddressPrefix = "10.0.0.0/16"
$SingleSubnet = New-AzureRmVirtualNetworkSubnetConfig `
-Name $SubnetName `
-AddressPrefix $SubnetAddressPrefix
#At this point nothing is created, so there is no valid subnet id
$Vnet = New-AzureRmVirtualNetwork -Name $NetworkName `
-ResourceGroupName $ResourceGroupName `
-Location $LocationName `
-AddressPrefix $VnetAddressPrefix `
-Subnet $SingleSubnet
#vnet and subnet are created, both get an id and etag
$vnet = Get-AzureRmVirtualNetwork -Name $NetworkName
-ResourceGroupName $ResourceGroupName
$vnet.Subnets[0].Id
Which will give
/subscriptions/{Subscription ID}/resourceGroups/MyResourceGroup/providers/Microsoft.Network/virtualNetworks/MyNet/subnets/MySubnet

Resources