Add "kops trust keypair" command

This commit is contained in:
John Gardiner Myers 2021-07-10 13:35:42 -07:00
parent 73b1bce020
commit 1c3947220e
9 changed files with 306 additions and 1 deletions

2
cmd/kops/BUILD.bazel generated
View File

@ -50,6 +50,8 @@ go_library(
"toolbox_dump.go",
"toolbox_instance_selector.go",
"toolbox_template.go",
"trust.go",
"trust_keypair.go",
"unset.go",
"unset_cluster.go",
"unset_instancegroups.go",

View File

@ -172,11 +172,16 @@ func distrustKeypair(out io.Writer, name string, keypairIDs []string, keyStore f
if item == nil {
return fmt.Errorf("keypair not found")
}
if item.DistrustTimestamp != nil {
continue
}
now := time.Now().UTC().Round(0)
item.DistrustTimestamp = &now
if err := keyStore.StoreKeyset(name, keyset); err != nil {
return fmt.Errorf("error deleting keypair: %w", err)
return fmt.Errorf("error storing keyset: %w", err)
}
fmt.Fprintf(out, "Distrusted %s %s\n", name, id)

View File

@ -156,6 +156,7 @@ func NewCmdRoot(f *util.Factory, out io.Writer) *cobra.Command {
cmd.AddCommand(NewCmdRollingUpdate(f, out))
cmd.AddCommand(NewCmdSet(f, out))
cmd.AddCommand(NewCmdToolbox(f, out))
cmd.AddCommand(NewCmdTrust(f, out))
cmd.AddCommand(NewCmdUnset(f, out))
cmd.AddCommand(NewCmdUpgrade(f, out))
cmd.AddCommand(NewCmdValidate(f, out))

41
cmd/kops/trust.go Normal file
View File

@ -0,0 +1,41 @@
/*
Copyright 2019 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 (
"io"
"github.com/spf13/cobra"
"k8s.io/kops/cmd/kops/util"
"k8s.io/kubectl/pkg/util/i18n"
)
var (
trustShort = i18n.T("Trust keypairs.")
)
func NewCmdTrust(f *util.Factory, out io.Writer) *cobra.Command {
cmd := &cobra.Command{
Use: "trust",
Short: trustShort,
}
// create subcommands
cmd.AddCommand(NewCmdTrustKeypair(f, out))
return cmd
}

161
cmd/kops/trust_keypair.go Normal file
View File

@ -0,0 +1,161 @@
/*
Copyright 2019 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"
"fmt"
"io"
"github.com/spf13/cobra"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/kops/cmd/kops/util"
"k8s.io/kops/pkg/commands/commandutils"
"k8s.io/kops/pkg/pretty"
"k8s.io/kops/upup/pkg/fi"
"k8s.io/kubectl/pkg/util/i18n"
"k8s.io/kubectl/pkg/util/templates"
)
var (
trustKeypairLong = templates.LongDesc(i18n.T(`
Trust one or more keypairs in a keyset.
Trusting adds the certificates of the specified keypairs to trust
stores. It is the reverse of the ` + pretty.Bash("kops distrust keypair") + ` command.
`))
trustKeypairExample = templates.Examples(i18n.T(`
kops trust keypair ca 6977545226837259959403993899
`))
trustKeypairShort = i18n.T(`Trust a keypair.`)
)
type TrustKeypairOptions struct {
ClusterName string
Keyset string
KeypairIDs []string
}
func NewCmdTrustKeypair(f *util.Factory, out io.Writer) *cobra.Command {
options := &TrustKeypairOptions{}
cmd := &cobra.Command{
Use: "keypair KEYSET ID...",
Short: trustKeypairShort,
Long: trustKeypairLong,
Example: trustKeypairExample,
Args: func(cmd *cobra.Command, args []string) error {
options.ClusterName = rootCommand.ClusterName(true)
if options.ClusterName == "" {
return fmt.Errorf("--name is required")
}
if len(args) == 0 {
return fmt.Errorf("must specify name of keyset to trust keypair in")
}
options.Keyset = args[0]
if len(args) == 1 {
return fmt.Errorf("must specify names of keypairs to trust keypair in")
}
options.KeypairIDs = args[1:]
return nil
},
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
return completeTrustKeyset(options, args, toComplete)
},
RunE: func(cmd *cobra.Command, args []string) error {
ctx := context.TODO()
return RunTrustKeypair(ctx, f, out, options)
},
}
return cmd
}
func RunTrustKeypair(ctx context.Context, f *util.Factory, out io.Writer, options *TrustKeypairOptions) error {
clientset, err := f.Clientset()
if err != nil {
return err
}
cluster, err := GetCluster(ctx, f, options.ClusterName)
if err != nil {
return err
}
keyStore, err := clientset.KeyStore(cluster)
if err != nil {
return err
}
keyset, err := keyStore.FindKeyset(options.Keyset)
if err != nil {
return err
}
for _, id := range options.KeypairIDs {
item := keyset.Items[id]
if item == nil {
return fmt.Errorf("keypair not found")
}
if item.DistrustTimestamp == nil {
continue
}
item.DistrustTimestamp = nil
if err := keyStore.StoreKeyset(options.Keyset, keyset); err != nil {
return fmt.Errorf("error storing keypair: %w", err)
}
fmt.Fprintf(out, "Trusted %s %s\n", options.Keyset, id)
}
return nil
}
func completeTrustKeyset(options *TrustKeypairOptions, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
commandutils.ConfigureKlogForCompletion()
ctx := context.TODO()
cluster, clientSet, completions, directive := GetClusterForCompletion(ctx, &rootCommand, nil)
if cluster == nil {
return completions, directive
}
keyset, _, completions, directive := completeKeyset(cluster, clientSet, args, func(name string, keyset *fi.Keyset) bool {
if name == "all" {
return false
}
return rotatableKeysetFilter(name, keyset)
})
if keyset == nil {
return completions, directive
}
alreadySelected := sets.NewString(args[1:]...)
return completeKeypairID(keyset, func(keyset *fi.Keyset, item *fi.KeysetItem) bool {
return item.DistrustTimestamp != nil && !alreadySelected.Has(item.Id)
})
}

1
docs/cli/kops.md generated
View File

@ -50,6 +50,7 @@ kOps is Kubernetes Operations.
* [kops rolling-update](kops_rolling-update.md) - Rolling update a cluster.
* [kops set](kops_set.md) - Set fields on clusters and other resources.
* [kops toolbox](kops_toolbox.md) - Misc infrequently used commands.
* [kops trust](kops_trust.md) - Trust keypairs.
* [kops unset](kops_unset.md) - Unset fields on clusters and other resources.
* [kops update](kops_update.md) - Update a cluster.
* [kops upgrade](kops_upgrade.md) - Upgrade a kubernetes cluster.

39
docs/cli/kops_trust.md generated Normal file
View File

@ -0,0 +1,39 @@
<!--- This file is automatically generated by make gen-cli-docs; changes should be made in the go CLI command code (under cmd/kops) -->
## kops trust
Trust keypairs.
### Options
```
-h, --help help for trust
```
### 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)
--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](kops.md) - kOps is Kubernetes Operations.
* [kops trust keypair](kops_trust_keypair.md) - Trust a keypair.

54
docs/cli/kops_trust_keypair.md generated Normal file
View File

@ -0,0 +1,54 @@
<!--- This file is automatically generated by make gen-cli-docs; changes should be made in the go CLI command code (under cmd/kops) -->
## kops trust keypair
Trust a keypair.
### Synopsis
Trust one or more keypairs in a keyset.
Trusting adds the certificates of the specified keypairs to trust stores. It is the reverse of thekops distrust keypair command.
```
kops trust keypair KEYSET ID... [flags]
```
### Examples
```
kops trust keypair ca 6977545226837259959403993899
```
### Options
```
-h, --help help for keypair
```
### 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)
--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 trust](kops_trust.md) - Trust keypairs.

View File

@ -62,6 +62,7 @@ nav:
- kops rolling-update: "cli/kops_rolling-update.md"
- kops set: "cli/kops_set.md"
- kops toolbox: "cli/kops_toolbox.md"
- kops trust: "cli/kops_trust.md"
- kops unset: "cli/kops_unset.md"
- kops update: "cli/kops_update.md"
- kops upgrade: "cli/kops_upgrade.md"