github.com/olljanat/moby@v1.13.1/cli/command/secret/create.go (about) 1 package secret 2 3 import ( 4 "fmt" 5 "io" 6 "io/ioutil" 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 "github.com/docker/docker/pkg/system" 13 runconfigopts "github.com/docker/docker/runconfig/opts" 14 "github.com/spf13/cobra" 15 "golang.org/x/net/context" 16 ) 17 18 type createOptions struct { 19 name string 20 file string 21 labels opts.ListOpts 22 } 23 24 func newSecretCreateCommand(dockerCli *command.DockerCli) *cobra.Command { 25 createOpts := createOptions{ 26 labels: opts.NewListOpts(runconfigopts.ValidateEnv), 27 } 28 29 cmd := &cobra.Command{ 30 Use: "create [OPTIONS] SECRET file|-", 31 Short: "Create a secret from a file or STDIN as content", 32 Args: cli.ExactArgs(2), 33 RunE: func(cmd *cobra.Command, args []string) error { 34 createOpts.name = args[0] 35 createOpts.file = args[1] 36 return runSecretCreate(dockerCli, createOpts) 37 }, 38 } 39 flags := cmd.Flags() 40 flags.VarP(&createOpts.labels, "label", "l", "Secret labels") 41 42 return cmd 43 } 44 45 func runSecretCreate(dockerCli *command.DockerCli, options createOptions) error { 46 client := dockerCli.Client() 47 ctx := context.Background() 48 49 var in io.Reader = dockerCli.In() 50 if options.file != "-" { 51 file, err := system.OpenSequential(options.file) 52 if err != nil { 53 return err 54 } 55 in = file 56 defer file.Close() 57 } 58 59 secretData, err := ioutil.ReadAll(in) 60 if err != nil { 61 return fmt.Errorf("Error reading content from %q: %v", options.file, err) 62 } 63 64 spec := swarm.SecretSpec{ 65 Annotations: swarm.Annotations{ 66 Name: options.name, 67 Labels: runconfigopts.ConvertKVStringsToMap(options.labels.GetAll()), 68 }, 69 Data: secretData, 70 } 71 72 r, err := client.SecretCreate(ctx, spec) 73 if err != nil { 74 return err 75 } 76 77 fmt.Fprintln(dockerCli.Out(), r.ID) 78 return nil 79 }