create.go 1.9 KB

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