Skip to content

Commit 20c05f0

Browse files
authored
[Aks]Add new switch GenerateSshKey to generate SSH keys if necessary (#12637)
* Add new switch GenerateSshKey to generate SSH keys if necessary. * Handle the exception of white space in path. Co-authored-by: wyunchi-ms <[email protected]>
1 parent 4a4733c commit 20c05f0

File tree

6 files changed

+135
-2
lines changed

6 files changed

+135
-2
lines changed

src/Aks/Aks/ChangeLog.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,8 @@
1818
- Additional information about change #1
1919
-->
2020
## Upcoming Release
21-
* Update api version to 2020-06-01.
21+
* Added parameter `GenerateSshKey` for `New-AzAksCluster`.
22+
* Updated api version to 2020-06-01.
2223

2324
## Version 1.2.0
2425
* Removed `ClientIdAndSecret` to `ServicePrincipalIdAndSecret` and set `ClientIdAndSecret` as an alias [#12381].

src/Aks/Aks/Commands/NewAzureRmAks.cs

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,11 @@
1313
// ----------------------------------------------------------------------------------
1414

1515
using System;
16+
using System.Diagnostics;
17+
using System.IO;
1618
using System.Management.Automation;
19+
using System.Runtime.InteropServices;
20+
1721
using Microsoft.Azure.Commands.Aks.Models;
1822
using Microsoft.Azure.Commands.Aks.Properties;
1923
using Microsoft.Azure.Management.ContainerService;
@@ -31,10 +35,16 @@ public class NewAzureRmAks : NewKubeBase
3135
[Parameter(Mandatory = false, HelpMessage = "Create cluster even if it already exists")]
3236
public SwitchParameter Force { get; set; }
3337

38+
[Parameter(
39+
Mandatory = false,
40+
HelpMessage = "Generate ssh key file to {HOME}/.ssh/id_rsa.")]
41+
public SwitchParameter GenerateSshKey { get; set; }
42+
3443
public override void ExecuteCmdlet()
3544
{
3645
base.ExecuteCmdlet();
3746
PreValidate();
47+
PrepareParameter();
3848

3949
Action action = () =>
4050
{
@@ -72,6 +82,76 @@ private void PreValidate()
7282
if ((this.IsParameterBound(c => c.NodeMinCount) || this.IsParameterBound(c => c.NodeMaxCount) || this.EnableNodeAutoScaling.IsPresent) &&
7383
!(this.IsParameterBound(c => c.NodeMinCount) && this.IsParameterBound(c => c.NodeMaxCount) && this.EnableNodeAutoScaling.IsPresent))
7484
throw new PSInvalidCastException(Resources.AksNodePoolAutoScalingParametersMustAppearTogether);
85+
86+
if (this.IsParameterBound(c => c.GenerateSshKey) && this.IsParameterBound(c => c.SshKeyValue))
87+
{
88+
throw new ArgumentException(string.Format(Resources.DonotUseGenerateSshKeyWithSshKeyValue));
89+
}
90+
}
91+
92+
private void VerifySshKeyGenBinaryExist()
93+
{
94+
using (Process process = new Process())
95+
{
96+
if ((RuntimeInformation.IsOSPlatform(OSPlatform.Windows)))
97+
{
98+
process.StartInfo.FileName = "where.exe";
99+
}
100+
else
101+
{
102+
process.StartInfo.FileName = "whereis";
103+
}
104+
process.StartInfo.Arguments = "ssh-keygen";
105+
process.StartInfo.UseShellExecute = false;
106+
process.StartInfo.RedirectStandardOutput = true;
107+
108+
process.Start();
109+
process.WaitForExit();
110+
111+
string result = process.StandardOutput.ReadLine();
112+
if (result.Contains("not found") || result.Contains("Could not find") || result.Trim().Equals("ssh-keygen:"))
113+
{
114+
throw new ArgumentException(Resources.EnableSsh);
115+
}
116+
117+
if (process.ExitCode != 0)
118+
{
119+
throw new ArgumentException(Resources.EnableSsh);
120+
}
121+
}
122+
}
123+
124+
private string GenerateSshKeyValue()
125+
{
126+
VerifySshKeyGenBinaryExist();
127+
String generateSshKeyPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".ssh", "id_rsa"); ;
128+
if (File.Exists(generateSshKeyPath))
129+
{
130+
throw new ArgumentException(string.Format(Resources.DefaultSshKeyAlreadyExist));
131+
}
132+
using (Process process = new Process())
133+
{
134+
process.StartInfo.FileName = "ssh-keygen";
135+
process.StartInfo.Arguments = String.Format("-f \"{0}\"", generateSshKeyPath);
136+
process.StartInfo.UseShellExecute = false;
137+
process.StartInfo.RedirectStandardInput = true;
138+
process.StartInfo.RedirectStandardError = true;
139+
process.StartInfo.RedirectStandardOutput = true;
140+
process.Start();
141+
142+
Console.WriteLine(process.StandardOutput.ReadToEnd());
143+
144+
process.WaitForExit();
145+
}
146+
return GetSshKey(generateSshKeyPath);
147+
}
148+
149+
protected void PrepareParameter()
150+
{
151+
if (this.IsParameterBound(c => c.GenerateSshKey))
152+
{
153+
SshKeyValue = GenerateSshKeyValue();
154+
}
75155
}
76156
}
77157
}

src/Aks/Aks/Properties/Resources.Designer.cs

Lines changed: 27 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

src/Aks/Aks/Properties/Resources.resx

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -369,6 +369,15 @@
369369
<data name="WindowsNodePoolNameLengthLimitation" xml:space="preserve">
370370
<value>Windows agent pool name can not be longer than 6 characters.</value>
371371
</data>
372+
<data name="DonotUseGenerateSshKeyWithSshKeyValue" xml:space="preserve">
373+
<value>Don't use -GenerateSshKey and -SshKeyVaule at the same time.</value>
374+
</data>
375+
<data name="DefaultSshKeyAlreadyExist" xml:space="preserve">
376+
<value>Default ssh key already exists. Please use -SshKeyVaule.</value>
377+
</data>
378+
<data name="EnableSsh" xml:space="preserve">
379+
<value>Cannot find ssh-keygen. Please enable OpenSSH on your local machine.</value>
380+
</data>
372381
<data name="UpdatingNodePoolMode" xml:space="preserve">
373382
<value>Updating NodePoolMode.</value>
374383
</data>

src/Aks/Aks/help/Az.Aks.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,3 +49,4 @@ Stop the Kubectl SSH tunnel created in Start-AzKubernetesDashboard.
4949

5050
### [Update-AzAksNodePool](Update-AzAksNodePool.md)
5151
Update node pool in a managed cluster.
52+

src/Aks/Aks/help/New-AzAksCluster.md

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ New-AzAksCluster [-Force] [-NodeVmSetType <String>] [-NodeVnetSubnetID <String>]
2121
[[-ServicePrincipalIdAndSecret] <PSCredential>] [-Location <String>] [-LinuxProfileAdminUserName <String>]
2222
[-DnsNamePrefix <String>] [-KubernetesVersion <String>] [-NodeName <String>] [-NodeMinCount <Int32>]
2323
[-NodeMaxCount <Int32>] [-EnableNodeAutoScaling] [-NodeCount <Int32>] [-NodeOsDiskSize <Int32>]
24-
[-NodeVmSize <String>] [-SshKeyValue <String>] [-AsJob] [-Tag <Hashtable>]
24+
[-NodeVmSize <String>] [-SshKeyValue <String>] [-GenerateSshKey] [-AsJob] [-Tag <Hashtable>]
2525
[-DefaultProfile <IAzureContextContainer>] [-WhatIf] [-Confirm] [<CommonParameters>]
2626
```
2727

@@ -154,6 +154,21 @@ Accept pipeline input: False
154154
Accept wildcard characters: False
155155
```
156156
157+
### -GenerateSshKey
158+
Generate ssh key file to {HOME}/.ssh/id_rsa.
159+
160+
```yaml
161+
Type: System.Management.Automation.SwitchParameter
162+
Parameter Sets: (All)
163+
Aliases:
164+
165+
Required: False
166+
Position: Named
167+
Default value: None
168+
Accept pipeline input: False
169+
Accept wildcard characters: False
170+
```
171+
157172
### -KubernetesVersion
158173
The version of Kubernetes to use for creating the cluster.
159174

0 commit comments

Comments
 (0)