diff --git a/encrypt/ipsec_key_status.go b/encrypt/ipsec_key_status.go new file mode 100644 index 0000000000..5c2107ccd4 --- /dev/null +++ b/encrypt/ipsec_key_status.go @@ -0,0 +1,48 @@ +// SPDX-License-Identifier: Apache-2.0 +// Copyright Authors of Cilium + +package encrypt + +import ( + "context" + "encoding/json" + "fmt" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + + "github.com/cilium/cilium-cli/defaults" + "github.com/cilium/cilium-cli/status" +) + +// IPsecKeyStatus displays IPsec key. +func (s *Encrypt) IPsecKeyStatus(ctx context.Context) error { + ctx, cancelFn := context.WithTimeout(ctx, s.params.WaitDuration) + defer cancelFn() + + secret, err := s.client.GetSecret(ctx, s.params.CiliumNamespace, defaults.EncryptionSecretName, metav1.GetOptions{}) + if err != nil { + return fmt.Errorf("failed to fetch IPsec secret: %s", err) + } + + if key, ok := secret.Data["keys"]; ok { + return printIPsecKey(string(key), s.params.Output) + } + return fmt.Errorf("IPsec keys not found in the secret: %s", defaults.EncryptionSecretName) +} + +type ipsecKeyStatus struct { + Key string `json:"ipsec-key"` +} + +func printIPsecKey(key string, format string) error { + if format == status.OutputJSON { + js, err := json.MarshalIndent(ipsecKeyStatus{Key: key}, "", " ") + if err != nil { + return err + } + _, err = fmt.Println(string(js)) + return err + } + _, err := fmt.Printf("IPsec key: %s\n", key) + return err +} diff --git a/internal/cli/cmd/encrypt.go b/internal/cli/cmd/encrypt.go index dd3a17b8b0..abe4192a18 100644 --- a/internal/cli/cmd/encrypt.go +++ b/internal/cli/cmd/encrypt.go @@ -23,6 +23,7 @@ func newCmdEncrypt() *cobra.Command { } cmd.AddCommand(newCmdEncryptStatus()) cmd.AddCommand(newCmdIPsecRotateKey()) + cmd.AddCommand(newCmdIPsecKeyStatus()) return cmd } @@ -65,6 +66,26 @@ func newCmdIPsecRotateKey() *cobra.Command { }, } cmd.Flags().DurationVar(¶ms.WaitDuration, "wait-duration", 1*time.Minute, "Maximum time to wait for result, default 1 minute") + return cmd +} + +func newCmdIPsecKeyStatus() *cobra.Command { + params := encrypt.Parameters{} + cmd := &cobra.Command{ + Use: "key-status", + Aliases: []string{"ks"}, + Short: "Display IPsec key", + Long: "This command displays IPsec encryption key", + RunE: func(cmd *cobra.Command, args []string) error { + params.CiliumNamespace = namespace + s := encrypt.NewEncrypt(k8sClient, params) + if err := s.IPsecKeyStatus(context.Background()); err != nil { + fatalf("Unable to display IPsec key: %s", err) + } + return nil + }, + } + cmd.Flags().DurationVar(¶ms.WaitDuration, "wait-duration", 1*time.Minute, "Maximum time to wait for result, default 1 minute") cmd.Flags().StringVarP(¶ms.Output, "output", "o", status.OutputSummary, "Output format. One of: json, summary") return cmd }