Split out "get sshpublickeys" command

This commit is contained in:
John Gardiner Myers 2021-07-22 22:12:08 -07:00
parent cddefc0a1f
commit 0b4345d3fd
7 changed files with 202 additions and 46 deletions

1
cmd/kops/BUILD.bazel generated
View File

@ -34,6 +34,7 @@ go_library(
"get_instances.go",
"get_keypairs.go",
"get_secrets.go",
"get_sshpublickeys.go",
"main.go",
"promote.go",
"promote_keypair.go",

View File

@ -114,7 +114,7 @@ func RunDeleteSecret(ctx context.Context, f *util.Factory, out io.Writer, option
return err
}
secrets, err := listSecrets(secretStore, nil, options.SecretType, []string{options.SecretName})
secrets, err := listSecrets(secretStore, options.SecretType, []string{options.SecretName})
if err != nil {
return err
}

View File

@ -90,9 +90,10 @@ func NewCmdGet(f *util.Factory, out io.Writer) *cobra.Command {
cmd.AddCommand(NewCmdGetAssets(f, out, options))
cmd.AddCommand(NewCmdGetCluster(f, out, options))
cmd.AddCommand(NewCmdGetInstanceGroups(f, out, options))
cmd.AddCommand(NewCmdGetInstances(f, out, options))
cmd.AddCommand(NewCmdGetKeypairs(f, out, options))
cmd.AddCommand(NewCmdGetSecrets(f, out, options))
cmd.AddCommand(NewCmdGetInstances(f, out, options))
cmd.AddCommand(NewCmdGetSSHPublicKeys(f, out, options))
return cmd
}

View File

@ -24,20 +24,14 @@ import (
"strings"
"github.com/spf13/cobra"
"k8s.io/klog/v2"
"k8s.io/kops/cmd/kops/util"
"k8s.io/kops/pkg/apis/kops"
"k8s.io/kops/pkg/sshcredentials"
"k8s.io/kops/upup/pkg/fi"
"k8s.io/kops/util/pkg/tables"
"k8s.io/kubectl/pkg/util/i18n"
"k8s.io/kubectl/pkg/util/templates"
)
// SecretTypeSSHPublicKey is set in a KeysetItem.Type for an SSH public keypair
// As we move fully to using API objects this should go away.
const SecretTypeSSHPublicKey = kops.KeysetType("SSHPublicKey")
var (
getSecretLong = templates.LongDesc(i18n.T(`
Display one or many secrets.`))
@ -80,17 +74,17 @@ func NewCmdGetSecrets(f *util.Factory, out io.Writer, getOptions *GetOptions) *c
return cmd
}
func listSecrets(secretStore fi.SecretStore, sshCredentialStore fi.SSHCredentialStore, secretType string, names []string) ([]*fi.KeystoreItem, error) {
func listSecrets(secretStore fi.SecretStore, secretType string, names []string) ([]*fi.KeystoreItem, error) {
var items []*fi.KeystoreItem
findType := strings.ToLower(secretType)
switch findType {
case "":
// OK
case "sshpublickey", "secret":
case "", "secret":
// OK
case "sshpublickey":
return nil, fmt.Errorf("use 'kops get sshpublickey' instead")
case "keypair":
return nil, fmt.Errorf("use 'kops get keypairs %s' instead", secretType)
return nil, fmt.Errorf("use 'kops get keypairs' instead")
default:
return nil, fmt.Errorf("unknown secret type %q", secretType)
}
@ -114,33 +108,6 @@ func listSecrets(secretStore fi.SecretStore, sshCredentialStore fi.SSHCredential
}
}
if findType == "" || findType == strings.ToLower(string(SecretTypeSSHPublicKey)) {
l, err := sshCredentialStore.ListSSHCredentials()
if err != nil {
return nil, fmt.Errorf("error listing SSH credentials %v", err)
}
for i := range l {
id, err := sshcredentials.Fingerprint(l[i].Spec.PublicKey)
if err != nil {
klog.Warningf("unable to compute fingerprint for public key %q", l[i].Name)
}
item := &fi.KeystoreItem{
Name: l[i].Name,
ID: id,
Type: SecretTypeSSHPublicKey,
}
if l[i].Spec.PublicKey != "" {
item.Data = []byte(l[i].Spec.PublicKey)
}
if findType != "" && findType != strings.ToLower(string(item.Type)) {
continue
}
items = append(items, item)
}
}
if len(names) != 0 {
var matches []*fi.KeystoreItem
for _, arg := range names {
@ -180,12 +147,7 @@ func RunGetSecrets(ctx context.Context, options *GetSecretsOptions, args []strin
return err
}
sshCredentialStore, err := clientset.SSHCredentialStore(cluster)
if err != nil {
return err
}
items, err := listSecrets(secretStore, sshCredentialStore, options.Type, args)
items, err := listSecrets(secretStore, options.Type, args)
if err != nil {
return err
}

View File

@ -0,0 +1,141 @@
/*
Copyright 2021 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package main
import (
"context"
"encoding/json"
"fmt"
"io"
"github.com/spf13/cobra"
"k8s.io/klog/v2"
"k8s.io/kops/cmd/kops/util"
"k8s.io/kops/pkg/commands/commandutils"
"k8s.io/kops/pkg/sshcredentials"
"k8s.io/kops/util/pkg/tables"
"k8s.io/kubectl/pkg/util/i18n"
"k8s.io/kubectl/pkg/util/templates"
"sigs.k8s.io/yaml"
)
var (
getSSHPublicKeysExample = templates.Examples(i18n.T(`
# Get the SSH public key
kops get sshpublickey`))
getSSHPublicKeysShort = i18n.T(`Get one or many secrets.`)
)
type GetSSHPublicKeysOptions struct {
*GetOptions
}
func NewCmdGetSSHPublicKeys(f *util.Factory, out io.Writer, getOptions *GetOptions) *cobra.Command {
options := GetSSHPublicKeysOptions{
GetOptions: getOptions,
}
cmd := &cobra.Command{
Use: "sshpublickeys [CLUSTER]",
Aliases: []string{"sshpublickey", "ssh"},
Short: getSSHPublicKeysShort,
Example: getSSHPublicKeysExample,
Args: rootCommand.clusterNameArgs(&options.ClusterName),
ValidArgsFunction: commandutils.CompleteClusterName(&rootCommand, true, false),
RunE: func(cmd *cobra.Command, args []string) error {
return RunGetSSHPublicKeys(context.TODO(), f, out, &options)
},
}
return cmd
}
type SSHKeyItem struct {
ID string `json:"id"`
PublicKey string `json:"publicKey"`
}
func RunGetSSHPublicKeys(ctx context.Context, f *util.Factory, out io.Writer, options *GetSSHPublicKeysOptions) error {
clientset, err := f.Clientset()
if err != nil {
return err
}
cluster, err := clientset.GetCluster(ctx, options.ClusterName)
if err != nil {
return err
}
sshCredentialStore, err := clientset.SSHCredentialStore(cluster)
if err != nil {
return err
}
var items []*SSHKeyItem
l, err := sshCredentialStore.FindSSHPublicKeys("admin")
if err != nil {
return fmt.Errorf("listing SSH credentials %v", err)
}
for _, key := range l {
id, err := sshcredentials.Fingerprint(key.Spec.PublicKey)
if err != nil {
klog.Warningf("unable to compute fingerprint for public key")
}
item := &SSHKeyItem{
ID: id,
PublicKey: key.Spec.PublicKey,
}
items = append(items, item)
}
if len(items) == 0 {
return fmt.Errorf("no SSH public key found")
}
switch options.Output {
case OutputTable:
t := &tables.Table{}
t.AddColumn("ID", func(i *SSHKeyItem) string {
return i.ID
})
return t.Render(items, out, "ID")
case OutputYaml:
y, err := yaml.Marshal(items)
if err != nil {
return fmt.Errorf("unable to marshal YAML: %v", err)
}
if _, err := out.Write(y); err != nil {
return fmt.Errorf("error writing to output: %v", err)
}
case OutputJSON:
j, err := json.Marshal(items)
if err != nil {
return fmt.Errorf("unable to marshal JSON: %v", err)
}
if _, err := out.Write(j); err != nil {
return fmt.Errorf("error writing to output: %v", err)
}
default:
return fmt.Errorf("unknown output format: %q", options.Output)
}
return nil
}

1
docs/cli/kops_get.md generated
View File

@ -67,4 +67,5 @@ kops get [flags]
* [kops get instances](kops_get_instances.md) - Display cluster instances.
* [kops get keypairs](kops_get_keypairs.md) - Get one or many keypairs.
* [kops get secrets](kops_get_secrets.md) - Get one or many secrets.
* [kops get sshpublickeys](kops_get_sshpublickeys.md) - Get one or many secrets.

50
docs/cli/kops_get_sshpublickeys.md generated Normal file
View File

@ -0,0 +1,50 @@
<!--- This file is automatically generated by make gen-cli-docs; changes should be made in the go CLI command code (under cmd/kops) -->
## kops get sshpublickeys
Get one or many secrets.
```
kops get sshpublickeys [CLUSTER] [flags]
```
### Examples
```
# Get the SSH public key
kops get sshpublickey
```
### Options
```
-h, --help help for sshpublickeys
```
### Options inherited from parent commands
```
--add_dir_header If true, adds the file directory to the header of the log messages
--alsologtostderr log to standard error as well as files
--config string yaml config file (default is $HOME/.kops.yaml)
--log_backtrace_at traceLocation when logging hits line file:N, emit a stack trace (default :0)
--log_dir string If non-empty, write log files in this directory
--log_file string If non-empty, use this log file
--log_file_max_size uint Defines the maximum size a log file can grow to. Unit is megabytes. If the value is 0, the maximum file size is unlimited. (default 1800)
--logtostderr log to standard error instead of files (default true)
--name string Name of cluster. Overrides KOPS_CLUSTER_NAME environment variable
--one_output If true, only write logs to their native severity level (vs also writing to each lower severity level)
-o, --output string output format. One of: table, yaml, json (default "table")
--skip_headers If true, avoid header prefixes in the log messages
--skip_log_headers If true, avoid headers when opening log files
--state string Location of state storage (kops 'config' file). Overrides KOPS_STATE_STORE environment variable
--stderrthreshold severity logs at or above this threshold go to stderr (default 2)
-v, --v Level number for the log level verbosity
--vmodule moduleSpec comma-separated list of pattern=N settings for file-filtered logging
```
### SEE ALSO
* [kops get](kops_get.md) - Get one or many resources.