Skip to content

[Aks]Add new switch GenerateSshKey to generate SSH keys if necessary #12637

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Sep 9, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion src/Aks/Aks/ChangeLog.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@
- Additional information about change #1
-->
## Upcoming Release
* Update api version to 2020-06-01.
* Added parameter `GenerateSshKey` for `New-AzAksCluster`.
* Updated api version to 2020-06-01.

## Version 1.2.0
* Removed `ClientIdAndSecret` to `ServicePrincipalIdAndSecret` and set `ClientIdAndSecret` as an alias [#12381].
Expand Down
80 changes: 80 additions & 0 deletions src/Aks/Aks/Commands/NewAzureRmAks.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,11 @@
// ----------------------------------------------------------------------------------

using System;
using System.Diagnostics;
using System.IO;
using System.Management.Automation;
using System.Runtime.InteropServices;

using Microsoft.Azure.Commands.Aks.Models;
using Microsoft.Azure.Commands.Aks.Properties;
using Microsoft.Azure.Management.ContainerService;
Expand All @@ -31,10 +35,16 @@ public class NewAzureRmAks : NewKubeBase
[Parameter(Mandatory = false, HelpMessage = "Create cluster even if it already exists")]
public SwitchParameter Force { get; set; }

[Parameter(
Mandatory = false,
HelpMessage = "Generate ssh key file to {HOME}/.ssh/id_rsa.")]
public SwitchParameter GenerateSshKey { get; set; }

public override void ExecuteCmdlet()
{
base.ExecuteCmdlet();
PreValidate();
PrepareParameter();

Action action = () =>
{
Expand Down Expand Up @@ -72,6 +82,76 @@ private void PreValidate()
if ((this.IsParameterBound(c => c.NodeMinCount) || this.IsParameterBound(c => c.NodeMaxCount) || this.EnableNodeAutoScaling.IsPresent) &&
!(this.IsParameterBound(c => c.NodeMinCount) && this.IsParameterBound(c => c.NodeMaxCount) && this.EnableNodeAutoScaling.IsPresent))
throw new PSInvalidCastException(Resources.AksNodePoolAutoScalingParametersMustAppearTogether);

if (this.IsParameterBound(c => c.GenerateSshKey) && this.IsParameterBound(c => c.SshKeyValue))
{
throw new ArgumentException(string.Format(Resources.DonotUseGenerateSshKeyWithSshKeyValue));
}
}

private void VerifySshKeyGenBinaryExist()
{
using (Process process = new Process())
{
if ((RuntimeInformation.IsOSPlatform(OSPlatform.Windows)))
{
process.StartInfo.FileName = "where.exe";
}
else
{
process.StartInfo.FileName = "whereis";
}
process.StartInfo.Arguments = "ssh-keygen";
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;

process.Start();
process.WaitForExit();

string result = process.StandardOutput.ReadLine();
if (result.Contains("not found") || result.Contains("Could not find") || result.Trim().Equals("ssh-keygen:"))
{
throw new ArgumentException(Resources.EnableSsh);
}

if (process.ExitCode != 0)
{
throw new ArgumentException(Resources.EnableSsh);
}
}
}

private string GenerateSshKeyValue()
{
VerifySshKeyGenBinaryExist();
String generateSshKeyPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".ssh", "id_rsa"); ;
if (File.Exists(generateSshKeyPath))
{
throw new ArgumentException(string.Format(Resources.DefaultSshKeyAlreadyExist));
}
using (Process process = new Process())
{
process.StartInfo.FileName = "ssh-keygen";
process.StartInfo.Arguments = String.Format("-f \"{0}\"", generateSshKeyPath);
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardInput = true;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.RedirectStandardOutput = true;
process.Start();

Console.WriteLine(process.StandardOutput.ReadToEnd());

process.WaitForExit();
}
return GetSshKey(generateSshKeyPath);
}

protected void PrepareParameter()
{
if (this.IsParameterBound(c => c.GenerateSshKey))
{
SshKeyValue = GenerateSshKeyValue();
}
}
}
}
27 changes: 27 additions & 0 deletions src/Aks/Aks/Properties/Resources.Designer.cs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

9 changes: 9 additions & 0 deletions src/Aks/Aks/Properties/Resources.resx
Original file line number Diff line number Diff line change
Expand Up @@ -369,6 +369,15 @@
<data name="WindowsNodePoolNameLengthLimitation" xml:space="preserve">
<value>Windows agent pool name can not be longer than 6 characters.</value>
</data>
<data name="DonotUseGenerateSshKeyWithSshKeyValue" xml:space="preserve">
<value>Don't use -GenerateSshKey and -SshKeyVaule at the same time.</value>
</data>
<data name="DefaultSshKeyAlreadyExist" xml:space="preserve">
<value>Default ssh key already exists. Please use -SshKeyVaule.</value>
</data>
<data name="EnableSsh" xml:space="preserve">
<value>Cannot find ssh-keygen. Please enable OpenSSH on your local machine.</value>
</data>
<data name="UpdatingNodePoolMode" xml:space="preserve">
<value>Updating NodePoolMode.</value>
</data>
Expand Down
1 change: 1 addition & 0 deletions src/Aks/Aks/help/Az.Aks.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,3 +49,4 @@ Stop the Kubectl SSH tunnel created in Start-AzKubernetesDashboard.

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

17 changes: 16 additions & 1 deletion src/Aks/Aks/help/New-AzAksCluster.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ New-AzAksCluster [-Force] [-NodeVmSetType <String>] [-NodeVnetSubnetID <String>]
[[-ServicePrincipalIdAndSecret] <PSCredential>] [-Location <String>] [-LinuxProfileAdminUserName <String>]
[-DnsNamePrefix <String>] [-KubernetesVersion <String>] [-NodeName <String>] [-NodeMinCount <Int32>]
[-NodeMaxCount <Int32>] [-EnableNodeAutoScaling] [-NodeCount <Int32>] [-NodeOsDiskSize <Int32>]
[-NodeVmSize <String>] [-SshKeyValue <String>] [-AsJob] [-Tag <Hashtable>]
[-NodeVmSize <String>] [-SshKeyValue <String>] [-GenerateSshKey] [-AsJob] [-Tag <Hashtable>]
[-DefaultProfile <IAzureContextContainer>] [-WhatIf] [-Confirm] [<CommonParameters>]
```

Expand Down Expand Up @@ -154,6 +154,21 @@ Accept pipeline input: False
Accept wildcard characters: False
```

### -GenerateSshKey
Generate ssh key file to {HOME}/.ssh/id_rsa.

```yaml
Type: System.Management.Automation.SwitchParameter
Parameter Sets: (All)
Aliases:

Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### -KubernetesVersion
The version of Kubernetes to use for creating the cluster.

Expand Down