create.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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(opts.ValidateEnv),
  23. }
  24. cmd := &cobra.Command{
  25. Use: "create [OPTIONS] SECRET file|-",
  26. Short: "Create a secret from a file or STDIN as content",
  27. Args: cli.ExactArgs(2),
  28. RunE: func(cmd *cobra.Command, args []string) error {
  29. createOpts.name = args[0]
  30. createOpts.file = args[1]
  31. return runSecretCreate(dockerCli, createOpts)
  32. },
  33. }
  34. flags := cmd.Flags()
  35. flags.VarP(&createOpts.labels, "label", "l", "Secret labels")
  36. return cmd
  37. }
  38. func runSecretCreate(dockerCli *command.DockerCli, options createOptions) error {
  39. client := dockerCli.Client()
  40. ctx := context.Background()
  41. var in io.Reader = dockerCli.In()
  42. if options.file != "-" {
  43. file, err := system.OpenSequential(options.file)
  44. if err != nil {
  45. return err
  46. }
  47. in = file
  48. defer file.Close()
  49. }
  50. secretData, err := ioutil.ReadAll(in)
  51. if err != nil {
  52. return fmt.Errorf("Error reading content from %q: %v", options.file, err)
  53. }
  54. spec := swarm.SecretSpec{
  55. Annotations: swarm.Annotations{
  56. Name: options.name,
  57. Labels: runconfigopts.ConvertKVStringsToMap(options.labels.GetAll()),
  58. },
  59. Data: secretData,
  60. }
  61. r, err := client.SecretCreate(ctx, spec)
  62. if err != nil {
  63. return err
  64. }
  65. fmt.Fprintln(dockerCli.Out(), r.ID)
  66. return nil
  67. }