create.go 1.5 KB

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