github.com/zhuohuang-hust/src-cbuild@v0.0.0-20230105071821-c7aab3e7c840/cli/command/secret/create.go (about) 1 package secret 2 3 import ( 4 "fmt" 5 "io/ioutil" 6 "os" 7 8 "github.com/docker/docker/api/types/swarm" 9 "github.com/docker/docker/cli" 10 "github.com/docker/docker/cli/command" 11 "github.com/docker/docker/opts" 12 runconfigopts "github.com/docker/docker/runconfig/opts" 13 "github.com/spf13/cobra" 14 "golang.org/x/net/context" 15 ) 16 17 type createOptions struct { 18 name string 19 labels opts.ListOpts 20 } 21 22 func newSecretCreateCommand(dockerCli *command.DockerCli) *cobra.Command { 23 createOpts := createOptions{ 24 labels: opts.NewListOpts(runconfigopts.ValidateEnv), 25 } 26 27 cmd := &cobra.Command{ 28 Use: "create [OPTIONS] SECRET", 29 Short: "Create a secret using stdin as content", 30 Args: cli.ExactArgs(1), 31 RunE: func(cmd *cobra.Command, args []string) error { 32 createOpts.name = args[0] 33 return runSecretCreate(dockerCli, createOpts) 34 }, 35 } 36 flags := cmd.Flags() 37 flags.VarP(&createOpts.labels, "label", "l", "Secret labels") 38 39 return cmd 40 } 41 42 func runSecretCreate(dockerCli *command.DockerCli, options createOptions) error { 43 client := dockerCli.Client() 44 ctx := context.Background() 45 46 secretData, err := ioutil.ReadAll(os.Stdin) 47 if err != nil { 48 return fmt.Errorf("Error reading content from STDIN: %v", err) 49 } 50 51 spec := swarm.SecretSpec{ 52 Annotations: swarm.Annotations{ 53 Name: options.name, 54 Labels: runconfigopts.ConvertKVStringsToMap(options.labels.GetAll()), 55 }, 56 Data: secretData, 57 } 58 59 r, err := client.SecretCreate(ctx, spec) 60 if err != nil { 61 return err 62 } 63 64 fmt.Fprintln(dockerCli.Out(), r.ID) 65 return nil 66 }