Skip to content

Commit 7c9e99c

Browse files
update
1 parent f5d7fb5 commit 7c9e99c

File tree

5 files changed

+3636
-19
lines changed

5 files changed

+3636
-19
lines changed

src/Compute/Compute.Test/ScenarioTests/VirtualMachineTests.cs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -430,5 +430,13 @@ public void TestCapacityReservation()
430430
{
431431
TestRunner.RunTestScript("Test-CapacityReservation");
432432
}
433+
434+
[Fact]
435+
[Trait(Category.AcceptanceType, Category.CheckIn)]
436+
public void TestVMwithSSHKey()
437+
{
438+
TestRunner.RunTestScript("Test-VMwithSSHKey");
439+
}
440+
433441
}
434442
}

src/Compute/Compute.Test/ScenarioTests/VirtualMachineTests.ps1

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5134,6 +5134,42 @@ function Test-CapacityReservation
51345134
$CRG = Get-AzCapacityReservationGroup -ResourceGroupName $rgname
51355135
Assert-AreEqual 0 $CRG.count
51365136

5137+
}
5138+
finally
5139+
{
5140+
# Cleanup
5141+
Clean-ResourceGroup $rgname;
5142+
}
5143+
}
5144+
5145+
function Test-VMwithSSHKey
5146+
{
5147+
# Setup
5148+
$rgname = Get-ComputeTestResourceName;
5149+
$loc = Get-ComputeVMLocation;
5150+
5151+
try
5152+
{
5153+
New-AzResourceGroup -Name $rgname -Location $loc -Force;
5154+
5155+
5156+
# create credential
5157+
$securePassword = Get-PasswordForVM | ConvertTo-SecureString -AsPlainText -Force;
5158+
$user = "admin01";
5159+
$cred = New-Object System.Management.Automation.PSCredential ($user, $securePassword);
5160+
5161+
# Add one VM from creation
5162+
$vmname = '1' + $rgname;
5163+
$domainNameLabel = "d1" + $rgname;
5164+
$sshKeyName = "s" + $rgname
5165+
$vm = New-AzVM -ResourceGroupName $rgname -Name $vmname -Credential $cred -Image CentOS -DomainNameLabel $domainNameLabel -SshKeyname $sshKeyName -generateSshkey
5166+
5167+
$vm = Get-AzVm -ResourceGroupName $rgname -Name $vmname
5168+
$sshKey = Get-AzSshKey -ResourceGroupName $rgname -Name $sshKeyName
5169+
5170+
#assert compare
5171+
Assert-AreEqual $vm.OSProfile.LinuxConfiguration.Ssh.PublicKeys[0].KeyData $sshKey.publickey
5172+
51375173
}
51385174
finally
51395175
{

src/Compute/Compute.Test/SessionRecords/Microsoft.Azure.Commands.Compute.Test.ScenarioTests.VirtualMachineTests/TestVMwithSSHKey.json

Lines changed: 3498 additions & 0 deletions
Large diffs are not rendered by default.

src/Compute/Compute/VirtualMachine/Operation/NewAzureVMCommand.cs

Lines changed: 60 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@
4545
using System.Net;
4646
using System.Reflection;
4747
using System.Threading.Tasks;
48+
using System.Diagnostics;
4849
using CM = Microsoft.Azure.Management.Compute.Models;
4950
using SM = Microsoft.Azure.PowerShell.Cmdlets.Compute.Helpers.Storage.Models;
5051

@@ -58,6 +59,7 @@ public class NewAzureVMCommand : VirtualMachineBaseCmdlet
5859
public const string DefaultParameterSet = "DefaultParameterSet";
5960
public const string SimpleParameterSet = "SimpleParameterSet";
6061
public const string DiskFileParameterSet = "DiskFileParameterSet";
62+
public bool ConfigAsyncVisited = false;
6163

6264
[Parameter(
6365
ParameterSetName = DefaultParameterSet,
@@ -395,6 +397,7 @@ public string DefaultLocation
395397

396398
public async Task<ResourceConfig<VirtualMachine>> CreateConfigAsync()
397399
{
400+
398401
if (_cmdlet.DiskFile == null)
399402
{
400403
ImageAndOsType = await _client.UpdateImageAndOsTypeAsync(
@@ -441,22 +444,24 @@ public async Task<ResourceConfig<VirtualMachine>> CreateConfigAsync()
441444

442445

443446
List<SshPublicKey> sshPublicKeyList = new List<SshPublicKey>();
444-
if (_cmdlet.SshKeyName != null || _cmdlet.GenerateSshKey == true)
447+
if (_cmdlet.ConfigAsyncVisited == true && (_cmdlet.SshKeyName != null || _cmdlet.GenerateSshKey == true))
445448
{
446449
if (ImageAndOsType?.OsType != OperatingSystemTypes.Linux)
447450
{
448451
throw new Exception("Parameters '-SshKeyName' and '-GenerateSshKey' are only allowed with Linux VMs");
449452
}
450453

451454
string publicKey = _cmdlet.SshKeyForLinux();
452-
SshPublicKey sshPublicKey = new SshPublicKey("~/.ssh", publicKey);
455+
SshPublicKey sshPublicKey = new SshPublicKey("/home/" + _cmdlet.Credential.UserName + "/.ssh/authorized_keys", publicKey);
453456
sshPublicKeyList.Add(sshPublicKey);
454457
}
455458
else
456459
{
457460
sshPublicKeyList = null;
458461
}
459462

463+
_cmdlet.ConfigAsyncVisited = true;
464+
460465
if (_cmdlet.DiskFile == null)
461466
{
462467
return resourceGroup.CreateVirtualMachineConfig(
@@ -616,7 +621,29 @@ async Task StrategyExecuteCmdletAsync(IAsyncCmdlet asyncCmdlet)
616621
}
617622
}
618623

619-
var result = await client.RunAsync(client.SubscriptionId, parameters, asyncCmdlet);
624+
VirtualMachine result;
625+
if (this.GenerateSshKey.IsPresent)
626+
{
627+
try
628+
{
629+
result = await client.RunAsync(client.SubscriptionId, parameters, asyncCmdlet);
630+
}
631+
catch (Microsoft.Rest.Azure.CloudException ex)
632+
{
633+
634+
//delete the created ssh key resource
635+
636+
WriteInformation("VM creation failed. Deleting the SSH key resource that was created.", new string[] { "PSHOST" });
637+
Microsoft.Azure.Commands.Compute.Automation.NewAzureSshKey sshKeyClass = new Microsoft.Azure.Commands.Compute.Automation.NewAzureSshKey();
638+
sshKeyClass.SshPublicKeyClient.Delete(this.ResourceGroupName, this.SshKeyName);
639+
// throw exception
640+
throw ex;
641+
}
642+
}
643+
else
644+
{
645+
result = await client.RunAsync(client.SubscriptionId, parameters, asyncCmdlet);
646+
}
620647

621648
if (result != null)
622649
{
@@ -717,18 +744,7 @@ public void DefaultExecuteCmdlet()
717744
throw new Exception("Parameters '-SshKeyName' and '-GenerateSshKey' are only allowed with Linux VMs");
718745
}
719746

720-
string publicKey = SshKeyForLinux();
721-
SshPublicKey sshPublicKey = new SshPublicKey("~/.ssh", publicKey);
722-
List<SshPublicKey> sshPublicKeys = new List<SshPublicKey>()
723-
{
724-
sshPublicKey
725-
};
726-
if (parameters.OsProfile.LinuxConfiguration.Ssh == null)
727-
{
728-
SshConfiguration sshConfig = new SshConfiguration();
729-
parameters.OsProfile.LinuxConfiguration.Ssh = sshConfig;
730-
}
731-
parameters.OsProfile.LinuxConfiguration.Ssh.PublicKeys = sshPublicKeys;
747+
parameters = addSshPublicKey(parameters);
732748

733749
try
734750
{
@@ -1124,5 +1140,34 @@ private string SshKeyForLinux()
11241140

11251141
return publicKey;
11261142
}
1143+
1144+
private VirtualMachine addSshPublicKey(VirtualMachine parameters)
1145+
{
1146+
string publicKeyPath;
1147+
if (parameters.OsProfile?.AdminUsername != null)
1148+
{
1149+
publicKeyPath = "/home/" + parameters.OsProfile.AdminUsername + "/.ssh/authorized_keys";
1150+
}
1151+
else
1152+
{
1153+
publicKeyPath = "/home/azureuser/.ssh/authorized_keys";
1154+
}
1155+
1156+
string publicKey = SshKeyForLinux();
1157+
1158+
SshPublicKey sshPublicKey = new SshPublicKey(publicKeyPath, publicKey);
1159+
List<SshPublicKey> sshPublicKeys = new List<SshPublicKey>()
1160+
{
1161+
sshPublicKey
1162+
};
1163+
if (parameters.OsProfile.LinuxConfiguration.Ssh == null)
1164+
{
1165+
SshConfiguration sshConfig = new SshConfiguration();
1166+
parameters.OsProfile.LinuxConfiguration.Ssh = sshConfig;
1167+
}
1168+
parameters.OsProfile.LinuxConfiguration.Ssh.PublicKeys = sshPublicKeys;
1169+
1170+
return parameters;
1171+
}
11271172
}
11281173
}

src/Compute/Compute/help/New-AzVM.md

Lines changed: 34 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -24,16 +24,16 @@ New-AzVM [[-ResourceGroupName] <String>] [[-Location] <String>] [-EdgeZone <Stri
2424
[-AsJob] [-OSDiskDeleteOption <String>] [-DataDiskSizeInGb <Int32[]>] [-DataDiskDeleteOption <String>]
2525
[-EnableUltraSSD] [-ProximityPlacementGroupId <String>] [-HostId <String>] [-VmssId <String>]
2626
[-Priority <String>] [-EvictionPolicy <String>] [-MaxPrice <Double>] [-EncryptionAtHost]
27-
[-HostGroupId <String>] [-CapacityReservationGroupId <String>] [-DefaultProfile <IAzureContextContainer>]
28-
[-WhatIf] [-Confirm] [<CommonParameters>]
27+
[-HostGroupId <String>] [-CapacityReservationGroupId <String>] [-SshKeyName <String>] [-GenerateSshKey]
28+
[-DefaultProfile <IAzureContextContainer>] [-WhatIf] [-Confirm] [<CommonParameters>]
2929
```
3030

3131
### DefaultParameterSet
3232
```
3333
New-AzVM [-ResourceGroupName] <String> [-Location] <String> [-EdgeZone <String>] [-VM] <PSVirtualMachine>
3434
[[-Zone] <String[]>] [-DisableBginfoExtension] [-Tag <Hashtable>] [-LicenseType <String>] [-AsJob]
35-
[-OSDiskDeleteOption <String>] [-DataDiskDeleteOption <String>] [-DefaultProfile <IAzureContextContainer>]
36-
[-WhatIf] [-Confirm] [<CommonParameters>]
35+
[-OSDiskDeleteOption <String>] [-DataDiskDeleteOption <String>] [-SshKeyName <String>] [-GenerateSshKey]
36+
[-DefaultProfile <IAzureContextContainer>] [-WhatIf] [-Confirm] [<CommonParameters>]
3737
```
3838

3939
### DiskFileParameterSet
@@ -417,6 +417,21 @@ Accept pipeline input: False
417417
Accept wildcard characters: False
418418
```
419419

420+
### -GenerateSshKey
421+
Generate a SSH Public/Private key pair and create a SSH Public Key resource on Azure.
422+
423+
```yaml
424+
Type: System.Management.Automation.SwitchParameter
425+
Parameter Sets: SimpleParameterSet, DefaultParameterSet
426+
Aliases:
427+
428+
Required: False
429+
Position: Named
430+
Default value: None
431+
Accept pipeline input: False
432+
Accept wildcard characters: False
433+
```
434+
420435
### -HostGroupId
421436
Specifies the dedicated host group the virtual machine will reside in.
422437

@@ -705,6 +720,21 @@ Accept pipeline input: False
705720
Accept wildcard characters: False
706721
```
707722

723+
### -SshKeyName
724+
Name of the SSH Public Key resource.
725+
726+
```yaml
727+
Type: System.String
728+
Parameter Sets: SimpleParameterSet, DefaultParameterSet
729+
Aliases:
730+
731+
Required: False
732+
Position: Named
733+
Default value: None
734+
Accept pipeline input: False
735+
Accept wildcard characters: False
736+
```
737+
708738
### -SubnetAddressPrefix
709739
The address prefix for the subnet which will be created for the VM.
710740

0 commit comments

Comments
 (0)