- 1 year ago
Add-AzVMSshPublicKey to vmConfig fails when calling New-AzVM
The Add-AzVMSshPublicKey
cmdlet is used to add an SSH public key to an Azure virtual machine configuration (vmConfig
). However, when creating a new Azure virtual machine using the New-AzVM
cmdlet, you need to directly pass the SSH public key to the New-AzVM
cmdlet instead of using Add-AzVMSshPublicKey
.
Here's an example of how you can add an SSH public key to a vmConfig
and create a new Azure virtual machine using New-AzVM
:
PowerShell# Define the SSH public key
$sshPublicKey = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAB...<your-public-key>"
# Create a new Azure virtual machine configuration
$vmConfig = New-AzVMConfig -VMName "MyVM" -VMSize "Standard_D2s_v3"
# Add the SSH public key to the virtual machine configuration
$vmConfig = $vmConfig | Set-AzVMSshPublicKey -SshPublicKey $sshPublicKey -Path "/home/<username>/.ssh/authorized_keys"
# Specify the other configuration details such as OS image, credentials, and resource group
$osConfig = New-AzLinuxConfiguration -DisablePasswordAuthentication -AuthenticationType "sshPublicKey" -SshPublicKeyData $sshPublicKey
$cred = Get-Credential -Credential "<username>"
$rgName = "MyResourceGroup"
# Create the virtual machine
New-AzVM -ResourceGroupName $rgName -Location "East US" -VM $vmConfig -LinuxConfiguration $osConfig -Credential $cred
In the example above, we define the SSH public key, create a new vmConfig
, add the SSH public key to the configuration using Set-AzVMSshPublicKey
, and then proceed with the remaining configuration details such as the OS image, credentials, and resource group. Finally, we use New-AzVM
to create the virtual machine with the specified configuration.
Make sure to replace <your-public-key>
with your actual SSH public key, <username>
with your desired username, and update the other parameters according to your requirements.
Please note that this example assumes you have already installed and imported the Azure PowerShell module (Az
) and logged in to your Azure account using Connect-AzAccount
.