createaci.go 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. /*
  2. Copyright 2020 Docker, Inc.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package context
  14. import (
  15. "context"
  16. "github.com/pkg/errors"
  17. "github.com/spf13/cobra"
  18. "github.com/docker/api/client"
  19. "github.com/docker/api/context/store"
  20. "github.com/docker/api/errdefs"
  21. )
  22. type aciCreateOpts struct {
  23. description string
  24. location string
  25. subscriptionID string
  26. resourceGroup string
  27. }
  28. func createAciCommand() *cobra.Command {
  29. var opts aciCreateOpts
  30. cmd := &cobra.Command{
  31. Use: "aci CONTEXT [flags]",
  32. Short: "Create a context for Azure Container Instances",
  33. Args: cobra.ExactArgs(1),
  34. RunE: func(cmd *cobra.Command, args []string) error {
  35. return runCreateAci(cmd.Context(), args[0], opts)
  36. },
  37. }
  38. addDescriptionFlag(cmd, &opts.description)
  39. cmd.Flags().StringVar(&opts.location, "location", "eastus", "Location")
  40. cmd.Flags().StringVar(&opts.subscriptionID, "subscription-id", "", "Location")
  41. cmd.Flags().StringVar(&opts.resourceGroup, "resource-group", "", "Resource group")
  42. return cmd
  43. }
  44. func runCreateAci(ctx context.Context, contextName string, opts aciCreateOpts) error {
  45. if contextExists(ctx, contextName) {
  46. return errors.Wrapf(errdefs.ErrAlreadyExists, "context %s", contextName)
  47. }
  48. contextData, description, err := getAciContextData(ctx, opts)
  49. if err != nil {
  50. return err
  51. }
  52. return createDockerContext(ctx, contextName, store.AciContextType, description, contextData)
  53. }
  54. func getAciContextData(ctx context.Context, opts aciCreateOpts) (interface{}, string, error) {
  55. cs, err := client.GetCloudService(ctx, store.AciContextType)
  56. if err != nil {
  57. return nil, "", errors.Wrap(err, "cannot connect to ACI backend")
  58. }
  59. return cs.CreateContextData(ctx, convertAciOpts(opts))
  60. }
  61. func convertAciOpts(opts aciCreateOpts) map[string]string {
  62. return map[string]string{
  63. "aciSubscriptionId": opts.subscriptionID,
  64. "aciResourceGroup": opts.resourceGroup,
  65. "aciLocation": opts.location,
  66. "description": opts.description,
  67. }
  68. }