Create VM in Azure with powershell with no public IP - azure

I'm creating VM on Azure from an Image using powershell.
This is the script I'm using .
$UserName = "username"
$Password = ConvertTo-SecureString "password#123" -AsPlainText -Force
$psCred = New-Object System.Management.Automation.PSCredential($UserName, $Password)
New-AzureRmVm `
-ResourceGroupName "RSG" `
-Name "VMName" `
-ImageName "ImageName" `
-Location "West US" `
-VirtualNetworkName "VNName" `
-SubnetName "default" `
-Credential $psCred
-PublicIpAddressName "None" `
-OpenPorts 3389
But, when I got into the Azure portal and see, some Public Ip is getting assigned by default. I have also tried without giving PublicIpAddressName property assuming , it wont assign any IP, but still it is assigning.
I want the Public IP to be none.Can anyone help me achieve this.Thanks!

Currently this an issue which is still in Open state on official azure-powershell github. You can refer it here . Incase if you still want to bypass this you can try using New-AzureReservedIP or after the deployment command try to remove the public ip by yourself Remove-AzureRmPublicIpAddress.
Note : I have'nt tested it yet. Just an idea.
Refer : Docs

To set no public ip address you have can just define it as "" , in powershell you will need to quote that again so it will be """" .

If you are using PowerShell, then you will need to escape all empty parameters by changing "" to '""' to properly pass an empty string into the command. Without this, PowerShell will not pass the empty string, and you will get an error from the command indicating it's missing a parameter.

$winVmCred = Get-Credential `
-Message "Enter username and password for the Windows management virtual machine."
# Create a NIC for the VM.
$winVmNic = New-AzNetworkInterface -Name "winVMNIC01" `
-ResourceGroupName $resourceGroup.ResourceGroupName `
-Location $location `
-SubnetId $targetVMSubnet.Id `
-PrivateIpAddress "10.10.12.10"
# Configure the Windows management VM.
$winVmConfig = New-AzVMConfig -VMName $winVmName -VMSize $winVmSize | `
Set-AzVMOperatingSystem -Windows -ComputerName $winVmName -Credential $winVmCred | `
Set-AzVMSourceImage -PublisherName $winVmPublisher `
-Offer $winVmOffer `
-Skus $winVmSku `
-Version $winVmVersion | `
Add-AzVMNetworkInterface -Id $winVmNic.Id
# Create the VM.
$winVM = New-AzVM -ResourceGroupName $resourceGroup.ResourceGroupName `
-Location $location `
-VM $winVmConfig `
-ErrorAction Stop

Related

When I create a new VM using Azure Powershell I get no public IP Address. Why?

I just started playing around with Azure Powershell and I'm trying to create a new Azure VM.
Script:
$username = 'demoadmin'
$password = ConvertTo-SecureString 'Password123!##' -AsPlainText -Force
$WindowsCred = New-Object System.Management.Automation.PSCredential ($username, $password)
New-AzVM -ResourceGroup 'psdemo-rg-uksouth' -Name 'psdemo-win-az' -Image 'win2016datacenter' -Size 'Standard_D2ads_v5' -Credential $WindowsCred -OpenPorts 3389
Result: Azure VM is successfully created, but there is no Public IP address assigned.
Looking at the documentation here I can see the description for parameter "PublicIpAddressName": "The name of a new (or existing) public IP address for the created VM to use. If not specified, a name will be generated.".
How can I make it assign a Public IP Address on creation?
When I run the PowerShell commands you provided, yes - it is not provisioned the Public IP address, but it will be assigned the Private IP Address by Azure dynamically.
If you do not pass the PublicIpAddressName parameter, then it will not be created automatically:
Following these MSFT Doc1 & Doc 2, we have to pass the Public IP Address parameter to get assigned to the associated Virtual Machine by Azure.
PowerShell Script I used to get the Public IP Address while VM Creation in Azure:
#Create the Virtual Network
$vnet = #{
Name = 'myVNet'
ResourceGroupName = 'HariTestRg'
Location = 'EastUS'
AddressPrefix = '10.0.0.0/16'
}
$virtualNetwork = New-AzVirtualNetwork #vnet
#Create the Subnet
$subnet = #{
Name = 'default'
VirtualNetwork = $virtualNetwork
AddressPrefix = '10.0.0.0/24'
}
$subnetConfig = Add-AzVirtualNetworkSubnetConfig #subnet
$virtualNetwork | Set-AzVirtualNetwork
#Create the Virtual Machine by passing the Public IP Address parameter
$username = '<your-user-name>'
$password = ConvertTo-SecureString '<your-password>' -AsPlainText -Force
$WindowsCred = New-Object System.Management.Automation.PSCredential ($username, $password)
New-AzVm `
-ResourceGroupName "HariTestRg" `
-Name "psdemo-win-az02" `
-Location "EastUS" `
-VirtualNetworkName "myVnet" `
-SubnetName "default" `
-SecurityGroupName "myNetworkSecurityGroup" `
-PublicIpAddressName "myPublicIpAddress2" `
-ImageName "MicrosoftWindowsServer:WindowsServer:2016-Datacenter-with-Containers:latest" `
-Credential $WindowsCred
Result:

Deploying multiple scripts with CustomScriptExtension on an Azure Windows VM

I'm trying to deploy multiple PowerShell scripts to an Azure Windows VM by using the CustomScriptExtension.
The scripts are independent from each other so the order of their deployment doesn't matter. Also the scripts are in same blob container.
I have already a working template as below for installing one script at the moment:
$resourceGroup = "myResourceGroup"
$vmName = "myVM"
$location = "easteurope"
$storageAcctName = "myStorageAcct"
$storageKey = $env:ARM_ACCESS_KEY
$fileUri = #("https://xxxxx.blob.core.windows.net/xxxx/01-installTools.ps1")
$protectedSettings = #{"storageAccountName" = $storageAcctName; "storageAccountKey" = $storageKey};
$settings = #{"fileUris" = $fileUri;"commandToExecute" ="powershell -ExecutionPolicy Unrestricted -File 01-installTools.ps1"};
#run command
Set-AzVMExtension -ResourceGroupName $resourceGroup `
-Location $location `
-ExtensionName "IIS" `
-VMName $vmName `
-Publisher "Microsoft.Compute" `
-ExtensionType "CustomScriptExtension" `
-TypeHandlerVersion "1.8" `
-Settings $settings `
-ProtectedSettings $protectedSettings;
Also is it possible to use 2 CustomScriptExtensions?
I get a TypeHandlerVersion error if i try to do that.

Change password of Azure VM using PowerShell

I have tried this approach to change a password of an Azure VM:
$resgroup = "rsource1"
$vmName = "virtualmachine1"
$VM = Get-AzVM -ResourceGroupName $resgroup -Name $vmName
$Credential = Get-Credential
$VM | Set-AzureVMAccessExtension –UserName $Credential.UserName `
–Password $Credential.GetNetworkCredential().Password
$VM | Update-AzVM
But I keep getting this error:
Object reference not set to an instance of an object.
When I console.log the values of $Credential.UserName and $Credential.GetNetworkCredential().Password I got the values of username and password that I have inputted.
What am I missing here?
I've never used Set-AzureVMAccessExtension, but I've used the Az PowerShell equivalant Set-AzVMAccessExtension. It needs you to pass -Credential $Credential instead of -UserName and -Password.
You can try this script I made a while ago to to reset passwords for Azure VMs:
# Replace these values with your own
$resourceGroupName = "Servers-RG"
$vmName = "server1"
# Get the VM into an object
$vm = Get-AzVM -ResourceGroupName $resourceGroupName -Name $vmName
# Store credentials you want to change
$credential = Get-Credential -Message "Enter your username and password for $vmName"
# Store parameters in a hashtable for splatting
# Have a look at https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_splatting?view=powershell-7
$extensionParams = #{
'VMName' = $vmName
'Credential' = $credential
'ResourceGroupName' = $resourceGroupName
'Name' = 'AdminPasswordReset'
'Location' = $vm.Location
}
# Pass splatted parameters and update password
Set-AzVMAccessExtension #extensionParams
# Restart VM
# Don't need to pass any switches since they are inferred ByPropertyName
# Have a look at https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_pipelines?view=powershell-7
$vm | Restart-AzVM
I found that the password update doesn't happen until you restart the VM, so Restart-VM is required.
If anyone interested in the Linux (KISS) version (no VM restart needed):
$settings = '{}'
$protectedSettings = '{
"username": "<yourusername, prefer using Credentials object>",
"password": "<yourpassword, prefer using Credentials object>"
}'
Set-AzVMExtension `
-VMName $vmName `
-ResourceGroupName $rgName `
-Location $location `
-Name "VMAccessForLinux" `
-Publisher "Microsoft.OSTCExtensions" `
-ExtensionType "VMAccessForLinux" `
-TypeHandlerVersion "1.4" `
-Settingstring $settings `
-ProtectedSettingString $protectedSettings

placing the results of Get-AzureRmVM into an array and using a loop to add them to the domain

I need to query a resource group for the number of VMs in the resource group, I then need to run the following command to add each machine to the domain.
In the below example I'm only adding server1 but if there are multiple servers in this resource group, whats the best way of ensuring each machine gets added based on the results of Get-AzureRmVM?
Set-AzureRmVMExtension -ResourceGroupName "abcd" -ExtensionType "JSONADDomainExtension" `
-Name "joindomain" -Publisher "Microsoft.Compute" -TypeHandlerVersion "1.0" `
-VMName "server1" -Location "uk west" -SettingString $string1 `
-ProtectedSettingString $String2
If you want to run Set-AzureRmVMExtension for each VM in a resource group, then you could run
$rg = "abcd"
# Fetch all the machines from one resource group
$machines = Get-AzureRmVM -ResourceGroupName $rg
# Loop over each object in the $machines array and add the extension
$machines | ForEach { Set-AzureRmVMExtension -ResourceGroupName $rg `
-ExtensionType "JSONADDomainExtension" -Name "joindomain" `
-Publisher "Microsoft.Compute" -TypeHandlerVersion "1.0" -VMName $_.Name `
-Location "uk west" -SettingString $string1 -ProtectedSettingString $String2 }

Cannot create Azure HDInsight cluster with Hive metastore using Powershell

I get error when I try to create Azure HDInsight cluster using powershell cmdlet:
New-AzureRmHDInsightClusterConfig `
| Add-AzureRmHDInsightMetastore `
-SqlAzureServerName "$sqlDatabaseServerName.database.windows.net" `
-DatabaseName $hiveMetaStoreDBName `
-Credential $sqlServerCred `
-MetastoreType HiveMetaStore `
| New-AzureRmHDInsightCluster `
-ResourceGroupName $resourceGroupName `
-HttpCredential $clusterCreds `
-ClusterName $clusterName `
-Location $location `
-ClusterType $clusterType `
-OSType $OSType `
-Version "$hdVersion" `
-SshCredential $clusterCreds `
-DefaultStorageAccountName "$storageAccountName.blob.core.windows.net" `
-DefaultStorageAccountKey $storageAccountKey `
-ClusterSizeInNodes $clusterNodes
Looks like parameters are not recognized by powershell because it asks to input them (see below). I input required parameters (Location, ClusterName, ClusterSizeInNodes) and then error occurs.
cmdlet New-AzureRmHDInsightCluster at command pipeline position 3
Supply values for the following parameters:
(Type !? for Help.)
Location: West Europe
ClusterName: xxxxxxxxx
ClusterSizeInNodes: 1
New-AzureRmHDInsightCluster : BadRequest: ParameterNullOrEmpty,Parameter 'ASVAccount.AccountName' cannot be null or
empty.
At line:117 char:11
+ | New-AzureRmHDInsightCluster `
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [New-AzureRmHDInsightCluster], CloudException
+ FullyQualifiedErrorId : Hyak.Common.CloudException,Microsoft.Azure.Commands.HDInsight.NewAzureHDInsightClusterCom
mand
Does somebody know why its happens or what is wrong in smdlet?
From the error message, it seems like your $storageAccountName parameter to the New-AzureRmHDInsightCluster cmdlet is Null or Empty, you may want to inspect further on this.
Besides, I would also strongly recommend you to specify the -DefaultStorageContainer to the New-AzureRmHDInsightCluster cmdlet as well. This will ensures that the cmdlet will be able to resolve the FQDN of your storage account Uri.
E.g. asv://YourDefaultContainer#YourDefaultStorageAccountName.blob.core.windows.net/
Hope this helps!
Use below command for Cluster with Hive Metastore.
Here is a working PowerShell script, to be used with Azure ARM PowerShell, 1.0.1 or later – you can install Azure RM PS via web platform installer or follow this blog https://azure.microsoft.com/en-us/blog/azps-1-0/
Add-AzureRmAccount
$MyClusterName = "clustername";
$MyClusterLocation = "East US 2";
$NumClusterNodes = 2;
$MyClusterVersion = "3.2";
$MyHDInsightUserName = ""
$MyHDInsightPwd = ""
$MySqlAzureUserName = ""
$MySqlAzurePwd = ""
$MySqlAzureServerName = "*.database.windows.net"
$MySqlAzureDbName = "Dbtest"
$MyDefaultContainerName = "tastoreps"
$clusterResourceGroupName = "dirg"
# Use the correct Azure Subscription!
$subid = ""
Select-AzureRmSubscription -SubscriptionId $subid
# Storage key
$primaryStorageAcctName = "toragesouth"
$primaryStorageResourceGroupName = "storagerg"
# you need to use an ARM based storage as the primary account , classic storage won’t work as a primary account, known issue
$storageAccountKey = Get-AzureRmStorageAccountKey -ResourceGroupName $primaryStorageResourceGroupName -Name $primaryStorageAcctName | %{ $_.Key1 }
# credentials
$HdInsightPwd = ConvertTo-SecureString $MyHDInsightPwd -AsPlainText -Force
$HdInsightCreds = New-Object System.Management.Automation.PSCredential ($MyHDInsightUserName, $HdInsightPwd)
$SqlAzurePwd = ConvertTo-SecureString $MySqlAzurePwd -AsPlainText -Force
$SqlAzureCreds = New-Object System.Management.Automation.PSCredential ($MySqlAzureUserName, $SqlAzurePwd)
$config = New-AzureRmHDInsightClusterConfig -ClusterType Hadoop |
Add-AzureRmHDInsightMetastore -SqlAzureServerName $MySqlAzureServerName -DatabaseName $MySqlAzureDbName -Credential $SqlAzureCreds -MetastoreType HiveMetastore |
Add-AzureRmHDInsightMetastore -SqlAzureServerName $MySqlAzureServerName -DatabaseName $MySqlAzureDbName -Credential $SqlAzureCreds -MetastoreType OozieMetastore
$config.DefaultStorageAccountName="$StorageAcctName.blob.core.windows.net"
$config.DefaultStorageAccountKey=$storageAccountKey
#create cluster
New-AzureRmHDInsightCluster -config $config -OSType Windows -clustername $MyClusterName -HttpCredential $HdInsightCreds -DefaultStorageContainer $MyDefaultContainerName -Location $MyClusterLocation -ResourceGroupName $clusterResourceGroupName -ClusterSizeInNodes $NumClusterNodes -Version $MyClusterVersion

Resources