Documentation
¶
Index ¶
- Constants
- Variables
- func FindCommandTreeAnnotation(cmd *cobra.Command, k string) string
- func GetFlagWithFallback(cmd *cobra.Command, flag, deprecatedFlag string) string
- func MustConfiguration(c context.Context) config.Config
- func MustCpClient(c context.Context) cp.ClientWithResponsesInterface
- func MustDpClient(c context.Context) dp.ClientWithResponsesInterface
- func MustIamClient(c context.Context) iam.ClientWithResponsesInterface
- func MustPrinter(c context.Context) printer.Printer
- func PromptTextAndEnterToContinue(ctx context.Context, stdin io.Reader, requiredText string) error
- func PromptYesNo(ctx context.Context, stdin io.Reader, prompt string) (bool, error)
- func ShouldApiUrl(c context.Context) (string, error)
- func ShouldOrg(c context.Context) (string, error)
- func SuggestHintByCause(ctx context.Context, cause Cause, parentCmd *cobra.Command, parentErr error) error
- type Cause
- type Hint
- type HintCommand
Constants ¶
View Source
const ( ExtraRequestHeadersEnvVar = "PO_EXTRA_REQUEST_HEADERS" AuthTokenEnvVar = "PO_AUTH_TOKEN" // #nosec G101 CpClientContextKey contextKey = "cp-client" DpClientContextKey contextKey = "dp-client" IamClientContextKey contextKey = "iam-client" ConfigContextKey contextKey = "config" PrinterContextKey contextKey = "printer" )
View Source
const PromptTimeout = 300 * time.Second
View Source
const SkipConfigContextAnnotation = "skip-config-context"
SkipConfigContextAnnotation skips the pre-run hook that reads the config file and adds it into the command context.
Variables ¶
View Source
var ( ObjectTypeModuleAliasesSingular = []string{ "mod", } ObjectTypeModuleAliasesPlural = []string{ "mods", } )
View Source
var ( ObjectTypeProviderAliasesSingular = []string{ "mp", } ObjectTypeProviderAliasesPlural = []string{ "mps", } )
View Source
var ( ObjectTypeRuleAliasesSingular = []string{ "rule", "rl", } ObjectTypeRuleAliasesPlural = []string{ "rules", "rls", } )
View Source
var ( ObjectTypeRunnerRuleAliasesSingular = []string{ "rrl", } ObjectTypeRunnerRuleAliasesPlural = []string{ "rrls", } )
View Source
var ( ObjectTypeRunnerAliasesSingular []string ObjectTypeRunnerAliasesPlural []string )
View Source
var ConfigCmd = &cobra.Command{ Use: "config", Short: "Manage the configuration", CompletionOptions: cobra.CompletionOptions{ HiddenDefaultCmd: true, }, }
View Source
var CreateCmd = &cobra.Command{ GroupID: CrudGroup.ID, Use: "create <type>", Short: "Create an object of a given type", SilenceErrors: true, PersistentPreRunE: func(cmd *cobra.Command, args []string) error { out, _ := cmd.Flags().GetString(printer.OutputFormatFlag) ctx, err := withPrinter(cmd.Context(), out, []string{printer.JsonPrinterType, printer.YamlPrinterType}) if err != nil { return err } cmd.SetContext(ctx) return nil }, CompletionOptions: cobra.CompletionOptions{ HiddenDefaultCmd: true, }, }
View Source
var CreateEnvironment = &cobra.Command{ Use: "environment <project-id> <environment-id> --set env_type_id=<env_type_id>", Aliases: ObjectTypeEnvironmentAliasesSingular, Args: cobra.ExactArgs(2), Short: "Create an environment in a project", Long: fmt.Sprintf(`Create a new environment in a project. The following fields can be set using --set or --set-json: %s. Examples: # The env_type_id is required $ octl create environment my-project my-new-env --set env_type_id=production # Set a display name $ octl create environment my-project my-new-env --set env_type_id=production --set display_name='My New Environment' `, generateTopLevelSetFields(cp.EnvironmentCreateBody{})), RunE: func(cmd *cobra.Command, args []string) error { x, err := readSetFlagsIntoType[cp.EnvironmentCreateBody](cmd) if err != nil { return err } projectId := args[0] x.Id = args[1] if x.EnvTypeId == "" { return errors.New("env_type_id is required. Use --set env_type_id=<env_type_id>") } cmd.SilenceUsage = true cpc := MustCpClient(cmd.Context()) orgId, err := ShouldOrg(cmd.Context()) if err != nil { return err } slog.Debug("Creating environment", slog.String("org_id", orgId), slog.String("project_id", projectId), slog.String("id", x.Id)) if res, err := cpc.CreateEnvironmentWithResponse(cmd.Context(), orgId, projectId, *x); err != nil { return errors.Wrap(err, "failed to create environment") } else if res.StatusCode() == http.StatusConflict { return errorToHint(cmd, errors.Errorf("conflict: %s.", res.JSON409.Message)) } else if res.StatusCode() == http.StatusBadRequest { return errors.Errorf("request is invalid: %s", res.JSON400.Message) } else if res.StatusCode() != http.StatusCreated { return errors.Errorf("unexpected status code %d when creating environment: %s", res.StatusCode(), string(res.Body)) } else { successMessageF("Environment %s created in project %s.", x.Id, projectId) printer := MustPrinter(cmd.Context()) return printer.Write(cmd.OutOrStdout(), *res.JSON201) } }, }
View Source
var CreateEnvironmentType = &cobra.Command{ Use: environmentTypeUse, Aliases: ObjectTypeEnvironmentTypeAliasesSingular, Args: cobra.ExactArgs(1), Short: "Create an environment type", Long: fmt.Sprintf(`Create a new environment type in the organization. The following fields can be set using --set or --set-json: %s. `, generateTopLevelSetFields(cp.EnvironmentTypeCreateBody{})), RunE: func(cmd *cobra.Command, args []string) error { cmd.SilenceUsage = true x, err := readSetFlagsIntoType[cp.EnvironmentTypeCreateBody](cmd) if err != nil { return err } x.Id = args[0] cpc := MustCpClient(cmd.Context()) orgId, err := ShouldOrg(cmd.Context()) if err != nil { return err } slog.Debug("Creating environment type", slog.String("org_id", orgId), slog.String("id", x.Id)) if res, err := cpc.CreateEnvironmentTypeWithResponse(cmd.Context(), orgId, *x); err != nil { return errors.Wrap(err, "failed to create environment type") } else if res.StatusCode() == http.StatusConflict { return errors.Errorf("conflict: %s", res.JSON409.Message) } else if res.StatusCode() == http.StatusBadRequest { return errors.Errorf("request is invalid: %s", res.JSON400.Message) } else if res.StatusCode() != http.StatusCreated { return errors.Errorf("unexpected status code %d when creating environment type: %s", res.StatusCode(), string(res.Body)) } else { successMessageF("Environment type %s created in organization %s.", x.Id, orgId) printer := MustPrinter(cmd.Context()) return printer.Write(cmd.OutOrStdout(), *res.JSON201) } }, }
View Source
var CreateMetadataKey = &cobra.Command{ Use: metadataKeyUse, Args: cobra.ExactArgs(1), Short: "Create an organization metadata key", Long: fmt.Sprintf(`Create an organization metadata key. The following fields can be set using --set, --set-json, or --set-yaml: %s. The name positional argument takes precedence over a name in the request body. `, generateTopLevelSetFields(dp.MetadataKeyCreateBody{})), RunE: func(cmd *cobra.Command, args []string) error { cmd.SilenceUsage = true body, err := readSetFlagsIntoType[dp.MetadataKeyCreateBody](cmd) if err != nil { return err } body.Name = args[0] orgID, err := ShouldOrg(cmd.Context()) if err != nil { return err } res, err := MustDpClient(cmd.Context()).CreateMetadataKeyWithResponse(cmd.Context(), orgID, *body) if err != nil { return errors.Wrap(err, "failed to create metadata key") } switch res.StatusCode() { case http.StatusCreated: successMessageF("Metadata key %q created in organization %s.", args[0], orgID) return MustPrinter(cmd.Context()).Write(cmd.OutOrStdout(), *res.JSON201) case http.StatusBadRequest: return errors.Errorf("request is invalid: %s", res.JSON400.Message) case http.StatusNotFound: return errors.Errorf("organization '%s' not found", orgID) case http.StatusConflict: return errors.Errorf("metadata key %q already exists in organization '%s'", args[0], orgID) default: return errors.Errorf("unexpected status code %d when creating metadata key: %s", res.StatusCode(), string(res.Body)) } }, }
View Source
var CreateModule = &cobra.Command{ Use: moduleUse, Aliases: ObjectTypeModuleAliasesSingular, Args: cobra.ExactArgs(1), Short: "Create a module", Long: fmt.Sprintf(`Create a new module in the organization. The following fields can be set using --set or --set-json: %s. `, generateTopLevelSetFields(cp.ModuleCreateBody{})), RunE: func(cmd *cobra.Command, args []string) error { cmd.SilenceUsage = true x, err := readSetFlagsIntoType[cp.ModuleCreateBody](cmd) if err != nil { return err } x.Id = args[0] cpc := MustCpClient(cmd.Context()) orgId, err := ShouldOrg(cmd.Context()) if err != nil { return err } slog.Debug("Creating module", slog.String("org_id", orgId), slog.String("id", x.Id)) if res, err := cpc.CreateModuleWithResponse(cmd.Context(), orgId, *x); err != nil { return errors.Wrap(err, "failed to create module") } else if res.StatusCode() == http.StatusConflict { return errors.Errorf("conflict: %s", res.JSON409.Message) } else if res.StatusCode() == http.StatusBadRequest { return errors.Errorf("request is invalid: %s", res.JSON400.Message) } else if res.StatusCode() != http.StatusCreated { return errors.Errorf("unexpected status code %d when creating module: %s", res.StatusCode(), string(res.Body)) } else { successMessageF("Module %s created in organization %s.", x.Id, orgId) printer := MustPrinter(cmd.Context()) return printer.Write(cmd.OutOrStdout(), *res.JSON201) } }, }
View Source
var CreateModuleProvider = &cobra.Command{ Use: moduleProviderUse, Aliases: ObjectTypeProviderAliasesSingular, Args: cobra.ExactArgs(2), Short: "Create a module provider", Long: fmt.Sprintf(`Create a new module provider in the organization. The following fields can be set using --set or --set-json: %s. `, generateTopLevelSetFields(cp.ModuleProviderCreateBody{})), RunE: func(cmd *cobra.Command, args []string) error { cmd.SilenceUsage = true x, err := readSetFlagsIntoType[cp.ModuleProviderCreateBody](cmd) if err != nil { return err } x.ProviderType = args[0] x.Id = args[1] cpc := MustCpClient(cmd.Context()) orgId, err := ShouldOrg(cmd.Context()) if err != nil { return err } slog.Debug("Creating module provider", slog.String("org_id", orgId), slog.String("id", x.Id)) if res, err := cpc.CreateModuleProviderWithResponse(cmd.Context(), orgId, *x); err != nil { return errors.Wrap(err, "failed to create module provider") } else if res.StatusCode() == http.StatusConflict { return errors.Errorf("conflict: %s", res.JSON409.Message) } else if res.StatusCode() == http.StatusBadRequest { return errors.Errorf("request is invalid: %s", res.JSON400.Message) } else if res.StatusCode() != http.StatusCreated { return errors.Errorf("unexpected status code %d when creating module provider: %s", res.StatusCode(), string(res.Body)) } else { successMessageF("Module provider %s created in organization %s.", x.Id, orgId) printer := MustPrinter(cmd.Context()) return printer.Write(cmd.OutOrStdout(), *res.JSON201) } }, }
View Source
var CreateModuleRule = &cobra.Command{ Use: "module-rule", Aliases: ObjectTypeRuleAliasesSingular, Args: cobra.NoArgs, Short: "Create a module rule", Long: fmt.Sprintf(`Create a new module rule for a module in the organization. The following fields can be set using --set or --set-json: %s. `, generateTopLevelSetFields(cp.RuleCreateBody{})), RunE: func(cmd *cobra.Command, args []string) error { cmd.SilenceUsage = true x, err := readSetFlagsIntoType[cp.RuleCreateBody](cmd) if err != nil { return err } cpc := MustCpClient(cmd.Context()) orgId, err := ShouldOrg(cmd.Context()) if err != nil { return err } ctx := cmd.Context() if x.ProjectId != nil { if res, err := cpc.GetProjectWithResponse(ctx, orgId, *x.ProjectId); err != nil { return errors.Wrap(err, "failed to validate project id") } else if res.StatusCode() == http.StatusNotFound { if noPrompt, _ := cmd.Flags().GetBool(createModuleRuleNoPromptFlag); !noPrompt { changedMessageF("Project %q not found in organization %q. Are you sure you want to create a module rule on it?", *x.ProjectId, orgId) if err := PromptTextAndEnterToContinue(cmd.Context(), os.Stdin, ""); err != nil { return err } } } else if res.StatusCode() != http.StatusOK { return errors.Errorf("unexpected status code %d when validating project id: %s", res.StatusCode(), string(res.Body)) } if x.EnvId != nil { if res, err := cpc.GetEnvironmentWithResponse(ctx, orgId, *x.ProjectId, *x.EnvId); err != nil { return errors.Wrap(err, "failed to validate environment id") } else if res.StatusCode() == http.StatusNotFound { if noPrompt, _ := cmd.Flags().GetBool(createModuleRuleNoPromptFlag); !noPrompt { changedMessageF("Environment %q not found in organization %q and project %q. Are you sure you want to create a module rule on it?", *x.EnvId, orgId, *x.ProjectId) if err := PromptTextAndEnterToContinue(cmd.Context(), os.Stdin, ""); err != nil { return err } } } else if res.StatusCode() != http.StatusOK { return errors.Errorf("unexpected status code %d when validating environment id: %s", res.StatusCode(), string(res.Body)) } } } slog.Debug("Creating module rule", slog.String("org_id", orgId), slog.String("module_id", x.ModuleId)) if res, err := cpc.CreateModuleRuleInOrgWithResponse(ctx, orgId, *x); err != nil { return errors.Wrap(err, "failed to create module rule") } else if res.StatusCode() == http.StatusConflict { return errorToHint(cmd, errors.Errorf("conflict: %s.", res.JSON409.Message)) } else if res.StatusCode() == http.StatusBadRequest { return errors.Errorf("request is invalid: %s", res.JSON400.Message) } else if res.StatusCode() != http.StatusCreated { return errors.Errorf("unexpected status code %d when creating module rule: %s", res.StatusCode(), string(res.Body)) } else { successMessageF("Module rule %s created for module %s in organization %s.", res.JSON201.Id, x.ModuleId, orgId) printer := MustPrinter(ctx) return printer.Write(cmd.OutOrStdout(), *res.JSON201) } }, }
View Source
var CreateProject = &cobra.Command{ Use: projectUse, Aliases: ObjectTypeProjectAliasesSingular, Args: cobra.ExactArgs(1), Short: "Create a project", Long: fmt.Sprintf(`Create a new project in your organization. The following fields can be set using --set or --set-json: %s. `, generateTopLevelSetFields(cp.ProjectCreateBody{})), RunE: func(cmd *cobra.Command, args []string) error { cmd.SilenceUsage = true x, err := readSetFlagsIntoType[cp.ProjectCreateBody](cmd) if err != nil { return err } x.Id = args[0] cpc := MustCpClient(cmd.Context()) orgId, err := ShouldOrg(cmd.Context()) if err != nil { return err } slog.Debug("Creating project", slog.String("org_id", orgId), slog.String("id", x.Id)) if res, err := cpc.CreateProjectWithResponse(cmd.Context(), orgId, *x); err != nil { return errors.Wrap(err, "failed to create project") } else if res.StatusCode() == http.StatusConflict { return errors.Errorf("conflict: %s", res.JSON409.Message) } else if res.StatusCode() == http.StatusBadRequest { return errors.Errorf("request is invalid: %s", res.JSON400.Message) } else if res.StatusCode() != http.StatusCreated { return errors.Errorf("unexpected status code %d when creating project: %s", res.StatusCode(), string(res.Body)) } else { successMessageF("Project %s created in organization %s.", x.Id, orgId) printer := MustPrinter(cmd.Context()) return printer.Write(cmd.OutOrStdout(), *res.JSON201) } }, }
View Source
var CreateResourceType = &cobra.Command{ Use: resourceTypeUse, Aliases: ObjectTypeResourceTypeAliasesSingular, Args: cobra.ExactArgs(1), Short: "Create a resource type", Long: fmt.Sprintf(`Create a new resource type in your organization. The following fields can be set using --set or --set-json: %s. `, generateTopLevelSetFields(cp.ResourceTypeCreateBody{})), RunE: func(cmd *cobra.Command, args []string) error { cmd.SilenceUsage = true x, err := readSetFlagsIntoType[cp.ResourceTypeCreateBody](cmd) if err != nil { return err } x.Id = args[0] cpc := MustCpClient(cmd.Context()) orgId, err := ShouldOrg(cmd.Context()) if err != nil { return err } slog.Debug("Creating resource type", slog.String("org_id", orgId), slog.String("id", x.Id)) if res, err := cpc.CreateResourceTypeWithResponse(cmd.Context(), orgId, *x); err != nil { return errors.Wrap(err, "failed to create resource type") } else if res.StatusCode() == http.StatusConflict { return errors.Errorf("conflict: %s", res.JSON409.Message) } else if res.StatusCode() == http.StatusBadRequest { return errors.Errorf("request is invalid: %s", res.JSON400.Message) } else if res.StatusCode() != http.StatusCreated { return errors.Errorf("unexpected status code %d when creating resource type: %s", res.StatusCode(), string(res.Body)) } else { successMessageF("Resource type %s created in organization %s.", x.Id, orgId) printer := MustPrinter(cmd.Context()) return printer.Write(cmd.OutOrStdout(), *res.JSON201) } }, }
View Source
var CreateRole = &cobra.Command{ Use: "role", Args: cobra.NoArgs, Short: "Create a configurable organization role", Long: fmt.Sprintf(`Create a configurable organization role. The following fields can be set using --set, --set-json, or --set-yaml: %s. `, generateTopLevelSetFields(iam.RoleWriteBody{})), RunE: func(cmd *cobra.Command, _ []string) error { cmd.SilenceUsage = true body, err := readSetFlagsIntoType[iam.RoleWriteBody](cmd) if err != nil { return err } orgID, err := ShouldOrg(cmd.Context()) if err != nil { return err } res, err := MustIamClient(cmd.Context()).CreateRoleWithResponse(cmd.Context(), orgID, *body) if err != nil { return errors.Wrap(err, "failed to create role") } switch res.StatusCode() { case http.StatusCreated: successMessageF("Role %s created in organization %s.", res.JSON201.Id, orgID) return MustPrinter(cmd.Context()).Write(cmd.OutOrStdout(), *res.JSON201) case http.StatusBadRequest: return errors.Errorf("request is invalid: %s", res.JSON400.Message) case http.StatusConflict: return errors.Errorf("role conflicts with existing state: %s", res.JSON409.Message) default: return errors.Errorf("unexpected status code %d when creating role: %s", res.StatusCode(), string(res.Body)) } }, }
View Source
var CreateRunner = &cobra.Command{ Use: runnerUse, Aliases: ObjectTypeRunnerAliasesSingular, Args: cobra.ExactArgs(1), Short: "Create a runner", Long: fmt.Sprintf(`Create a new runner in your organization. The following fields can be set using --set or --set-json: %s. `, generateTopLevelSetFields(cp.RunnerCreateBody{})), RunE: func(cmd *cobra.Command, args []string) error { cmd.SilenceUsage = true x, err := readSetFlagsIntoType[cp.RunnerCreateBody](cmd) if err != nil { return err } x.Id = args[0] cpc := MustCpClient(cmd.Context()) orgId, err := ShouldOrg(cmd.Context()) if err != nil { return err } slog.Debug("Creating runner", slog.String("org_id", orgId), slog.String("id", x.Id)) if res, err := cpc.CreateRunnerWithResponse(cmd.Context(), orgId, *x); err != nil { return errors.Wrap(err, "failed to create runner") } else if res.StatusCode() == http.StatusConflict { return errors.Errorf("conflict: %s", res.JSON409.Message) } else if res.StatusCode() == http.StatusBadRequest { return errors.Errorf("request is invalid: %s", res.JSON400.Message) } else if res.StatusCode() != http.StatusCreated { return errors.Errorf("unexpected status code %d when creating runner: %s", res.StatusCode(), string(res.Body)) } else { successMessageF("Runner %s created in organization %s.", x.Id, orgId) printer := MustPrinter(cmd.Context()) return printer.Write(cmd.OutOrStdout(), *res.JSON201) } }, }
View Source
var CreateRunnerRule = &cobra.Command{ Use: "runner-rule", Aliases: ObjectTypeRunnerRuleAliasesSingular, Args: cobra.NoArgs, Short: "Create a runner rule", Long: fmt.Sprintf(`Create a new runner rule for a rule in the organization. The following fields can be set using --set or --set-json: %s. `, generateTopLevelSetFields(cp.RunnerRuleCreateBody{})), RunE: func(cmd *cobra.Command, args []string) error { cmd.SilenceUsage = true x, err := readSetFlagsIntoType[cp.RunnerRuleCreateBody](cmd) if err != nil { return err } cpc := MustCpClient(cmd.Context()) orgId, err := ShouldOrg(cmd.Context()) if err != nil { return err } ctx := cmd.Context() if x.ProjectId != nil { if res, err := cpc.GetProjectWithResponse(ctx, orgId, *x.ProjectId); err != nil { return errors.Wrap(err, "failed to validate project id") } else if res.StatusCode() == http.StatusNotFound { if noPrompt, _ := cmd.Flags().GetBool(createRunnerRuleNoPromptFlag); !noPrompt { changedMessageF("Project %q not found in organization %q. Are you sure you want to create a runner rule on it?", *x.ProjectId, orgId) if err := PromptTextAndEnterToContinue(cmd.Context(), os.Stdin, ""); err != nil { return err } } } else if res.StatusCode() != http.StatusOK { return errors.Errorf("unexpected status code %d when validating project id: %s", res.StatusCode(), string(res.Body)) } } slog.Debug("Creating runner rule", slog.String("org_id", orgId), slog.String("runner_id", x.RunnerId)) if res, err := cpc.CreateRunnerRuleInOrgWithResponse(cmd.Context(), orgId, *x); err != nil { return errors.Wrap(err, "failed to create runner rule") } else if res.StatusCode() == http.StatusConflict { return errorToHint(cmd, errors.Errorf("conflict: %s.", res.JSON409.Message)) } else if res.StatusCode() == http.StatusBadRequest { return errors.Errorf("request is invalid: %s", res.JSON400.Message) } else if res.StatusCode() != http.StatusCreated { return errors.Errorf("unexpected status code %d when creating runner rule: %s", res.StatusCode(), string(res.Body)) } else { successMessageF("Runner rule %s created for runner %s in organization %s.", res.JSON201.Id, x.RunnerId, orgId) printer := MustPrinter(cmd.Context()) return printer.Write(cmd.OutOrStdout(), *res.JSON201) } }, }
View Source
var CreateScimGroupMapping = newUpsertScimGroupMappingCommand("Create a SCIM group-to-role mapping")
View Source
var CreateServiceUser = &cobra.Command{ Use: "service-user", Args: cobra.NoArgs, Short: "Create a service user and print its one-time bearer token", Long: fmt.Sprintf(`Create a service user and print its bearer token. The token is returned only once. Redirect structured output directly to a secure destination. The following fields can be set using --set, --set-json, or --set-yaml: %s. `, generateTopLevelSetFields(iam.ServiceUserCreateBody{})), RunE: func(cmd *cobra.Command, _ []string) error { cmd.SilenceUsage = true body, err := readSetFlagsIntoType[iam.ServiceUserCreateBody](cmd) if err != nil { return err } orgID, err := ShouldOrg(cmd.Context()) if err != nil { return err } res, err := MustIamClient(cmd.Context()).CreateServiceUserWithResponse(cmd.Context(), orgID, *body) if err != nil { return errors.Wrap(err, "failed to create service user") } switch res.StatusCode() { case http.StatusCreated: successMessageF("Service user %s created in organization %s. Its token will not be shown again.", res.JSON201.Id, orgID) return MustPrinter(cmd.Context()).Write(cmd.OutOrStdout(), *res.JSON201) case http.StatusBadRequest: return errors.Errorf("request is invalid: %s", res.JSON400.Message) case http.StatusConflict: return errors.Errorf("service user conflicts with existing state: %s", res.JSON409.Message) default: return errors.Errorf("unexpected status code %d when creating service user: %s", res.StatusCode(), string(res.Body)) } }, }
View Source
var CrudGroup = &cobra.Group{ID: "crud", Title: "Verbs"}
View Source
var DeleteCmd = &cobra.Command{ GroupID: CrudGroup.ID, Use: "delete <type>", Short: "Delete an object of a given type", SilenceErrors: true, CompletionOptions: cobra.CompletionOptions{ HiddenDefaultCmd: true, }, }
View Source
var DeleteEnvironment = &cobra.Command{ Use: environmentUse, Aliases: ObjectTypeEnvironmentAliasesSingular, Args: cobra.ExactArgs(2), Short: "Delete an environment from the project. This will trigger a background destroy deployment.", Long: `This will trigger a background destroy deployment and remove all applications and resources from the environment. If the deployment fails, the environment will be in a delete_failed state and the delete environment operation can be retried. This command prompts for confirmation, but the prompt can be skipped using the --no-prompt flag. If necessary, the --force flag can be used to delete the environment without running a destroy deployment first. This is not recommended since this will leave all resources and applications behind and is not recoverable.`, RunE: func(cmd *cobra.Command, args []string) error { cmd.SilenceUsage = true cpc := MustCpClient(cmd.Context()) dpClient := MustDpClient(cmd.Context()) orgId, err := ShouldOrg(cmd.Context()) if err != nil { return err } projectId, envId := args[0], args[1] if res, err := cpc.GetEnvironmentWithResponse(cmd.Context(), orgId, projectId, envId); err != nil { return errors.Wrap(err, "failed to get environment") } else if res.StatusCode() == http.StatusNotFound { return errors.Errorf("environment '%s' not found in project '%s' in org '%s'", envId, projectId, orgId) } else if res.StatusCode() != http.StatusOK { return errors.Errorf("unexpected status code %d when getting environment: %s", res.StatusCode(), string(res.Body)) } else if res.JSON200.Status == cp.EnvironmentStatusDeleting { return errors.Errorf("environment '%s' is already deleting", envId) } var manifest dp.DeploymentManifest if res, err := dpClient.ListLastDeploymentsWithResponse(cmd.Context(), orgId, &dp.ListLastDeploymentsParams{ ProjectId: &projectId, EnvId: &envId, StateChangeOnly: ref.Ref(true), PerPage: ref.Ref(1), }); err != nil { return errors.Wrap(err, "failed to list last deployments") } else if res.StatusCode() != http.StatusOK { return errors.Errorf("unexpected status code %d when listing last deployments: %s", res.StatusCode(), string(res.Body)) } else if len(res.JSON200.Items) > 0 { if res, err := dpClient.GetDeploymentWithResponse(cmd.Context(), orgId, res.JSON200.Items[0].Id); err != nil { return errors.Wrap(err, "failed to get deployment") } else if res.StatusCode() != http.StatusOK { return errors.Errorf("unexpected status code %d when getting deployment: %s", res.StatusCode(), string(res.Body)) } else { manifest = res.JSON200.Manifest } } infoMessageF("Environment '%s' in project '%s' contains %d workloads and %d shared resources", envId, projectId, len(manifest.Workloads), len(manifest.Shared)) // Handle rules deletion var deleteRules bool if deleteRules, err = cmd.Flags().GetBool(deleteEnvRulesFlag); err != nil { return err } var noPrompt, _ = cmd.Flags().GetBool(deployCmdNoPromptFlag) if !deleteRules && !noPrompt { moduleRulesRes, err := cpc.ListModuleRulesInOrgWithResponse(cmd.Context(), orgId, &cp.ListModuleRulesInOrgParams{ ByProjectId: &projectId, ByEnvId: &envId, }) if err != nil { return errors.Wrap(err, "failed to list module rules for environment") } else if moduleRulesRes.StatusCode() != http.StatusOK { return errors.Errorf("unexpected status code %d when listing module rules for environment: %s", moduleRulesRes.StatusCode(), string(moduleRulesRes.Body)) } moduleRulesCount := len(moduleRulesRes.JSON200.Items) if moduleRulesCount > 0 { infoMessageF("Environment %q in project %q has %d module rule(s).", envId, projectId, moduleRulesCount) infoMessageF("Module rules:") for _, rule := range moduleRulesRes.JSON200.Items { infoMessageF(" - %s (module: %s, type: %s)", rule.Id, rule.ModuleId, rule.ResourceType) } confirmed, err := PromptYesNo(cmd.Context(), os.Stdin, "Do you want to delete these rules along with the environment?") if err != nil { return err } if confirmed { deleteRules = true } else { infoMessageF("Proceeding without deleting rules.") } } } forceDelete, _ := cmd.Flags().GetBool(deleteEnvForceFlag) if !noPrompt { if forceDelete { changedMessageF("This destroy cannot be undone and using --force may result in stranded and unrecoverable state. Are you sure you want to FORCE delete environment '%s' in project '%s'?", envId, projectId) } else { changedMessageF("This destroy cannot be undone. Are you sure you want to delete environment '%s' in project '%s'?", envId, projectId) } if err := PromptTextAndEnterToContinue(cmd.Context(), os.Stdin, fmt.Sprintf("%s/%s", projectId, envId)); err != nil { return err } } if res, err := cpc.DeleteEnvironmentWithResponse(cmd.Context(), orgId, projectId, envId, &cp.DeleteEnvironmentParams{Force: &forceDelete, DeleteRules: ref.Ref(deleteRules)}); err != nil { return errors.Wrap(err, "failed to delete environment") } else if res.StatusCode() == http.StatusNotFound { return errors.Errorf("environment '%s' not found in project '%s' in org '%s'", envId, projectId, orgId) } else if res.StatusCode() == http.StatusConflict { return errors.Errorf("environment '%s' cannot be deleted: %s", envId, res.JSON409.Message) } else if res.StatusCode() != http.StatusAccepted { return errors.Errorf("unexpected status code %d when deleting environment: %s", res.StatusCode(), string(res.Body)) } else if res.JSON202.Status != cp.EnvironmentStatusDeleting { return errors.Errorf("unexpected status %s when deleting environment: %s", res.JSON202.Status, string(res.Body)) } else { changedMessageF("Environment %s is deleting from project %s.", envId, projectId) if v, _ := cmd.Flags().GetBool(deleteEnvNoWaitFlag); v { return nil } } infoMessageF("Waiting for environment %s to be gone...", envId) completedDeps := make(map[uuid.UUID]bool) for { select { case <-time.After(2 * time.Second): case <-cmd.Context().Done(): return cmd.Context().Err() } exists, depId, err := isEnvironmentStillDeleting(cmd.Context(), cpc, orgId, projectId, envId) if err != nil { return err } else if !exists { successMessageF("Environment %s deleted from project %s.", envId, projectId) return nil } else if depId != uuid.Nil && !completedDeps[depId] { infoMessageF("Waiting for environment destroy deployment %s to complete...", depId) succeeded, err := hasDestroyDeploymentSucceeded(cmd.Context(), dpClient, orgId, depId) if err != nil { return err } else if succeeded { successMessageF("Destroy deployment %s succeeded.", depId) completedDeps[depId] = true } } } }, }
View Source
var DeleteEnvironmentType = &cobra.Command{ Use: environmentTypeUse, Aliases: ObjectTypeEnvironmentTypeAliasesSingular, Args: cobra.ExactArgs(1), Short: "Delete an environment type", RunE: func(cmd *cobra.Command, args []string) error { cmd.SilenceUsage = true cpc := MustCpClient(cmd.Context()) orgId, err := ShouldOrg(cmd.Context()) if err != nil { return err } slog.Debug("Deleting environment type", slog.String("org_id", orgId), slog.String("id", args[0])) if res, err := cpc.DeleteEnvironmentTypeWithResponse(cmd.Context(), orgId, args[0]); err != nil { return errors.Wrap(err, "failed to delete environment type") } else if res.StatusCode() == http.StatusNotFound { return SuggestHintByCause(cmd.Context(), HintCauseEnvTypeNotFound, cmd, envTypeNotFoundError(args[0], orgId)) } else if res.StatusCode() == http.StatusConflict { return errors.Errorf("environment type '%s' cannot be deleted: %s", args[0], res.JSON409.Message) } else if res.StatusCode() != http.StatusNoContent { return errors.Errorf("unexpected status code %d when deleting environment type: %s", res.StatusCode(), string(res.Body)) } changedMessageF("Environment type %s deleted from organization %s.", args[0], orgId) return nil }, }
View Source
var DeleteMetadataKey = &cobra.Command{ Use: metadataKeyUse, Args: cobra.ExactArgs(1), Short: "Delete an organization metadata key", RunE: func(cmd *cobra.Command, args []string) error { cmd.SilenceUsage = true orgID, err := ShouldOrg(cmd.Context()) if err != nil { return err } res, err := MustDpClient(cmd.Context()).DeleteMetadataKeyWithResponse(cmd.Context(), orgID, args[0]) if err != nil { return errors.Wrap(err, "failed to delete metadata key") } switch res.StatusCode() { case http.StatusNoContent: changedMessageF("Metadata key %q deleted from organization %s.", args[0], orgID) return nil case http.StatusNotFound: return errors.Errorf("metadata key %q not found in organization '%s'", args[0], orgID) default: return errors.Errorf("unexpected status code %d when deleting metadata key: %s", res.StatusCode(), string(res.Body)) } }, }
View Source
var DeleteModule = &cobra.Command{ Use: moduleUse, Aliases: ObjectTypeModuleAliasesSingular, Args: cobra.ExactArgs(1), Short: "Delete a module", RunE: func(cmd *cobra.Command, args []string) error { cmd.SilenceUsage = true cpc := MustCpClient(cmd.Context()) orgId, err := ShouldOrg(cmd.Context()) if err != nil { return err } slog.Debug("Deleting module", slog.String("org_id", orgId), slog.String("id", args[0])) if res, err := cpc.DeleteModuleWithResponse(cmd.Context(), orgId, args[0]); err != nil { return errors.Wrap(err, "failed to delete module") } else if res.StatusCode() == http.StatusNotFound { return errors.Errorf("module '%s' not found in org '%s'", args[0], orgId) } else if res.StatusCode() == http.StatusConflict { return errors.Errorf("module '%s' cannot be deleted: %s", args[0], res.JSON409.Message) } else if res.StatusCode() != http.StatusNoContent { return errors.Errorf("unexpected status code %d when deleting module: %s", res.StatusCode(), string(res.Body)) } changedMessageF("Module %s deleted from organization %s.", args[0], orgId) return nil }, }
View Source
var DeleteModuleProvider = &cobra.Command{ Use: moduleProviderUse, Aliases: ObjectTypeProviderAliasesSingular, Args: cobra.ExactArgs(2), Short: "Delete a module provider", RunE: func(cmd *cobra.Command, args []string) error { cmd.SilenceUsage = true cpc := MustCpClient(cmd.Context()) orgId, err := ShouldOrg(cmd.Context()) if err != nil { return err } slog.Debug("Deleting module provider", slog.String("org_id", orgId), slog.String("id", args[0])) if res, err := cpc.DeleteModuleProviderWithResponse(cmd.Context(), orgId, args[0], args[1]); err != nil { return errors.Wrap(err, "failed to delete module provider") } else if res.StatusCode() == http.StatusNotFound { return errors.Errorf("module provider '%s' '%s' not found in org '%s'", args[0], args[1], orgId) } else if res.StatusCode() == http.StatusConflict { return errors.Errorf("module provider '%s' '%s' cannot be deleted: %s", args[0], args[1], res.JSON409.Message) } else if res.StatusCode() != http.StatusNoContent { return errors.Errorf("unexpected status code %d when deleting module provider: %s", res.StatusCode(), string(res.Body)) } changedMessageF("Module provider %s deleted from organization %s.", args[0], orgId) return nil }, }
View Source
var DeleteModuleRule = &cobra.Command{ Use: "module-rule <rule-id>", Aliases: ObjectTypeRuleAliasesSingular, Args: cobra.ExactArgs(1), Short: "Delete a module rule", RunE: func(cmd *cobra.Command, args []string) error { cmd.SilenceUsage = true cpc := MustCpClient(cmd.Context()) orgId, err := ShouldOrg(cmd.Context()) if err != nil { return err } ruleId, err := uuid.Parse(args[0]) if err != nil { return errors.Wrapf(err, "supplied rule id '%s' is not a valid uuid", args[0]) } slog.Debug("Deleting module rule", slog.String("org_id", orgId), slog.String("id", args[0])) if res, err := cpc.DeleteModuleRuleInOrgWithResponse(cmd.Context(), orgId, ruleId); err != nil { return errors.Wrap(err, "failed to delete module rule") } else if res.StatusCode() == http.StatusNotFound { return errors.Errorf("module rule '%s' not found in org '%s'", args[0], orgId) } else if res.StatusCode() == http.StatusConflict { return errors.Errorf("module rule '%s' cannot be deleted: %s", args[0], res.JSON409.Message) } else if res.StatusCode() != http.StatusNoContent { return errors.Errorf("unexpected status code %d when deleting module rule: %s", res.StatusCode(), string(res.Body)) } changedMessageF("Module rule %q deleted from organization %q.", ruleId, orgId) return nil }, }
View Source
var DeleteProject = &cobra.Command{ Use: projectUse, Aliases: ObjectTypeProjectAliasesSingular, Args: cobra.ExactArgs(1), Short: "Delete a project", RunE: func(cmd *cobra.Command, args []string) error { cmd.SilenceUsage = true cpc := MustCpClient(cmd.Context()) orgId, err := ShouldOrg(cmd.Context()) if err != nil { return err } projectId := args[0] var deleteRules bool if deleteRules, err = cmd.Flags().GetBool(deleteRulesFlag); err != nil { return err } slog.Debug("Deleting project", slog.String("org_id", orgId), slog.String("id", projectId), slog.Bool("delete_rules", deleteRules)) if !deleteRules { moduleRulesRes, err := cpc.ListModuleRulesInOrgWithResponse(cmd.Context(), orgId, &cp.ListModuleRulesInOrgParams{ ByProjectId: &projectId, }) if err != nil { return errors.Wrap(err, "failed to list module rules for project") } else if moduleRulesRes.StatusCode() != http.StatusOK { return errors.Errorf("unexpected status code %d when listing module rules for project: %s", moduleRulesRes.StatusCode(), string(moduleRulesRes.Body)) } runnerRulesRes, err := cpc.ListRunnerRulesInOrgWithResponse(cmd.Context(), orgId, &cp.ListRunnerRulesInOrgParams{ ByProjectId: &projectId, }) if err != nil { return errors.Wrap(err, "failed to list runner rules for project") } else if runnerRulesRes.StatusCode() != http.StatusOK { return errors.Errorf("unexpected status code %d when listing runner rules for project: %s", runnerRulesRes.StatusCode(), string(runnerRulesRes.Body)) } moduleRulesCount := len(moduleRulesRes.JSON200.Items) runnerRulesCount := len(runnerRulesRes.JSON200.Items) if moduleRulesCount > 0 || runnerRulesCount > 0 { infoMessageF("Project %q has %d module rule(s) and %d runner rule(s).", projectId, moduleRulesCount, runnerRulesCount) confirmed, err := PromptYesNo(cmd.Context(), os.Stdin, "Do you want to delete these rules along with the project?") if err != nil { return err } if confirmed { deleteRules = true } else { infoMessageF("Proceeding without deleting rules.") } } } if res, err := cpc.DeleteProjectWithResponse(cmd.Context(), orgId, projectId, &cp.DeleteProjectParams{DeleteRules: ref.Ref(deleteRules)}); err != nil { return errors.Wrap(err, "failed to delete project") } else if res.StatusCode() == http.StatusNotFound { return errors.Errorf("project '%s' not found in org '%s'", projectId, orgId) } else if res.StatusCode() == http.StatusConflict { return errors.Errorf("project '%s' cannot be deleted: %s", projectId, res.JSON409.Message) } else if res.StatusCode() != http.StatusNoContent { return errors.Errorf("unexpected status code %d when deleting project: %s", res.StatusCode(), string(res.Body)) } changedMessageF("Project %s deleted from organization %s.", projectId, orgId) return nil }, }
View Source
var DeleteResourceType = &cobra.Command{ Use: resourceTypeUse, Aliases: ObjectTypeResourceTypeAliasesSingular, Args: cobra.ExactArgs(1), Short: "Delete a resource type", RunE: func(cmd *cobra.Command, args []string) error { cmd.SilenceUsage = true cpc := MustCpClient(cmd.Context()) orgId, err := ShouldOrg(cmd.Context()) if err != nil { return err } slog.Debug("Deleting resource type", slog.String("org_id", orgId), slog.String("id", args[0])) if res, err := cpc.DeleteResourceTypeWithResponse(cmd.Context(), orgId, args[0]); err != nil { return errors.Wrap(err, "failed to delete resource type") } else if res.StatusCode() == http.StatusNotFound { return errors.Errorf("resource type '%s' not found in org '%s'", args[0], orgId) } else if res.StatusCode() == http.StatusConflict { return errors.Errorf("resource type '%s' cannot be deleted: %s", args[0], res.JSON409.Message) } else if res.StatusCode() != http.StatusNoContent { return errors.Errorf("unexpected status code %d when deleting resource type: %s", res.StatusCode(), string(res.Body)) } changedMessageF("Resource type %s deleted from organization %s.", args[0], orgId) return nil }, }
View Source
var DeleteRole = &cobra.Command{ Use: roleUse, Args: cobra.ExactArgs(1), Short: "Delete an unassigned configurable role", RunE: func(cmd *cobra.Command, args []string) error { cmd.SilenceUsage = true roleID, err := uuid.Parse(args[0]) if err != nil { return errors.Wrap(err, "role ID must be a UUID") } orgID, err := ShouldOrg(cmd.Context()) if err != nil { return err } res, err := MustIamClient(cmd.Context()).DeleteRoleWithResponse(cmd.Context(), orgID, roleID) if err != nil { return errors.Wrap(err, "failed to delete role") } switch res.StatusCode() { case http.StatusNoContent: changedMessageF("Role %s deleted from organization %s.", roleID, orgID) return nil case http.StatusNotFound: return errors.Errorf("role '%s' not found in organization '%s'", roleID, orgID) case http.StatusConflict: return errors.Errorf("role cannot be deleted: %s", res.JSON409.Message) default: return errors.Errorf("unexpected status code %d when deleting role: %s", res.StatusCode(), string(res.Body)) } }, }
View Source
var DeleteRunner = &cobra.Command{ Use: runnerUse, Aliases: ObjectTypeRunnerAliasesSingular, Args: cobra.ExactArgs(1), Short: "Delete a runner by id", RunE: func(cmd *cobra.Command, args []string) error { cmd.SilenceUsage = true cpc := MustCpClient(cmd.Context()) orgId, err := ShouldOrg(cmd.Context()) if err != nil { return err } slog.Debug("Deleting runner", slog.String("org_id", orgId), slog.String("id", args[0])) if res, err := cpc.DeleteRunnerWithResponse(cmd.Context(), orgId, args[0]); err != nil { return errors.Wrap(err, "failed to delete runner") } else if res.StatusCode() == http.StatusNotFound { return errors.Errorf("runner '%s' not found in org '%s'", args[0], orgId) } else if res.StatusCode() == http.StatusConflict { return errors.Errorf("runner '%s' cannot be deleted: %s", args[0], res.JSON409.Message) } else if res.StatusCode() != http.StatusNoContent { return errors.Errorf("unexpected status code %d when deleting runner: %s", res.StatusCode(), string(res.Body)) } changedMessageF("Runner %s deleted from organization %s.", args[0], orgId) return nil }, }
View Source
var DeleteRunnerRule = &cobra.Command{ Use: "runner-rule <runner-rule-id>", Aliases: ObjectTypeRunnerRuleAliasesSingular, Args: cobra.ExactArgs(1), Short: "Delete a runner rule", RunE: func(cmd *cobra.Command, args []string) error { cmd.SilenceUsage = true cpc := MustCpClient(cmd.Context()) orgId, err := ShouldOrg(cmd.Context()) if err != nil { return err } ruleId, err := uuid.Parse(args[0]) if err != nil { return errors.Wrapf(err, "supplied runner rule id '%s' is not a valid uuid", args[0]) } slog.Debug("Deleting runner rule", slog.String("org_id", orgId), slog.String("id", args[0])) if res, err := cpc.DeleteRunnerRuleInOrgWithResponse(cmd.Context(), orgId, ruleId); err != nil { return errors.Wrap(err, "failed to delete runner rule") } else if res.StatusCode() == http.StatusNotFound { return errors.Errorf("runner rule '%s' not found in org '%s'", args[0], orgId) } else if res.StatusCode() == http.StatusConflict { return errors.Errorf("runner rule '%s' cannot be deleted: %s", args[0], res.JSON409.Message) } else if res.StatusCode() != http.StatusNoContent { return errors.Errorf("unexpected status code %d when deleting runner rule: %s", res.StatusCode(), string(res.Body)) } changedMessageF("Runner rule %s deleted from organization %s.", args[0], orgId) return nil }, }
View Source
var DeleteScimGroupMapping = &cobra.Command{ Use: scimGroupMappingUse, Args: cobra.ExactArgs(1), Short: "Delete a SCIM group-to-role mapping", RunE: func(cmd *cobra.Command, args []string) error { cmd.SilenceUsage = true orgID, err := ShouldOrg(cmd.Context()) if err != nil { return err } res, err := MustIamClient(cmd.Context()).DeleteScimGroupMappingWithResponse(cmd.Context(), orgID, args[0]) if err != nil { return errors.Wrap(err, "failed to delete SCIM group mapping") } switch res.StatusCode() { case http.StatusNoContent: changedMessageF("SCIM group mapping for %q deleted from organization %s.", args[0], orgID) return nil case http.StatusNotFound: return errors.Errorf("SCIM group mapping for %q not found in organization '%s'", args[0], orgID) default: return errors.Errorf("unexpected status code %d when deleting SCIM group mapping: %s", res.StatusCode(), string(res.Body)) } }, }
View Source
var DeleteServiceUser = &cobra.Command{ Use: serviceUserUse, Args: cobra.ExactArgs(1), Short: "Delete a service user and revoke its credential", RunE: func(cmd *cobra.Command, args []string) error { cmd.SilenceUsage = true serviceUserID, err := uuid.Parse(args[0]) if err != nil { return errors.Wrap(err, "service-user ID must be a UUID") } orgID, err := ShouldOrg(cmd.Context()) if err != nil { return err } res, err := MustIamClient(cmd.Context()).DeleteServiceUserWithResponse(cmd.Context(), orgID, serviceUserID) if err != nil { return errors.Wrap(err, "failed to delete service user") } switch res.StatusCode() { case http.StatusNoContent: changedMessageF("Service user %s deleted from organization %s.", serviceUserID, orgID) return nil case http.StatusNotFound: return errors.Errorf("service user '%s' not found in organization '%s'", serviceUserID, orgID) default: return errors.Errorf("unexpected status code %d when deleting service user: %s", res.StatusCode(), string(res.Body)) } }, }
View Source
var DeployCmd = &cobra.Command{ Use: "deploy <project-id> <environment-id> <manifest-source>", Short: "Deploy to an environment", Long: `Deploy to an environment. This command can be used to deploy a manifest file including workloads and resources to an environment, wait for completion, and return any outputs. $ octl deploy my-project my-env manifest.yaml This will, by default, delete any workloads or resources that are not in the manifest. To merge the manifest into the current environment state, use the --merge flag: $ octl deploy my-project my-env partial-manifest.yaml --merge When deploying partial manifests, it is possible to drop workloads or resources from the manifest using the --drop-workload and --drop-shared flags. This is particularly useful when cloning a previous deployment or environment: $ octl deploy my-project my-env deployment://HEAD --drop-workload deprecated-workload $ octl deploy my-project my-env deployment://HEAD --drop-shared unused-database-resource You can use the --plan-only flag to plan a deployment, which will plan the resource graph and module execution without actually changing the environment: $ octl deploy my-project my-env --plan-only Various manifest sources are supported for the default mode or when --plan-only is used: - ./manifest.yaml A local file - '-' Read from stdin - deployment://01234567-89ab-cdef-0123-456789abcdef A deployment id in the same org - deployment://HEAD The last stateful deployment for the environment, this acts like a redeployment - environment://staging The last stateful deployment for an environment in the same project The form of a manifest is a YAML or JSON file with the following structure: workloads: WORKLOAD-NAME: outputs: KEY: VALUE EXPRESSION resources: ALIAS: type: TYPE ... shared: ALIAS: type: TYPE ... By default, the command will prompt for confirmation of the diff before proceeding. This can be disabled with the --no-prompt flag and may be needed for non-interactive use. Once a deployment is created, the CLI shows a URL which can be used to download the runner logs when the deployment completes. The level of the log produced by the runner might be defined with the --runner-logs-level flag, while the CLI will not produce any URL and logs will not be downloadable if the flag --skip-logs is set. `, Args: cobra.ExactArgs(3), RunE: func(cmd *cobra.Command, args []string) error { cmd.SilenceUsage = true out, _ := cmd.Flags().GetString(printer.OutputFormatFlag) ctx, err := withPrinter(cmd.Context(), out, []string{printer.JsonPrinterType, printer.YamlPrinterType, printer.TablePrinterType}) if err != nil { return err } cmd.SetContext(ctx) projectId, envId := args[0], args[1] outputFlag := GetFlagWithFallback(cmd, "result", "output") if outputFlag != "" && outputFlag != "-" { if _, err := filepath.Abs(outputFlag); err != nil { return errors.Wrapf(err, "output file path '%s' was invalid", outputFlag) } } formatFlag := GetFlagWithFallback(cmd, deployCmdFormatFlag, deprecatedDeployCmdFormatFlag) if formatFlag != "yaml" && formatFlag != "json" { return errors.Errorf("unsupported output format %s", formatFlag) } orgId, err := ShouldOrg(cmd.Context()) if err != nil { return err } rawManifest, err := loadRawManifest(cmd.Context(), cmd.InOrStdin(), args[2], MustDpClient(cmd.Context()), orgId, projectId, envId) if err != nil { return err } dec := yaml.NewDecoder(bytes.NewReader(rawManifest)) dec.KnownFields(true) var manifest dp.DeploymentManifest if err := dec.Decode(&manifest); err != nil { return errors.Wrap(err, "failed to decode manifest") } if manifest.Workloads == nil { manifest.Workloads = make(map[string]dp.DeploymentManifestWorkload) } successMessageF("Loaded manifest.") if err := checkEnvironmentExistsForDeployment(cmd.Context(), orgId, projectId, envId, cmd); err != nil { return err } _, lastDeploymentManifest, err := getLastDeploymentManifestForEnvironment(cmd.Context(), orgId, projectId, envId) if err != nil { return err } if v, _ := cmd.Flags().GetBool(deployCmdMergeFlag); v { manifest = dp.DeploymentManifest{ Workloads: maps.Collect(internal.ConcatSeq2(maps.All(lastDeploymentManifest.Workloads), maps.All(manifest.Workloads))), Shared: maps.Collect(internal.ConcatSeq2(maps.All(lastDeploymentManifest.Shared), maps.All(manifest.Shared))), } } if v, _ := cmd.Flags().GetStringArray(deployCmdDropWorkload); len(v) > 0 { for _, workloadName := range v { delete(manifest.Workloads, workloadName) } } if v, _ := cmd.Flags().GetStringArray(deployCmdDropShared); len(v) > 0 { for _, sharedName := range v { delete(manifest.Shared, sharedName) } } if overrides, _ := cmd.Flags().GetStringArray(deployCmdSetFlag); len(overrides) > 0 { if err := applyManifestOverrides(&manifest, overrides); err != nil { return err } } body := dp.DeploymentCreateBody{ ProjectId: projectId, EnvId: envId, Mode: dp.DeploymentCreateBodyModeDeploy, Manifest: &manifest, } if v, _ := cmd.Flags().GetBool(deployCmdPlanOnlyFlag); v { body.PlanOnly = ref.Ref(true) } if v, _ := cmd.Flags().GetBool(deployCmdDryRunFlag); v { body.IsDryRun = v } var ageKey *age.X25519Identity if e, ok := cmd.Context().Value("ageKey").(*age.X25519Identity); ok { ageKey = e } else if ageKey, err = age.GenerateX25519Identity(); err != nil { return errors.Wrap(err, "failed to generate age key for outputs encryption") } body.EncryptedOutputsRecipient = ref.Ref(ageKey.Recipient().String()) slog.Debug("generated outputs encryption identity", slog.String("public recipient", ageKey.Recipient().String())) var logsAgeKey *age.X25519Identity if v, _ := cmd.Flags().GetBool(deployCmdSkipLogsFlag); !v { if e, ok := cmd.Context().Value("logsAgeKey").(*age.X25519Identity); ok { logsAgeKey = e } else if logsAgeKey, err = age.GenerateX25519Identity(); err != nil { return errors.Wrap(err, "failed to generate age key for logs encryption") } body.EncryptedLogsRecipient = ref.Ref(logsAgeKey.Recipient().String()) slog.Debug("generated logs encryption identity", slog.String("public recipient", logsAgeKey.Recipient().String())) } if v, _ := cmd.Flags().GetString(deployCmdRunnerLogsLevelFlag); !slices.Contains(validRunnerLogsLevels, v) { return errors.Errorf("unsupported value %s for %s flag", v, deployCmdRunnerLogsLevelFlag) } else { body.RunnerLogLevel = ref.Ref(dp.DeploymentCreateBodyRunnerLogLevel(v)) } if err := commonDeployCmdDiff(manifest, lastDeploymentManifest); err != nil { return err } deployment, err := commonDeployCmdInner(cmd, orgId, body, lastDeploymentManifest, logsAgeKey) if err != nil { return err } if body.IsDryRun { return nil } return commonDeploymentOutputHandler(cmd, deployment, ageKey) }, }
View Source
var GetAvailableResourceType = &cobra.Command{ Use: "available-resource-type <project-id> <environment-id> <resource-type-id>", Aliases: ObjectTypeAvailableResourceTypeAliasesSingular, Args: cobra.ExactArgs(3), Short: "Get an available resource type in the project for the environment", RunE: func(cmd *cobra.Command, args []string) error { cmd.SilenceUsage = true cpc := MustCpClient(cmd.Context()) orgId, err := ShouldOrg(cmd.Context()) if err != nil { return err } projectId := args[0] envId := args[1] resourceTypeId := args[2] resourceType, err := cpc.ListAvailableResourceTypesWithResponse(cmd.Context(), orgId, projectId, envId, &cp.ListAvailableResourceTypesParams{TypeId: ref.RefStringEmptyNil(resourceTypeId)}) if err != nil { return err } if resourceType.JSON404 != nil || len(resourceType.JSON200.Items) == 0 { return errors.Errorf("available resource type '%s' not found in project '%s' for environment '%s'", resourceTypeId, projectId, envId) } else { printer := MustPrinter(cmd.Context()) return printer.Write(cmd.OutOrStdout(), resourceType.JSON200.Items[0]) } }, }
View Source
var GetCmd = &cobra.Command{ GroupID: CrudGroup.ID, Use: "get <type>", Short: "Get or list objects of a given type", SilenceErrors: true, PersistentPreRunE: func(cmd *cobra.Command, args []string) error { out, _ := cmd.Flags().GetString(printer.OutputFormatFlag) ctx, err := withPrinter(cmd.Context(), out, []string{printer.JsonPrinterType, printer.YamlPrinterType, printer.TablePrinterType}) if err != nil { return err } cmd.SetContext(ctx) return nil }, CompletionOptions: cobra.CompletionOptions{ HiddenDefaultCmd: true, }, }
View Source
var GetCurrentUser = &cobra.Command{ Use: "current-user", Args: cobra.NoArgs, Short: "Get the details of the current authenticated user and their organizations", RunE: func(cmd *cobra.Command, args []string) error { cmd.SilenceUsage = true client := MustIamClient(cmd.Context()) cu, err := client.GetCurrentUserWithResponse(cmd.Context()) if err != nil { return err } else if cu.StatusCode() != http.StatusOK { return errors.Errorf("unexpected status code %d when getting current user: %s", cu.StatusCode(), string(cu.Body)) } printer := MustPrinter(cmd.Context()) return printer.Write(cmd.OutOrStdout(), *cu.JSON200) }, }
View Source
var GetDeployment = &cobra.Command{ Use: "deployment <deployment-id>", Aliases: ObjectTypeDeploymentAliasesSingular, Args: cobra.ExactArgs(1), Short: "Get a deployment", RunE: func(cmd *cobra.Command, args []string) error { cmd.SilenceUsage = true dpc := MustDpClient(cmd.Context()) orgId, err := ShouldOrg(cmd.Context()) if err != nil { return err } depId, err := uuid.Parse(args[0]) if err != nil { return errors.Wrapf(err, "invalid deployment id '%s'", args[0]) } if r, err := dpc.GetDeploymentWithResponse(cmd.Context(), orgId, depId); err != nil { return errors.Wrap(err, "failed to get deployment") } else if r.StatusCode() == http.StatusNotFound { return errors.Errorf("deployment '%s' not found in org '%s'", args[0], orgId) } else if r.StatusCode() != http.StatusOK { return errors.Errorf("unexpected status code %d when getting deployment: %s", r.StatusCode(), string(r.Body)) } else { printer := MustPrinter(cmd.Context()) return printer.Write(cmd.OutOrStdout(), *r.JSON200) } }, }
View Source
var GetEnvironment = &cobra.Command{ Use: environmentUse, Aliases: ObjectTypeEnvironmentAliasesSingular, Args: cobra.ExactArgs(2), Short: "Get an environment in the project", RunE: func(cmd *cobra.Command, args []string) error { cmd.SilenceUsage = true cpc := MustCpClient(cmd.Context()) orgId, err := ShouldOrg(cmd.Context()) if err != nil { return err } projectId := args[0] if r, err := cpc.GetEnvironmentWithResponse(cmd.Context(), orgId, projectId, args[1]); err != nil { return errors.Wrap(err, "failed to get environment") } else if r.StatusCode() == http.StatusNotFound { return errors.Errorf("environment '%s' not found in project '%s' in org '%s'", args[1], projectId, orgId) } else if r.StatusCode() != http.StatusOK { return errors.Errorf("unexpected status code %d when getting environment: %s", r.StatusCode(), string(r.Body)) } else { printer := MustPrinter(cmd.Context()) return printer.Write(cmd.OutOrStdout(), *r.JSON200) } }, }
View Source
var GetEnvironmentType = &cobra.Command{ Use: environmentTypeUse, Aliases: ObjectTypeEnvironmentTypeAliasesSingular, Args: cobra.ExactArgs(1), Short: "Get an environment type", RunE: func(cmd *cobra.Command, args []string) error { cmd.SilenceUsage = true cpc := MustCpClient(cmd.Context()) orgId, err := ShouldOrg(cmd.Context()) if err != nil { return err } if r, err := cpc.GetEnvironmentTypeWithResponse(cmd.Context(), orgId, args[0]); err != nil { return errors.Wrap(err, "failed to get environment type") } else if r.StatusCode() == http.StatusNotFound { return SuggestHintByCause(cmd.Context(), HintCauseEnvTypeNotFound, cmd, envTypeNotFoundError(args[0], orgId)) } else if r.StatusCode() != http.StatusOK { return errors.Errorf("unexpected status code %d when getting environment type: %s", r.StatusCode(), string(r.Body)) } else { printer := MustPrinter(cmd.Context()) return printer.Write(cmd.OutOrStdout(), *r.JSON200) } }, }
View Source
var GetManifest = &cobra.Command{ Use: "manifest <manifest-source>", Args: cobra.RangeArgs(1, 2), Short: "Get the deployment manifest for an environment or deployment", Long: `Get the deployment manifest for an environment or deployment. This returns the full manifest content and prints it to stdout. `, Example: ` # Get the manifest for a deployment by uuid. octl get manifest 01234567-89ab-cdef-0123-456789abcdef # Get the manifest for the latest stateful deployment for an environment. octl get manifest my-project my-env `, RunE: func(cmd *cobra.Command, args []string) error { cmd.SilenceUsage = true dpc := MustDpClient(cmd.Context()) orgId, err := ShouldOrg(cmd.Context()) if err != nil { return err } var depId uuid.UUID if len(args) == 1 { depId, err = uuid.Parse(args[0]) if err != nil { return errors.Wrapf(err, "invalid deployment id '%s'", args[0]) } } else if len(args) == 2 { if depsResp, err := dpc.ListLastDeploymentsWithResponse(cmd.Context(), orgId, &dp.ListLastDeploymentsParams{ ProjectId: ref.Ref(args[0]), EnvId: ref.Ref(args[1]), StateChangeOnly: ref.Ref(true), PerPage: ref.Ref(1), }); err != nil { return errors.Wrap(err, "failed to list last deployments") } else if depsResp.StatusCode() != http.StatusOK { return errors.Errorf("unexpected status code %d when listing deployments: %s", depsResp.StatusCode(), string(depsResp.Body)) } else if len(depsResp.JSON200.Items) == 0 { return errors.Errorf("no deployments found for environment '%s' - does it exist?", args[1]) } else { depId = depsResp.JSON200.Items[0].Id } } else { return errors.Errorf("expected 1 or 2 arguments, got %d", len(args)) } if r, err := dpc.GetDeploymentWithResponse(cmd.Context(), orgId, depId); err != nil { return errors.Wrap(err, "failed to get deployment") } else if r.StatusCode() == http.StatusNotFound { return errors.Errorf("deployment '%s' not found in org '%s'", args[0], orgId) } else if r.StatusCode() != http.StatusOK { return errors.Errorf("unexpected status code %d when getting deployment: %s", r.StatusCode(), string(r.Body)) } else { printer := MustPrinter(cmd.Context()) return printer.Write(cmd.OutOrStdout(), r.JSON200.Manifest) } }, }
View Source
var GetMetadataKey = &cobra.Command{ Use: metadataKeyUse, Args: cobra.ExactArgs(1), Short: "Get an organization metadata key", RunE: func(cmd *cobra.Command, args []string) error { cmd.SilenceUsage = true orgID, err := ShouldOrg(cmd.Context()) if err != nil { return err } res, err := MustDpClient(cmd.Context()).GetMetadataKeyWithResponse(cmd.Context(), orgID, args[0]) if err != nil { return errors.Wrap(err, "failed to get metadata key") } switch res.StatusCode() { case http.StatusOK: return MustPrinter(cmd.Context()).Write(cmd.OutOrStdout(), *res.JSON200) case http.StatusNotFound: return errors.Errorf("metadata key %q not found in organization '%s'", args[0], orgID) default: return errors.Errorf("unexpected status code %d when getting metadata key: %s", res.StatusCode(), string(res.Body)) } }, }
View Source
var GetModule = &cobra.Command{ Use: moduleUse, Aliases: ObjectTypeModuleAliasesSingular, Args: cobra.ExactArgs(1), Short: "Get a module", RunE: func(cmd *cobra.Command, args []string) error { cmd.SilenceUsage = true cpc := MustCpClient(cmd.Context()) orgId, err := ShouldOrg(cmd.Context()) if err != nil { return err } if r, err := cpc.GetModuleWithResponse(cmd.Context(), orgId, args[0]); err != nil { return errors.Wrap(err, "failed to get module") } else if r.StatusCode() == http.StatusNotFound { return errors.Errorf("module '%s' not found in org '%s'", args[0], orgId) } else if r.StatusCode() != http.StatusOK { return errors.Errorf("unexpected status code %d when getting module: %s", r.StatusCode(), string(r.Body)) } else { printer := MustPrinter(cmd.Context()) return printer.Write(cmd.OutOrStdout(), *r.JSON200) } }, }
View Source
var GetModuleProvider = &cobra.Command{ Use: moduleProviderUse, Aliases: ObjectTypeProviderAliasesSingular, Args: cobra.ExactArgs(2), Short: "Get a module provider", RunE: func(cmd *cobra.Command, args []string) error { cmd.SilenceUsage = true cpc := MustCpClient(cmd.Context()) orgId, err := ShouldOrg(cmd.Context()) if err != nil { return err } if r, err := cpc.GetModuleProviderWithResponse(cmd.Context(), orgId, args[0], args[1]); err != nil { return errors.Wrap(err, "failed to get module provider") } else if r.StatusCode() == http.StatusNotFound { return errors.Errorf("module provider '%s' '%s' not found in org '%s'", args[0], args[1], orgId) } else if r.StatusCode() != http.StatusOK { return errors.Errorf("unexpected status code %d when getting module provider: %s", r.StatusCode(), string(r.Body)) } else { printer := MustPrinter(cmd.Context()) return printer.Write(cmd.OutOrStdout(), *r.JSON200) } }, }
View Source
var GetModuleRule = &cobra.Command{ Use: "module-rule <rule-id>", Aliases: ObjectTypeRuleAliasesSingular, Args: cobra.ExactArgs(1), Short: "Get a module rule", RunE: func(cmd *cobra.Command, args []string) error { cmd.SilenceUsage = true cpc := MustCpClient(cmd.Context()) orgId, err := ShouldOrg(cmd.Context()) if err != nil { return err } ruleId, err := uuid.Parse(args[0]) if err != nil { return errors.Wrap(err, "supplied rule id is not a valid uuid") } if r, err := cpc.GetModuleRuleInOrgWithResponse(cmd.Context(), orgId, ruleId); err != nil { return errors.Wrap(err, "failed to get module rule") } else if r.StatusCode() == http.StatusNotFound { return errors.Errorf("module rule '%s' not found in org '%s'", args[0], orgId) } else if r.StatusCode() != http.StatusOK { return errors.Errorf("unexpected status code %d when getting module rule: %s", r.StatusCode(), string(r.Body)) } else { printer := MustPrinter(cmd.Context()) return printer.Write(cmd.OutOrStdout(), *r.JSON200) } }, }
View Source
var GetProject = &cobra.Command{ Use: projectUse, Aliases: ObjectTypeProjectAliasesSingular, Args: cobra.ExactArgs(1), Short: "Get a project", RunE: func(cmd *cobra.Command, args []string) error { cmd.SilenceUsage = true cpc := MustCpClient(cmd.Context()) orgId, err := ShouldOrg(cmd.Context()) if err != nil { return err } if r, err := cpc.GetProjectWithResponse(cmd.Context(), orgId, args[0]); err != nil { return errors.Wrap(err, "failed to get project") } else if r.StatusCode() == http.StatusNotFound { return errors.Errorf("project '%s' not found in org '%s'", args[0], orgId) } else if r.StatusCode() != http.StatusOK { return errors.Errorf("unexpected status code %d when getting project: %s", r.StatusCode(), string(r.Body)) } else { printer := MustPrinter(cmd.Context()) return printer.Write(cmd.OutOrStdout(), *r.JSON200) } }, }
View Source
var GetResourceType = &cobra.Command{ Use: resourceTypeUse, Aliases: ObjectTypeResourceTypeAliasesSingular, Args: cobra.ExactArgs(1), Short: "Get a resource type", RunE: func(cmd *cobra.Command, args []string) error { cmd.SilenceUsage = true cpc := MustCpClient(cmd.Context()) orgId, err := ShouldOrg(cmd.Context()) if err != nil { return err } if r, err := cpc.GetResourceTypeWithResponse(cmd.Context(), orgId, args[0]); err != nil { return errors.Wrap(err, "failed to get resource type") } else if r.StatusCode() == http.StatusNotFound { return errors.Errorf("resource type '%s' not found in org '%s'", args[0], orgId) } else if r.StatusCode() != http.StatusOK { return errors.Errorf("unexpected status code %d when getting resource type: %s", r.StatusCode(), string(r.Body)) } else { printer := MustPrinter(cmd.Context()) return printer.Write(cmd.OutOrStdout(), *r.JSON200) } }, }
View Source
var GetRole = &cobra.Command{ Use: roleUse, Args: cobra.ExactArgs(1), Short: "Get an organization role", RunE: func(cmd *cobra.Command, args []string) error { cmd.SilenceUsage = true roleID, err := uuid.Parse(args[0]) if err != nil { return errors.Wrap(err, "role ID must be a UUID") } orgID, err := ShouldOrg(cmd.Context()) if err != nil { return err } res, err := MustIamClient(cmd.Context()).GetRoleWithResponse(cmd.Context(), orgID, roleID) if err != nil { return errors.Wrap(err, "failed to get role") } switch res.StatusCode() { case http.StatusOK: return MustPrinter(cmd.Context()).Write(cmd.OutOrStdout(), *res.JSON200) case http.StatusNotFound: return errors.Errorf("role '%s' not found in organization '%s'", roleID, orgID) default: return errors.Errorf("unexpected status code %d when getting role: %s", res.StatusCode(), string(res.Body)) } }, }
View Source
var GetRunner = &cobra.Command{ Use: runnerUse, Aliases: ObjectTypeRunnerAliasesSingular, Args: cobra.ExactArgs(1), Short: "Get a runner by id", RunE: func(cmd *cobra.Command, args []string) error { cmd.SilenceUsage = true cpc := MustCpClient(cmd.Context()) orgId, err := ShouldOrg(cmd.Context()) if err != nil { return err } if r, err := cpc.GetRunnerWithResponse(cmd.Context(), orgId, args[0]); err != nil { return errors.Wrap(err, "failed to get runner") } else if r.StatusCode() == http.StatusNotFound { return errors.Errorf("runner '%s' not found in org '%s'", args[0], orgId) } else if r.StatusCode() != http.StatusOK { return errors.Errorf("unexpected status code %d when getting runner: %s", r.StatusCode(), string(r.Body)) } else { printer := MustPrinter(cmd.Context()) return printer.Write(cmd.OutOrStdout(), *r.JSON200) } }, }
View Source
var GetRunnerRule = &cobra.Command{ Use: "runner-rule <runner-rule-id>", Aliases: ObjectTypeRunnerRuleAliasesSingular, Args: cobra.ExactArgs(1), Short: "Get a runner rule", RunE: func(cmd *cobra.Command, args []string) error { cmd.SilenceUsage = true cpc := MustCpClient(cmd.Context()) orgId, err := ShouldOrg(cmd.Context()) if err != nil { return err } ruleId, err := uuid.Parse(args[0]) if err != nil { return errors.Wrap(err, "supplied runner rule id is not a valid uuid") } if r, err := cpc.GetRunnerRuleInOrgWithResponse(cmd.Context(), orgId, ruleId); err != nil { return errors.Wrap(err, "failed to get runner rule") } else if r.StatusCode() == http.StatusNotFound { return errors.Errorf("runner rule '%s' not found in org '%s'", args[0], orgId) } else if r.StatusCode() != http.StatusOK { return errors.Errorf("unexpected status code %d when getting runner rule: %s", r.StatusCode(), string(r.Body)) } else { printer := MustPrinter(cmd.Context()) return printer.Write(cmd.OutOrStdout(), *r.JSON200) } }, }
View Source
var GetScimGroupMapping = &cobra.Command{ Use: scimGroupMappingUse, Args: cobra.ExactArgs(1), Short: "Get a SCIM group-to-role mapping", RunE: func(cmd *cobra.Command, args []string) error { cmd.SilenceUsage = true orgID, err := ShouldOrg(cmd.Context()) if err != nil { return err } res, err := MustIamClient(cmd.Context()).ListScimGroupMappingsWithResponse(cmd.Context(), orgID) if err != nil { return errors.Wrap(err, "failed to list SCIM group mappings") } if res.StatusCode() != http.StatusOK { return errors.Errorf("unexpected status code %d when listing SCIM group mappings: %s", res.StatusCode(), string(res.Body)) } for _, mapping := range res.JSON200.Items { if strings.EqualFold(mapping.GroupDisplayName, args[0]) { return MustPrinter(cmd.Context()).Write(cmd.OutOrStdout(), mapping) } } return errors.Errorf("SCIM group mapping for %q not found in organization '%s'", args[0], orgID) }, }
View Source
var GetServiceUser = &cobra.Command{ Use: serviceUserUse, Args: cobra.ExactArgs(1), Short: "Get a service user", RunE: func(cmd *cobra.Command, args []string) error { cmd.SilenceUsage = true serviceUserID, err := uuid.Parse(args[0]) if err != nil { return errors.Wrap(err, "service-user ID must be a UUID") } orgID, err := ShouldOrg(cmd.Context()) if err != nil { return err } serviceUsers, err := listAllServiceUsers(cmd, orgID) if err != nil { return errors.Wrap(err, "failed to list service users") } for _, serviceUser := range serviceUsers { if serviceUser.Id == serviceUserID { return MustPrinter(cmd.Context()).Write(cmd.OutOrStdout(), serviceUser) } } return errors.Errorf("service user '%s' not found in organization '%s'", serviceUserID, orgID) }, }
View Source
var GetTf = &cobra.Command{ Use: "tf <deployment-id>", Args: cobra.ExactArgs(1), Short: "Get the compiled TF code applied for the given deployment", Long: `Get the compiled TF code applied for the given deployment. This OpenTofu/Terraform source is generated during the deployment by expanding the manifest into a resource graph and compiling the result into TF. The resulting content includes all providers, variable and output declarations, and module blocks but does not include the source code of any inline modules. This command should be used by platform engineers to debug deployments and to understand the TF code that is applied. There is not expectation that this code can be used outside of the Platform Orchestrator. `, Example: ` # Get the TF code for a deployment by uuid. octl get tf 01234567-89ab-cdef-0123-456789abcdef `, RunE: func(cmd *cobra.Command, args []string) error { cmd.SilenceUsage = true depId, err := uuid.Parse(args[0]) if err != nil { return fmt.Errorf("invalid deployment id '%s'", args[0]) } dpc := MustDpClient(cmd.Context()) orgId, err := ShouldOrg(cmd.Context()) if err != nil { return err } if r, err := dpc.GetDeploymentTfWithResponse(cmd.Context(), orgId, depId); err != nil { return fmt.Errorf("failed to get deployment tf: %w", err) } else if r.StatusCode() == http.StatusNotFound { return fmt.Errorf("deployment '%s' not found in org '%s'", args[0], orgId) } else if r.StatusCode() != http.StatusOK { return fmt.Errorf("unexpected status code %d when getting deployment tf: %s", r.StatusCode(), string(r.Body)) } else { _, err = cmd.OutOrStdout().Write(r.Body) return err } }, }
View Source
var ListActiveResourceNodes = &cobra.Command{ Use: "active-resource-nodes <project-id> <environment-id>", Args: cobra.ExactArgs(2), Short: "List active resource graph nodes for a given environment", RunE: func(cmd *cobra.Command, args []string) error { cmd.SilenceUsage = true dpc := MustDpClient(cmd.Context()) orgId, err := ShouldOrg(cmd.Context()) if err != nil { return err } resp, err := dpc.ListActiveResourceNodesWithResponse(cmd.Context(), orgId, &dp.ListActiveResourceNodesParams{ProjectId: ref.Ref(args[0]), EnvId: ref.Ref(args[1])}) if err != nil { return errors.Wrap(err, "failed to list active resource nodes") } else if resp.StatusCode() == http.StatusNotFound { return errors.New(resp.JSON404.Message) } else if resp.StatusCode() == http.StatusBadRequest { return errors.New(resp.JSON400.Message) } else if resp.StatusCode() != http.StatusOK { return errors.Errorf("unexpected status code %d when listing active resource nodes: %s", resp.StatusCode(), string(resp.Body)) } printer := MustPrinter(cmd.Context()) return printer.Write(cmd.OutOrStdout(), resp.JSON200.Items) }, }
View Source
var ListAvailableResourceType = &cobra.Command{ Use: "available-resource-types <project-id> <environment-id>", Aliases: ObjectTypeAvailableResourceTypeAliasesPlural, Args: cobra.ExactArgs(2), Short: "List available resource types", RunE: func(cmd *cobra.Command, args []string) error { cmd.SilenceUsage = true cpc := MustCpClient(cmd.Context()) orgId, err := ShouldOrg(cmd.Context()) if err != nil { return err } projectId := args[0] envId := args[1] allResourceTypes, err := clients.CollectAll( func(pt string) (*cp.ListAvailableResourceTypesResponse, error) { return cpc.ListAvailableResourceTypesWithResponse(cmd.Context(), orgId, projectId, envId, &cp.ListAvailableResourceTypesParams{Page: ref.RefStringEmptyNil(pt)}) }, func(r *cp.ListAvailableResourceTypesResponse) ([]cp.AvailableResourceType, *string) { return r.JSON200.Items, r.JSON200.NextPageToken }, ) if err != nil { return err } printer := MustPrinter(cmd.Context()) return printer.Write(cmd.OutOrStdout(), allResourceTypes) }, }
View Source
var ListDeployments = &cobra.Command{ Use: "deployments [project-id] [environment-id]", Aliases: ObjectTypeDeploymentAliasesPlural, Args: cobra.RangeArgs(0, 2), Short: "List deployments", RunE: func(cmd *cobra.Command, args []string) error { cmd.SilenceUsage = true dpc := MustDpClient(cmd.Context()) orgId, err := ShouldOrg(cmd.Context()) if err != nil { return err } allDeployments, err := clients.CollectAll( func(pt string) (*dp.ListDeploymentsResponse, error) { var projectId *string if len(args) > 0 { projectId = ref.RefStringEmptyNil(args[0]) } var envId *string if len(args) > 1 { envId = ref.RefStringEmptyNil(args[1]) } return dpc.ListDeploymentsWithResponse(cmd.Context(), orgId, &dp.ListDeploymentsParams{ Page: ref.RefStringEmptyNil(pt), ProjectId: projectId, EnvId: envId, }) }, func(r *dp.ListDeploymentsResponse) ([]dp.DeploymentSummary, *string) { return r.JSON200.Items, r.JSON200.NextPageToken }, ) if err != nil { return err } printer := MustPrinter(cmd.Context()) return printer.Write(cmd.OutOrStdout(), allDeployments) }, }
View Source
var ListEnvironmentTypes = &cobra.Command{ Use: "environment-types", Aliases: ObjectTypeEnvironmentTypeAliasesPlural, Args: cobra.NoArgs, Short: "List environment types", RunE: func(cmd *cobra.Command, args []string) error { cmd.SilenceUsage = true cpc := MustCpClient(cmd.Context()) orgId, err := ShouldOrg(cmd.Context()) if err != nil { return err } allEnvironmentTypes, err := clients.CollectAll( func(pt string) (*cp.ListEnvironmentTypesResponse, error) { return cpc.ListEnvironmentTypesWithResponse(cmd.Context(), orgId, &cp.ListEnvironmentTypesParams{Page: ref.RefStringEmptyNil(pt)}) }, func(r *cp.ListEnvironmentTypesResponse) ([]cp.EnvironmentType, *string) { return r.JSON200.Items, r.JSON200.NextPageToken }, ) if err != nil { return err } printer := MustPrinter(cmd.Context()) return printer.Write(cmd.OutOrStdout(), allEnvironmentTypes) }, }
View Source
var ListEnvironments = &cobra.Command{ Use: "environments <project-id>", Aliases: ObjectTypeEnvironmentAliasesPlural, Args: cobra.ExactArgs(1), Short: "List environments in the project", RunE: func(cmd *cobra.Command, args []string) error { cmd.SilenceUsage = true cpc := MustCpClient(cmd.Context()) orgId, err := ShouldOrg(cmd.Context()) if err != nil { return err } projectId := args[0] allEnvironments, err := clients.CollectAll( func(pt string) (*cp.ListEnvironmentsResponse, error) { return cpc.ListEnvironmentsWithResponse(cmd.Context(), orgId, projectId, &cp.ListEnvironmentsParams{Page: ref.RefStringEmptyNil(pt)}) }, func(r *cp.ListEnvironmentsResponse) ([]cp.Environment, *string) { return r.JSON200.Items, r.JSON200.NextPageToken }, ) if err != nil { return err } printer := MustPrinter(cmd.Context()) return printer.Write(cmd.OutOrStdout(), allEnvironments) }, }
View Source
var ListMetadataKeys = &cobra.Command{ Use: "metadata-keys", Args: cobra.NoArgs, Short: "List organization metadata keys", RunE: func(cmd *cobra.Command, _ []string) error { cmd.SilenceUsage = true orgID, err := ShouldOrg(cmd.Context()) if err != nil { return err } items, err := clients.CollectAll( func(page string) (*dp.ListMetadataKeysResponse, error) { return MustDpClient(cmd.Context()).ListMetadataKeysWithResponse(cmd.Context(), orgID, &dp.ListMetadataKeysParams{Page: ref.RefStringEmptyNil(page)}) }, func(res *dp.ListMetadataKeysResponse) ([]dp.MetadataKey, *string) { return res.JSON200.Items, res.JSON200.NextPageToken }, ) if err != nil { return err } return MustPrinter(cmd.Context()).Write(cmd.OutOrStdout(), items) }, }
View Source
var ListModuleProviders = &cobra.Command{ Use: "providers", Aliases: ObjectTypeProviderAliasesPlural, Args: cobra.NoArgs, Short: "List module providers", RunE: func(cmd *cobra.Command, args []string) error { cmd.SilenceUsage = true cpc := MustCpClient(cmd.Context()) orgId, err := ShouldOrg(cmd.Context()) if err != nil { return err } byType, _ := cmd.Flags().GetString(listModuleProvidersCmdTypeFlag) allModuleProviders, err := clients.CollectAll( func(pt string) (*cp.ListModuleProvidersResponse, error) { return cpc.ListModuleProvidersWithResponse(cmd.Context(), orgId, &cp.ListModuleProvidersParams{ Page: ref.RefStringEmptyNil(pt), ByProviderType: ref.RefStringEmptyNil(byType), }) }, func(r *cp.ListModuleProvidersResponse) ([]cp.ModuleProviderSummary, *string) { return r.JSON200.Items, r.JSON200.NextPageToken }, ) if err != nil { return err } printer := MustPrinter(cmd.Context()) return printer.Write(cmd.OutOrStdout(), allModuleProviders) }, }
View Source
var ListModuleRules = &cobra.Command{ Use: "module-rules", Aliases: ObjectTypeRuleAliasesPlural, Args: cobra.NoArgs, Short: "List module rules", RunE: func(cmd *cobra.Command, args []string) error { cmd.SilenceUsage = true cpc := MustCpClient(cmd.Context()) orgId, err := ShouldOrg(cmd.Context()) if err != nil { return err } byType, _ := cmd.Flags().GetString(listModuleRulesTypeFlag) byModuleId, _ := cmd.Flags().GetString(listModuleRulesModuleFlag) allModuleRules, err := clients.CollectAll( func(pt string) (*cp.ListModuleRulesInOrgResponse, error) { return cpc.ListModuleRulesInOrgWithResponse(cmd.Context(), orgId, &cp.ListModuleRulesInOrgParams{ Page: ref.RefStringEmptyNil(pt), ByResourceType: ref.RefStringEmptyNil(byType), ByModuleId: ref.RefStringEmptyNil(byModuleId), }) }, func(r *cp.ListModuleRulesInOrgResponse) ([]cp.RuleSummary, *string) { return r.JSON200.Items, r.JSON200.NextPageToken }, ) if err != nil { return err } printer := MustPrinter(cmd.Context()) return printer.Write(cmd.OutOrStdout(), allModuleRules) }, }
View Source
var ListModules = &cobra.Command{ Use: "modules", Aliases: ObjectTypeModuleAliasesPlural, Args: cobra.NoArgs, Short: "List modules", RunE: func(cmd *cobra.Command, args []string) error { cmd.SilenceUsage = true cpc := MustCpClient(cmd.Context()) orgId, err := ShouldOrg(cmd.Context()) if err != nil { return err } byType, _ := cmd.Flags().GetString(listModulesTypeFlag) allModules, err := clients.CollectAll( func(pt string) (*cp.ListModulesResponse, error) { return cpc.ListModulesWithResponse(cmd.Context(), orgId, &cp.ListModulesParams{ Page: ref.RefStringEmptyNil(pt), ByResourceType: ref.RefStringEmptyNil(byType), }) }, func(r *cp.ListModulesResponse) ([]cp.ModuleSummary, *string) { return r.JSON200.Items, r.JSON200.NextPageToken }, ) if err != nil { return err } printer := MustPrinter(cmd.Context()) return printer.Write(cmd.OutOrStdout(), allModules) }, }
View Source
var ListPermissions = &cobra.Command{ Use: "permissions", Args: cobra.NoArgs, Short: "List permissions available for configurable roles", RunE: func(cmd *cobra.Command, _ []string) error { cmd.SilenceUsage = true orgID, err := ShouldOrg(cmd.Context()) if err != nil { return err } res, err := MustIamClient(cmd.Context()).ListPermissionsWithResponse(cmd.Context(), orgID) if err != nil { return errors.Wrap(err, "failed to list permissions") } if res.StatusCode() != http.StatusOK { return errors.Errorf("unexpected status code %d when listing permissions: %s", res.StatusCode(), string(res.Body)) } return MustPrinter(cmd.Context()).Write(cmd.OutOrStdout(), res.JSON200.Items) }, }
View Source
var ListProjects = &cobra.Command{ Use: "projects", Aliases: ObjectTypeProjectAliasesPlural, Args: cobra.NoArgs, Short: "List projects", RunE: func(cmd *cobra.Command, args []string) error { cmd.SilenceUsage = true cpc := MustCpClient(cmd.Context()) orgId, err := ShouldOrg(cmd.Context()) if err != nil { return err } allProjects, err := clients.CollectAll( func(pt string) (*cp.ListProjectsResponse, error) { return cpc.ListProjectsWithResponse(cmd.Context(), orgId, &cp.ListProjectsParams{Page: ref.RefStringEmptyNil(pt)}) }, func(r *cp.ListProjectsResponse) ([]cp.Project, *string) { return r.JSON200.Items, r.JSON200.NextPageToken }, ) if err != nil { return err } printer := MustPrinter(cmd.Context()) return printer.Write(cmd.OutOrStdout(), allProjects) }, }
View Source
var ListResourceTypes = &cobra.Command{ Use: "resource-types", Aliases: ObjectTypeResourceTypeAliasesPlural, Args: cobra.NoArgs, Short: "List resource types", RunE: func(cmd *cobra.Command, args []string) error { cmd.SilenceUsage = true cpc := MustCpClient(cmd.Context()) orgId, err := ShouldOrg(cmd.Context()) if err != nil { return err } allResourceTypes, err := clients.CollectAll( func(pt string) (*cp.ListResourceTypesResponse, error) { return cpc.ListResourceTypesWithResponse(cmd.Context(), orgId, &cp.ListResourceTypesParams{Page: ref.RefStringEmptyNil(pt)}) }, func(r *cp.ListResourceTypesResponse) ([]cp.ResourceType, *string) { return r.JSON200.Items, r.JSON200.NextPageToken }, ) if err != nil { return err } printer := MustPrinter(cmd.Context()) return printer.Write(cmd.OutOrStdout(), allResourceTypes) }, }
View Source
var ListRoles = &cobra.Command{ Use: "roles", Args: cobra.NoArgs, Short: "List organization roles", RunE: func(cmd *cobra.Command, _ []string) error { cmd.SilenceUsage = true orgID, err := ShouldOrg(cmd.Context()) if err != nil { return err } items, err := clients.CollectAll( func(page string) (*iam.ListRolesResponse, error) { return MustIamClient(cmd.Context()).ListRolesWithResponse(cmd.Context(), orgID, &iam.ListRolesParams{Page: ref.RefStringEmptyNil(page)}) }, func(res *iam.ListRolesResponse) ([]iam.Role, *string) { return res.JSON200.Items, res.JSON200.NextPageToken }, ) if err != nil { return err } return MustPrinter(cmd.Context()).Write(cmd.OutOrStdout(), items) }, }
View Source
var ListRunnerRules = &cobra.Command{ Use: "runner-rules", Aliases: ObjectTypeRunnerRuleAliasesPlural, Args: cobra.NoArgs, Short: "List runner rules", RunE: func(cmd *cobra.Command, args []string) error { cmd.SilenceUsage = true cpc := MustCpClient(cmd.Context()) orgId, err := ShouldOrg(cmd.Context()) if err != nil { return err } byRunnerId, _ := cmd.Flags().GetString(listRunnerRulesRunnerFlag) allRunnerRules, err := clients.CollectAll( func(pt string) (*cp.ListRunnerRulesInOrgResponse, error) { return cpc.ListRunnerRulesInOrgWithResponse(cmd.Context(), orgId, &cp.ListRunnerRulesInOrgParams{ Page: ref.RefStringEmptyNil(pt), ByRunnerId: ref.RefStringEmptyNil(byRunnerId), }) }, func(r *cp.ListRunnerRulesInOrgResponse) ([]cp.RunnerRuleSummary, *string) { return r.JSON200.Items, r.JSON200.NextPageToken }, ) if err != nil { return err } printer := MustPrinter(cmd.Context()) return printer.Write(cmd.OutOrStdout(), allRunnerRules) }, }
View Source
var ListRunners = &cobra.Command{ Use: "runners", Aliases: ObjectTypeRunnerAliasesPlural, Args: cobra.NoArgs, Short: "List runners", RunE: func(cmd *cobra.Command, args []string) error { cmd.SilenceUsage = true cpc := MustCpClient(cmd.Context()) orgId, err := ShouldOrg(cmd.Context()) if err != nil { return err } allRunners, err := clients.CollectAll( func(pt string) (*cp.ListRunnersResponse, error) { return cpc.ListRunnersWithResponse(cmd.Context(), orgId, &cp.ListRunnersParams{ Page: ref.RefStringEmptyNil(pt), }) }, func(r *cp.ListRunnersResponse) ([]cp.RunnerSummary, *string) { return r.JSON200.Items, r.JSON200.NextPageToken }, ) if err != nil { return err } printer := MustPrinter(cmd.Context()) return printer.Write(cmd.OutOrStdout(), allRunners) }, }
View Source
var ListScimGroupMappings = &cobra.Command{ Use: "scim-group-mappings", Args: cobra.NoArgs, Short: "List SCIM group-to-role mappings", RunE: func(cmd *cobra.Command, _ []string) error { cmd.SilenceUsage = true orgID, err := ShouldOrg(cmd.Context()) if err != nil { return err } res, err := MustIamClient(cmd.Context()).ListScimGroupMappingsWithResponse(cmd.Context(), orgID) if err != nil { return errors.Wrap(err, "failed to list SCIM group mappings") } if res.StatusCode() != http.StatusOK { return errors.Errorf("unexpected status code %d when listing SCIM group mappings: %s", res.StatusCode(), string(res.Body)) } return MustPrinter(cmd.Context()).Write(cmd.OutOrStdout(), res.JSON200.Items) }, }
View Source
var ListServiceUsers = &cobra.Command{ Use: "service-users", Args: cobra.NoArgs, Short: "List service users", RunE: func(cmd *cobra.Command, _ []string) error { cmd.SilenceUsage = true orgID, err := ShouldOrg(cmd.Context()) if err != nil { return err } serviceUsers, err := listAllServiceUsers(cmd, orgID) if err != nil { return errors.Wrap(err, "failed to list service users") } return MustPrinter(cmd.Context()).Write(cmd.OutOrStdout(), serviceUsers) }, }
View Source
var Login = &cobra.Command{ Use: "login", Args: cobra.NoArgs, Short: "Log in to the system", Annotations: map[string]string{ SkipConfigContextAnnotation: stringTrue, }, RunE: func(cmd *cobra.Command, args []string) error { cmd.SilenceUsage = true iamClient := MustIamClient(cmd.Context()) resp, err := iamClient.RequestDeviceLoginWithResponse(cmd.Context(), &iam.RequestDeviceLoginParams{ UserAgent: ref.Ref(fmt.Sprintf("octl %s %s", internal.ModulePath, internal.ModuleVersion)), }, iam.RequestDeviceLoginJSONRequestBody{}) if err != nil { return err } if resp.StatusCode() != 201 { return fmt.Errorf("failed to initiate device login: status code: %d, body: %s", resp.StatusCode(), string(resp.Body)) } successMessageF("Please visit the following URL to login: %s", resp.JSON201.ApprovalUrl) if !noBrowserFlag { if err := openBrowser(resp.JSON201.ApprovalUrl); err != nil { infoMessageF("Failed to open browser automatically: %v", err) } } timeout := time.NewTimer(3 * time.Minute) ticker := time.NewTicker(500 * time.Millisecond) animationTicker := time.NewTicker(500 * time.Millisecond) defer timeout.Stop() defer ticker.Stop() defer animationTicker.Stop() animationCtx, animationCancel := context.WithCancel(cmd.Context()) defer animationCancel() go func() { dots := []string{"", ".", "..", "..."} i := 0 for { select { case <-animationCtx.Done(): return case <-animationTicker.C: fmt.Print("\rWaiting for approval in your browser" + dots[i] + " ") i = (i + 1) % len(dots) } } }() var acceptedRequest *iam.AcceptedDeviceLoginRequest for acceptedRequest == nil { select { case <-timeout.C: stopAnimation(animationCancel) return fmt.Errorf("device login timed out after 3 minutes") case <-ticker.C: pollResp, err := iamClient.PollDeviceLoginRequestWithResponse(cmd.Context(), resp.JSON201.Id, &iam.PollDeviceLoginRequestParams{ PollingToken: resp.JSON201.PollingToken, }) if err != nil { stopAnimation(animationCancel) return fmt.Errorf("failed to poll device login: %v", err) } if pollResp.StatusCode() == 202 { continue } stopAnimation(animationCancel) if pollResp.StatusCode() != 200 { return fmt.Errorf("failed to poll device login: status code: %d, body: %s", pollResp.StatusCode(), string(pollResp.Body)) } acceptedRequest = pollResp.JSON200 } } successMessageF("Login successful!") successMessageF("Token expires at: %s", acceptedRequest.ExpiresAt.Format(time.RFC3339)) cu, err := iamClient.GetCurrentUserWithResponse(cmd.Context(), func(ctx context.Context, req *http.Request) error { req.Header.Set("Authorization", "Bearer "+acceptedRequest.Token) return nil }) if err != nil { return err } else if cu.StatusCode() != http.StatusOK { return errors.Errorf("unexpected status code %d when getting current user using new token: %s", cu.StatusCode(), string(cu.Body)) } orgNames := slices.Sorted(func(yield func(string) bool) { for _, m := range cu.JSON200.OrganizationMemberships { yield(m.Id) } }) cfg, err := config.ReadFile() if err != nil { return fmt.Errorf("failed to read configuration: %v", err) } cfg.Token = acceptedRequest.Token if len(orgNames) == 1 { cfg.DefaultOrg = orgNames[0] successMessageF("We set your org to %s", cfg.DefaultOrg) } else if !slices.Contains(orgNames, cfg.DefaultOrg) { infoMessageF("Warning: User does not belong to configured organization '%s'.", cfg.DefaultOrg) infoMessageF("Consider setting PO_ORG_ID or use 'octl config set-org' to one of the orgs: %s.", strings.Join(orgNames, ", ")) } if err := config.SaveFile(cfg); err != nil { return fmt.Errorf("failed to save configuration: %v", err) } return nil }, }
View Source
var LogsCmd = &cobra.Command{ Use: "logs <deployment-id>", Short: "Get logs for a deployment", Long: `Get logs for a deployment. This command can be used to show deployment logs for a given deployment. Logs are encrypted, so a private key needs to be passed to this command in the 'key' argument. The key is generated during the deployment and can be found in the output of the 'deploy' command. $ octl logs 01234567-89ab-cdef-0123-456789abcdef --key=AGE-SECRET-KEY-1SGKT64UHNGURNZUQSAJ9J0C65R2F2PXDCZQVVGRUPN98L33G2HFSUC24EJ `, Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { deploymentId, err := uuid.Parse(args[0]) if err != nil { return errors.Wrap(err, "deployment ID must be a valid UUID") } secretKey, _ := cmd.Flags().GetString(logsCmdKey) orgId, err := ShouldOrg(cmd.Context()) if err != nil { return err } params := &dp.GetDeploymentLogsParams{} if secretKey != "" { params.DecryptKey = &secretKey } dpClient := MustDpClient(cmd.Context()) if outRes, err := dpClient.GetDeploymentLogsWithResponse(cmd.Context(), orgId, deploymentId, params); err != nil { return errors.Wrap(err, "failed to get deployment logs") } else if outRes.StatusCode() != http.StatusOK { var msg string if outRes.JSON400 != nil { msg = outRes.JSON400.Message } else if outRes.JSON404 != nil { msg = outRes.JSON404.Message } else { msg = string(outRes.Body) } return errors.Errorf("unexpected status code %d when getting deployment logs: %s", outRes.StatusCode(), msg) } else { _, err = cmd.OutOrStdout().Write(outRes.Body) return err } }, }
View Source
var ObjectTypeAvailableResourceTypeAliasesPlural = []string{}
View Source
var ObjectTypeAvailableResourceTypeAliasesSingular = []string{}
View Source
var ObjectTypeDeploymentAliasesPlural = []string{
"deps",
}
View Source
var ObjectTypeDeploymentAliasesSingular = []string{
"dep",
}
View Source
var ObjectTypeEnvironmentAliasesPlural = []string{
"envs",
}
View Source
var ObjectTypeEnvironmentAliasesSingular = []string{
"env",
}
View Source
var ObjectTypeEnvironmentTypeAliasesPlural = []string{
"ets",
"env-types",
"envtypes",
"environmenttypes",
}
View Source
var ObjectTypeEnvironmentTypeAliasesSingular = []string{
"et",
"env-type",
"envtype",
"environmenttype",
}
View Source
var ObjectTypeProjectAliasesPlural = []string{}
View Source
var ObjectTypeProjectAliasesSingular = []string{}
View Source
var ObjectTypeResourceTypeAliasesPlural = []string{
"rts",
"resourcetypes",
}
View Source
var ObjectTypeResourceTypeAliasesSingular = []string{
"rt",
"resourcetype",
}
View Source
var RegenerateCmd = &cobra.Command{ GroupID: CrudGroup.ID, Use: "regenerate <type>", Short: "Regenerate a credential for an object", SilenceErrors: true, PersistentPreRunE: func(cmd *cobra.Command, _ []string) error { out, _ := cmd.Flags().GetString(printer.OutputFormatFlag) ctx, err := withPrinter(cmd.Context(), out, []string{printer.JsonPrinterType, printer.YamlPrinterType}) if err != nil { return err } cmd.SetContext(ctx) return nil }, CompletionOptions: cobra.CompletionOptions{HiddenDefaultCmd: true}, }
View Source
var RegenerateServiceUser = &cobra.Command{ Use: serviceUserUse, Args: cobra.ExactArgs(1), Short: "Regenerate a service-user credential and print its one-time token", RunE: func(cmd *cobra.Command, args []string) error { cmd.SilenceUsage = true serviceUserID, err := uuid.Parse(args[0]) if err != nil { return errors.Wrap(err, "service-user ID must be a UUID") } expiryInDays, err := cmd.Flags().GetInt(expiryInDaysFlag) if err != nil { return err } orgID, err := ShouldOrg(cmd.Context()) if err != nil { return err } res, err := MustIamClient(cmd.Context()).RegenerateServiceUserWithResponse(cmd.Context(), orgID, serviceUserID, iam.ServiceUserRegenerateBody{ExpiryInDays: expiryInDays}) if err != nil { return errors.Wrap(err, "failed to regenerate service-user credential") } switch res.StatusCode() { case http.StatusOK: changedMessageF("Credential for service user %s regenerated. Its token will not be shown again.", serviceUserID) return MustPrinter(cmd.Context()).Write(cmd.OutOrStdout(), *res.JSON200) case http.StatusNotFound: return errors.Errorf("service user '%s' not found in organization '%s'", serviceUserID, orgID) default: return errors.Errorf("unexpected status code %d when regenerating service-user credential: %s", res.StatusCode(), string(res.Body)) } }, }
View Source
var RollbackCmd = &cobra.Command{ Use: "rollback <project-id> <environment-id> <deployment-id>", Args: cobra.ExactArgs(3), Short: "Rollback an environment to the resource graph of a previous deployment.", Long: `Rollback an environment to the resource graph of a previous deployment. $ octl rollback my-project my-env 01234567-89ab-cdef-0123-456789abcdef This will start a new deployment to roll back the environment to the same manifest and resource graph, including pinned module versions, as the deployment with the given id. This will ignore any changes to the modules or module rules that may affect a normal deploy to this environment. Rollback does not revert changes to the runner or provider configurations. Like 'deploy', this command supports --plan-only, --dry-run, and flags for controlling deployment output and logs. `, RunE: func(cmd *cobra.Command, args []string) error { cmd.SilenceUsage = true orgId, err := ShouldOrg(cmd.Context()) if err != nil { return err } projectId := args[0] envId := args[1] targetDeploymentId, err := uuid.Parse(args[2]) if err != nil { return fmt.Errorf("invalid deployment id '%s'", args[2]) } var targetDeployment dp.Deployment infoMessageF("Looking up rollback target deployment '%s'...", targetDeploymentId) if r, err := MustDpClient(cmd.Context()).GetDeploymentWithResponse(cmd.Context(), orgId, targetDeploymentId); err != nil { return err } else if r.StatusCode() == http.StatusNotFound { return fmt.Errorf("deployment '%s' not found in org '%s'", targetDeploymentId, orgId) } else if r.StatusCode() != http.StatusOK { return fmt.Errorf("failed to get deployment '%s'", targetDeploymentId) } else { targetDeployment = *r.JSON200 } if targetDeployment.ProjectId != projectId || targetDeployment.EnvId != envId { return fmt.Errorf("deployment '%s' not found in project '%s' environment '%s'", targetDeploymentId, projectId, envId) } _, lastDeploymentManifest, err := getLastDeploymentManifestForEnvironment(cmd.Context(), orgId, projectId, envId) if err != nil { return err } body := dp.DeploymentCreateBody{ ProjectId: projectId, EnvId: envId, Mode: dp.DeploymentCreateBodyModeRollback, RollbackToDeploymentId: ref.Ref(targetDeploymentId), } if v, _ := cmd.Flags().GetBool(deployCmdPlanOnlyFlag); v { body.PlanOnly = ref.Ref(true) } if v, _ := cmd.Flags().GetBool(deployCmdDryRunFlag); v { body.IsDryRun = v } var outputsAgeKey *age.X25519Identity if e, ok := cmd.Context().Value("ageKey").(*age.X25519Identity); ok { outputsAgeKey = e } else if outputsAgeKey, err = age.GenerateX25519Identity(); err != nil { return fmt.Errorf("failed to generate age key for outputs encryption: %w", err) } body.EncryptedOutputsRecipient = ref.Ref(outputsAgeKey.Recipient().String()) var logsAgeKey *age.X25519Identity if v, _ := cmd.Flags().GetBool(deployCmdSkipLogsFlag); !v { if e, ok := cmd.Context().Value("logsAgeKey").(*age.X25519Identity); ok { logsAgeKey = e } else if logsAgeKey, err = age.GenerateX25519Identity(); err != nil { return fmt.Errorf("failed to generate age key for logs encryption: %w", err) } body.EncryptedLogsRecipient = ref.Ref(logsAgeKey.Recipient().String()) } if v, _ := cmd.Flags().GetString(deployCmdRunnerLogsLevelFlag); !slices.Contains(validRunnerLogsLevels, v) { return fmt.Errorf("unsupported value %s for %s flag", v, deployCmdRunnerLogsLevelFlag) } else { body.RunnerLogLevel = ref.Ref(dp.DeploymentCreateBodyRunnerLogLevel(v)) } if err := commonDeployCmdDiff(targetDeployment.Manifest, lastDeploymentManifest); err != nil { return err } deployment, err := commonDeployCmdInner(cmd, orgId, body, lastDeploymentManifest, logsAgeKey) if err != nil { return err } if body.IsDryRun { return nil } return commonDeploymentOutputHandler(cmd, deployment, outputsAgeKey) }, }
View Source
var RootCmd = &cobra.Command{ Use: "octl", SilenceErrors: true, CompletionOptions: cobra.CompletionOptions{ HiddenDefaultCmd: true, }, PersistentPreRunE: rootPersistentPreRunE, PersistentPostRun: rootPersistentPostRun, }
View Source
var ScoreCmd = &cobra.Command{ Use: "score", Short: "Deploy Score-based workloads to an environment", CompletionOptions: cobra.CompletionOptions{ HiddenDefaultCmd: true, }, }
View Source
var ScoreDeployCmd = &cobra.Command{ Use: "deploy <project-id> <environment-id> <score-file>...", Short: "Deploy one or more Score files to the environment", Long: fmt.Sprintf(`Deploy one or more Score files to the target environment. This works by converting each Score workload into a new workload entry and adding it to the deployment manifest. The workload contains a resource of type "%[1]s" which is provisioned to deploy the workload. This requires that the "%[1]s" resource type is available in your target environment. You can check this with the "octl get available-resource-types <project-id> <environment-id>" command. The resource-type, class, and id can be overridden by adding the '%[2]s', '%[3]s', or '%[4]s' annotations to the Score workload metadata. The command accepts multiple Score files. Each provided Score workload will be added or updated in the deployment manifest but never removed. Use other commands to remove workloads from the deployment manifest. `, scoreDeployDefaultResourceType, scoreAnnotationResType, scoreAnnotationResClass, scoreAnnotationResId), Example: ` # a single score file with default image octl score deploy my-project my-env score.yaml --default-image my-image:latest # multiple score files at once octl score deploy my-project my-env score-1.yaml score-2.yaml score-3.yaml # deploy in plan mode octl score deploy my-project my-env score.yaml --plan-only # deploy in dry run mode octl score deploy my-project my-env score.yaml --dry-run # print the deployment manifest after conversion to standard output and exit octl score deploy my-project my-env score.yaml --print-manifest=- # print the deployment manifest after conversion to a file output and exit octl score deploy my-project my-env score.yaml --print-manifest=manifest.yaml `, Args: cobra.MinimumNArgs(3), RunE: func(cmd *cobra.Command, args []string) error { cmd.SilenceUsage = true projectId, envId, scoreSources := args[0], args[1], args[2:] out, _ := cmd.Flags().GetString(printer.OutputFormatFlag) ctx, err := withPrinter(cmd.Context(), out, []string{printer.JsonPrinterType, printer.YamlPrinterType, printer.TablePrinterType}) if err != nil { return err } cmd.SetContext(ctx) var scoreWorkloads []types.Workload for _, source := range scoreSources { infoMessageF("Loading score file '%s'", source) raw, err := os.ReadFile(source) if err != nil { return errors.Wrapf(err, "failed to read score file '%s'", source) } var rawMap map[string]interface{} if err := yaml.Unmarshal(raw, &rawMap); err != nil { return errors.Wrapf(err, "failed to parse score file as yaml '%s'", source) } if changes, err := schema.ApplyCommonUpgradeTransforms(rawMap); err != nil { return errors.Wrapf(err, "failed to apply common upgrade transforms to score file '%s'", source) } else { for _, change := range changes { infoMessageF("Applied upgrade transform to score file: %s", change) } } if err = schema.Validate(rawMap); err != nil { return errors.Wrapf(err, "score file '%s' is invalid", source) } var workload types.Workload if err = loader.MapSpec(&workload, rawMap); err != nil { return errors.Wrapf(err, "failed to load score file '%s'", source) } for containerName, container := range workload.Containers { if container.Image == "." { if v, _ := cmd.Flags().GetString(scoreDeployCmdDefaultImageFlag); v != "" { container.Image = v infoMessageF("Set container image for container '%s' to %s", containerName, v) workload.Containers[containerName] = container } else { return errors.Errorf("failed to convert '%s' because container '%s' has no image and --%s was not provided", source, containerName, scoreDeployCmdDefaultImageFlag) } } } if err = loader.Normalize(&workload, filepath.Dir(source)); err != nil { return errors.Wrapf(err, "failed to normalize score file '%s'", source) } scoreWorkloads = append(scoreWorkloads, workload) } orgId, err := ShouldOrg(cmd.Context()) if err != nil { return err } if err := checkEnvironmentExistsForDeployment(cmd.Context(), orgId, projectId, envId, cmd); err != nil { return err } _, lastDeploymentManifest, err := getLastDeploymentManifestForEnvironment(cmd.Context(), orgId, projectId, envId) if err != nil { return err } manifest := lastDeploymentManifest manifest.Workloads = maps.Clone(manifest.Workloads) if manifest.Workloads == nil { manifest.Workloads = make(map[string]dp.DeploymentManifestWorkload, max(len(scoreWorkloads), len(manifest.Workloads))) } for _, workload := range scoreWorkloads { workloadResources := make(map[string]dp.DeploymentManifestResource, 1+len(workload.Resources)) if err := rewritePlaceholders(workload); err != nil { return errors.Wrapf(err, "failed to rewrite placeholders in workload '%s'", workload.Metadata["name"].(string)) } for alias, r := range workload.Resources { dmr := dp.DeploymentManifestResource{ Type: r.Type, Class: r.Class, Params: r.Params, } if r.Id != nil { dmr.Id = ref.Ref("shared." + *r.Id) } workloadResources[alias] = dmr } workloadResourceType := scoreDeployDefaultResourceType var workloadClass, workloadId *string if annotations, ok := workload.Metadata["annotations"].(map[string]interface{}); ok { if v, ok := annotations[scoreAnnotationResType].(string); ok && v != "" { workloadResourceType = v } if v, ok := annotations[scoreAnnotationResClass].(string); ok && v != "" { workloadClass = &v } if v, ok := annotations[scoreAnnotationResId].(string); ok && v != "" { workloadId = &v } } workloadResources[scoreDeployDefaultResourceType] = dp.DeploymentManifestResource{ Type: workloadResourceType, Class: workloadClass, Id: workloadId, Params: map[string]interface{}{ "metadata": workload.Metadata, "containers": workload.Containers, "service": ref.DerefOr(workload.Service, types.WorkloadService{}), }, } manifest.Workloads[workload.Metadata["name"].(string)] = dp.DeploymentManifestWorkload{Resources: workloadResources} } if v, _ := cmd.Flags().GetString(scorePrintManifestFlag); v != "" { rawManifest, _ := yaml.Marshal(manifest) successMessageF("Deployment manifest produced by score manifest[s], writing to destination '%s'", v) if v == "-" { _, err = cmd.OutOrStdout().Write(rawManifest) return err } else { if _, err := filepath.Abs(v); err != nil { return errors.Wrapf(err, "deployment manifest file path '%s' was invalid", v) } else { if err := os.WriteFile(v+".tmp", rawManifest, 0600); err != nil { return errors.Wrap(err, "failed to write temporary deployment manifest file") } else if err = os.Rename(v+".tmp", v); err != nil { return errors.Wrap(err, "failed to rename temporary deployment manifest file to output target") } } } return nil } body := dp.DeploymentCreateBody{ ProjectId: projectId, EnvId: envId, Mode: dp.DeploymentCreateBodyModeDeploy, Manifest: &manifest, } if v, _ := cmd.Flags().GetBool(deployCmdPlanOnlyFlag); v { body.Mode = dp.DeploymentCreateBodyModePlanOnly } if v, _ := cmd.Flags().GetBool(deployCmdDryRunFlag); v { body.IsDryRun = v } var logsAgeKey *age.X25519Identity if !body.IsDryRun { if v, _ := cmd.Flags().GetBool(deployCmdSkipLogsFlag); !v { if e, ok := cmd.Context().Value("logsAgeKey").(*age.X25519Identity); ok { logsAgeKey = e } else if logsAgeKey, err = age.GenerateX25519Identity(); err != nil { return errors.Wrap(err, "failed to generate age key for logs encryption") } body.EncryptedLogsRecipient = ref.Ref(logsAgeKey.Recipient().String()) slog.Debug("generated logs encryption identity", slog.String("public recipient", logsAgeKey.Recipient().String())) } if v, _ := cmd.Flags().GetString(deployCmdRunnerLogsLevelFlag); !slices.Contains(validRunnerLogsLevels, v) { return errors.Errorf("unsupported value %s for %s flag", v, deployCmdRunnerLogsLevelFlag) } else { body.RunnerLogLevel = ref.Ref(dp.DeploymentCreateBodyRunnerLogLevel(v)) } } if err := commonDeployCmdDiff(manifest, lastDeploymentManifest); err != nil { return err } _, err = commonDeployCmdInner(cmd, orgId, body, lastDeploymentManifest, logsAgeKey) if err != nil { return err } return nil }, }
View Source
var SetOrg = &cobra.Command{ Use: "set-org <org-id>", Args: cobra.ExactArgs(1), Short: "Set the default organization on all commands unless overridden by environment variable or --org", Annotations: map[string]string{ SkipConfigContextAnnotation: stringTrue, }, RunE: func(cmd *cobra.Command, args []string) error { cmd.SilenceUsage = true org := args[0] cfg, err := config.ReadFile() if err != nil { return errors.Wrap(err, "failed to read config file") } cfg.DefaultOrg = org if err := config.SaveFile(cfg); err != nil { return errors.Wrap(err, "failed to save config file") } successMessageF("Organization set to %s.", org) return nil }, }
View Source
var SetToken = &cobra.Command{ Use: "set-token <token>", Args: cobra.ExactArgs(1), Short: "Set the authentication token", Annotations: map[string]string{ SkipConfigContextAnnotation: stringTrue, }, RunE: func(cmd *cobra.Command, args []string) error { cmd.SilenceUsage = true token := args[0] cfg, err := config.ReadFile() if err != nil { return errors.Wrap(err, "failed to read config file") } cfg.Token = token if err := config.SaveFile(cfg); err != nil { return errors.Wrap(err, "failed to save config file") } successMessageF("Authentication token set successfully.") return nil }, }
View Source
var SetUrl = &cobra.Command{ Use: "set-url <url>", Args: cobra.ExactArgs(1), Short: "Set the API URL prefix (e.g. http://localhost:8080)", Annotations: map[string]string{ SkipConfigContextAnnotation: stringTrue, }, RunE: func(cmd *cobra.Command, args []string) error { cmd.SilenceUsage = true var apiUrl string if parsedUrl, err := url.Parse(args[0]); err != nil { return errors.Wrapf(err, "%s is not a valid url", args[0]) } else { apiUrl = strings.TrimSuffix(parsedUrl.String(), "/") } cfg, err := config.ReadFile() if err != nil { return errors.Wrap(err, "failed to read config file") } cfg.ApiUrl = apiUrl if err := config.SaveFile(cfg); err != nil { return errors.Wrap(err, "failed to save config file") } successMessageF("API URL prefix set to %s.", apiUrl) return nil }, }
View Source
var SetVersionCheck = &cobra.Command{ Use: "set-version-check <enable|disable>", Args: cobra.ExactArgs(1), Short: "Enable or disable automatic version checking", Long: "Enable or disable automatic version checking. When enabled, octl will periodically check for new versions and notify you when updates are available. Disabled by default.", Annotations: map[string]string{ SkipConfigContextAnnotation: stringTrue, }, DisableFlagsInUseLine: true, RunE: func(cmd *cobra.Command, args []string) error { cmd.SilenceUsage = true var disableVersionCheck bool switch strings.ToLower(args[0]) { case stringEnable, stringEnabled, stringYes, stringOn, stringTrue: disableVersionCheck = false case stringDisable, stringDisabled, stringNo, stringOff, stringFalse: disableVersionCheck = true default: return errors.New("invalid value: must be 'enable' or 'disable'") } cfg, err := config.ReadFile() if err != nil { return errors.Wrap(err, "failed to read config file") } cfg.DisableVersionCheck = &disableVersionCheck if err := config.SaveFile(cfg); err != nil { return errors.Wrap(err, "failed to save config file") } if disableVersionCheck { successMessageF("Version checking disabled.") } else { successMessageF("Version checking enabled.") } return nil }, }
View Source
var ShowActiveResourceGraph = &cobra.Command{ Use: "render-active-resource-graph <project-id> <environment-id>", Args: cobra.ExactArgs(2), Short: "Render an HTML graph of the active resource graph for a given environment", RunE: func(cmd *cobra.Command, args []string) error { cmd.SilenceUsage = true dpc := MustDpClient(cmd.Context()) orgId, err := ShouldOrg(cmd.Context()) if err != nil { return err } resp, err := dpc.ListActiveResourceNodesWithResponse(cmd.Context(), orgId, &dp.ListActiveResourceNodesParams{ProjectId: ref.Ref(args[0]), EnvId: ref.Ref(args[1])}) if err != nil { return errors.Wrap(err, "failed to list active resource nodes") } else if resp.StatusCode() == http.StatusNotFound { return errors.New(resp.JSON404.Message) } else if resp.StatusCode() == http.StatusBadRequest { return errors.New(resp.JSON400.Message) } else if resp.StatusCode() != http.StatusOK { return errors.Errorf("unexpected status code %d when listing active resource nodes: %s", resp.StatusCode(), string(resp.Body)) } nodes := slices.Collect(func(yield func(map[string]interface{}) bool) { for _, item := range resp.JSON200.Items { yield(map[string]interface{}{ "id": item.Id, "type": item.ResourceType, "coordinate": fmt.Sprintf("%s.%s#%s", item.ResourceType, item.ResourceClass, item.ResourceId), }) } }) links := slices.Collect(func(yield func(map[string]interface{}) bool) { for _, item := range resp.JSON200.Items { for alias, target := range item.Edges { aliasType := "named" if raw, err := base64.RawStdEncoding.DecodeString(alias); err == nil && len(raw) == 32 { aliasType = "anonymous" } yield(map[string]interface{}{ "source": item.Id, "target": target, "alias": alias, "aliasType": aliasType, }) } } }) tmpl, err := template.New("").Funcs(map[string]any{ "safeJson": func(v interface{}) template.JS { a, _ := json.Marshal(v) return template.JS(a) }, }).Parse(activeResourceGraphTmpl) if err != nil { return errors.Wrap(err, "failed to parse template") } buff := new(bytes.Buffer) if err := tmpl.Execute(buff, map[string]interface{}{ "project_id": args[0], "env_id": args[1], "nodes": nodes, "links": links, }); err != nil { return errors.Wrap(err, "failed to execute template") } outputFlag := GetFlagWithFallback(cmd, "result", "output") if outputFlag == "-" { _, err = cmd.OutOrStdout().Write(buff.Bytes()) return err } var f *os.File if outputFlag == "" { if f, err = os.CreateTemp(os.TempDir(), "platform-orchestrator-active-resource-graph-*.html"); err != nil { return errors.Wrap(err, "failed to create temp file") } } else if f, err = os.Create(outputFlag); err != nil { return errors.Wrap(err, "failed to open output file") } if _, err := f.Write(buff.Bytes()); err != nil { return errors.Wrap(err, "failed to write to output file") } _ = f.Close() _, _ = fmt.Fprintln(cmd.OutOrStdout(), f.Name()) if openFlag, _ := cmd.Flags().GetBool("no-open"); !openFlag { return browser.OpenFile(f.Name()) } return nil }, }
View Source
var ShowConfig = &cobra.Command{ Use: "show", Short: "Show the current configuration", Aliases: []string{"get"}, Annotations: map[string]string{ SkipConfigContextAnnotation: stringTrue, }, PersistentPreRunE: func(cmd *cobra.Command, args []string) error { out, _ := cmd.Flags().GetString(printer.OutputFormatFlag) ctx, err := withPrinter(cmd.Context(), out, []string{printer.JsonPrinterType, printer.YamlPrinterType}) if err != nil { return err } cmd.SetContext(ctx) return nil }, RunE: func(cmd *cobra.Command, args []string) error { cmd.SilenceUsage = true cfg := MustConfiguration(cmd.Context()) printer := MustPrinter(cmd.Context()) return printer.Write(cmd.OutOrStdout(), cfg) }, }
View Source
var UpdateCmd = &cobra.Command{ GroupID: CrudGroup.ID, Use: "update <type>", Short: "Update an object of a given type", SilenceErrors: true, PersistentPreRunE: func(cmd *cobra.Command, args []string) error { out, _ := cmd.Flags().GetString(printer.OutputFormatFlag) ctx, err := withPrinter(cmd.Context(), out, []string{printer.JsonPrinterType, printer.YamlPrinterType}) if err != nil { return err } cmd.SetContext(ctx) return nil }, CompletionOptions: cobra.CompletionOptions{ HiddenDefaultCmd: true, }, }
View Source
var UpdateEnvironment = &cobra.Command{ Use: environmentUse, Aliases: ObjectTypeEnvironmentAliasesSingular, Args: cobra.ExactArgs(2), Short: "Update an environment", Long: fmt.Sprintf(`Update an existing environment in the project. The following fields can be set using --set or --set-json: %s. `, generateTopLevelSetFields(cp.EnvironmentUpdateBody{})), RunE: func(cmd *cobra.Command, args []string) error { cmd.SilenceUsage = true x, err := readSetFlagsIntoType[cp.EnvironmentUpdateBody](cmd) if err != nil { return err } cpc := MustCpClient(cmd.Context()) orgId, err := ShouldOrg(cmd.Context()) if err != nil { return err } projectId := args[0] id := args[1] slog.Debug("Updating environment", slog.String("org_id", orgId), slog.String("project_id", projectId), slog.String("id", id)) if res, err := cpc.UpdateEnvironmentWithResponse(cmd.Context(), orgId, projectId, id, *x); err != nil { return errors.Wrap(err, "failed to update environment") } else if res.StatusCode() == http.StatusNotFound { return errors.Errorf("environment '%s' not found in project '%s' in org '%s'", id, projectId, orgId) } else if res.StatusCode() != http.StatusOK { return errors.Errorf("unexpected status code %d when updating environment: %s", res.StatusCode(), string(res.Body)) } else { successMessageF("Environment %s updated in project %s.", id, projectId) printer := MustPrinter(cmd.Context()) return printer.Write(cmd.OutOrStdout(), *res.JSON200) } }, }
View Source
var UpdateEnvironmentType = &cobra.Command{ Use: environmentTypeUse, Aliases: ObjectTypeEnvironmentTypeAliasesSingular, Args: cobra.ExactArgs(1), Short: "Update an environment type", Long: fmt.Sprintf(`Update an existing environment type in the organization. The following fields can be set using --set or --set-json: %s. `, generateTopLevelSetFields(cp.EnvironmentTypeUpdateBody{})), RunE: func(cmd *cobra.Command, args []string) error { cmd.SilenceUsage = true x, err := readSetFlagsIntoType[cp.EnvironmentTypeUpdateBody](cmd) if err != nil { return err } cpc := MustCpClient(cmd.Context()) orgId, err := ShouldOrg(cmd.Context()) if err != nil { return err } slog.Debug("Updating environment type", slog.String("org_id", orgId), slog.String("id", args[0])) if res, err := cpc.UpdateEnvironmentTypeWithResponse(cmd.Context(), orgId, args[0], *x); err != nil { return errors.Wrap(err, "failed to update environment type") } else if res.StatusCode() == http.StatusNotFound { return SuggestHintByCause(cmd.Context(), HintCauseEnvTypeNotFound, cmd, envTypeNotFoundError(args[0], orgId)) } else if res.StatusCode() != http.StatusOK { return errors.Errorf("unexpected status code %d when updating environment type: %s", res.StatusCode(), string(res.Body)) } else { successMessageF("Environment type %s updated in organization %s.", args[0], orgId) printer := MustPrinter(cmd.Context()) return printer.Write(cmd.OutOrStdout(), *res.JSON200) } }, }
View Source
var UpdateMetadataKey = &cobra.Command{ Use: metadataKeyUse, Args: cobra.ExactArgs(1), Short: "Update an organization metadata key", Long: fmt.Sprintf(`Update an organization metadata key. The following fields can be set using --set, --set-json, or --set-yaml: %s. `, generateTopLevelSetFields(dp.MetadataKeyUpdateBody{})), RunE: func(cmd *cobra.Command, args []string) error { cmd.SilenceUsage = true body, err := readSetFlagsIntoType[dp.MetadataKeyUpdateBody](cmd) if err != nil { return err } orgID, err := ShouldOrg(cmd.Context()) if err != nil { return err } res, err := MustDpClient(cmd.Context()).UpdateMetadataKeyWithResponse(cmd.Context(), orgID, args[0], *body) if err != nil { return errors.Wrap(err, "failed to update metadata key") } switch res.StatusCode() { case http.StatusOK: changedMessageF("Metadata key %q updated in organization %s.", args[0], orgID) return MustPrinter(cmd.Context()).Write(cmd.OutOrStdout(), *res.JSON200) case http.StatusBadRequest: return errors.Errorf("request is invalid: %s", res.JSON400.Message) case http.StatusNotFound: return errors.Errorf("metadata key %q not found in organization '%s'", args[0], orgID) default: return errors.Errorf("unexpected status code %d when updating metadata key: %s", res.StatusCode(), string(res.Body)) } }, }
View Source
var UpdateModule = &cobra.Command{ Use: moduleUse, Aliases: ObjectTypeModuleAliasesSingular, Args: cobra.ExactArgs(1), Short: "Update a module", Long: fmt.Sprintf(`Update a module in the organization. The following fields can be set using --set or --set-json: %s. `, generateTopLevelSetFields(cp.ModuleUpdateBody{})), RunE: func(cmd *cobra.Command, args []string) error { cmd.SilenceUsage = true x, err := readSetFlagsIntoType[cp.ModuleUpdateBody](cmd) if err != nil { return err } cpc := MustCpClient(cmd.Context()) orgId, err := ShouldOrg(cmd.Context()) if err != nil { return err } slog.Debug("Updating module", slog.String("org_id", orgId), slog.String("id", args[0])) if res, err := cpc.UpdateModuleWithResponse(cmd.Context(), orgId, args[0], *x); err != nil { return errors.Wrap(err, "failed to update module") } else if res.StatusCode() == http.StatusBadRequest { return errors.Errorf("request is invalid: %s", res.JSON400.Message) } else if res.StatusCode() == http.StatusNotFound { return errors.Errorf("module '%s' not found in org '%s'", args[0], orgId) } else if res.StatusCode() != http.StatusOK { return errors.Errorf("unexpected status code %d when updating module: %s", res.StatusCode(), string(res.Body)) } else { successMessageF("Module %s updated to version %s in organization %s.", args[0], res.JSON200.VersionId, orgId) printer := MustPrinter(cmd.Context()) return printer.Write(cmd.OutOrStdout(), *res.JSON200) } }, }
View Source
var UpdateModuleProvider = &cobra.Command{ Use: moduleProviderUse, Aliases: ObjectTypeProviderAliasesSingular, Args: cobra.ExactArgs(2), Short: "Update a module provider", Long: fmt.Sprintf(`Update a module provider in the organization. The following fields can be set using --set or --set-json: %s. `, generateTopLevelSetFields(cp.ModuleProviderUpdateBody{})), RunE: func(cmd *cobra.Command, args []string) error { cmd.SilenceUsage = true x, err := readSetFlagsIntoType[cp.ModuleProviderUpdateBody](cmd) if err != nil { return err } cpc := MustCpClient(cmd.Context()) orgId, err := ShouldOrg(cmd.Context()) if err != nil { return err } slog.Debug("Updating module provider", slog.String("org_id", orgId), slog.String("id", args[0])) if res, err := cpc.UpdateModuleProviderWithResponse(cmd.Context(), orgId, args[0], args[1], *x); err != nil { return errors.Wrap(err, "failed to update module provider") } else if res.StatusCode() == http.StatusBadRequest { return errors.Errorf("request is invalid: %s", res.JSON400.Message) } else if res.StatusCode() == http.StatusNotFound { return errors.Errorf("module provider '%s' '%s' not found in org '%s'", args[0], args[1], orgId) } else if res.StatusCode() != http.StatusOK { return errors.Errorf("unexpected status code %d when updating module provider: %s", res.StatusCode(), string(res.Body)) } else { successMessageF("Module provider %s updated in organization %s.", args[0], orgId) printer := MustPrinter(cmd.Context()) return printer.Write(cmd.OutOrStdout(), *res.JSON200) } }, }
View Source
var UpdateProject = &cobra.Command{ Use: projectUse, Aliases: ObjectTypeProjectAliasesSingular, Args: cobra.ExactArgs(1), Short: "Update a project", Long: fmt.Sprintf(`Update an existing project. The following fields can be set using --set or --set-json: %s. `, generateTopLevelSetFields(cp.ProjectUpdateBody{})), RunE: func(cmd *cobra.Command, args []string) error { cmd.SilenceUsage = true x, err := readSetFlagsIntoType[cp.ProjectUpdateBody](cmd) if err != nil { return err } cpc := MustCpClient(cmd.Context()) orgId, err := ShouldOrg(cmd.Context()) if err != nil { return err } id := args[0] slog.Debug("Updating project", slog.String("org_id", orgId), slog.String("id", id)) if res, err := cpc.UpdateProjectWithResponse(cmd.Context(), orgId, id, *x); err != nil { return errors.Wrap(err, "failed to update project") } else if res.StatusCode() == http.StatusNotFound { return errors.Errorf("project '%s' not found in org '%s'", id, orgId) } else if res.StatusCode() != http.StatusOK { return errors.Errorf("unexpected status code %d when updating project: %s", res.StatusCode(), string(res.Body)) } else { successMessageF("Project %s updated in org %s.", id, orgId) printer := MustPrinter(cmd.Context()) return printer.Write(cmd.OutOrStdout(), *res.JSON200) } }, }
View Source
var UpdateResourceType = &cobra.Command{ Use: resourceTypeUse, Aliases: ObjectTypeResourceTypeAliasesSingular, Args: cobra.ExactArgs(1), Short: "Update a resource type", Long: fmt.Sprintf(`Update a resource type in your organization. The following fields can be set using --set or --set-json: %s. `, generateTopLevelSetFields(cp.ResourceTypeUpdateBody{})), RunE: func(cmd *cobra.Command, args []string) error { cmd.SilenceUsage = true x, err := readSetFlagsIntoType[cp.ResourceTypeUpdateBody](cmd) if err != nil { return err } cpc := MustCpClient(cmd.Context()) orgId, err := ShouldOrg(cmd.Context()) if err != nil { return err } slog.Debug("Updating resource type", slog.String("org_id", orgId), slog.String("id", args[0])) if res, err := cpc.UpdateResourceTypeWithResponse(cmd.Context(), orgId, args[0], *x); err != nil { return errors.Wrap(err, "failed to update resource type") } else if res.StatusCode() == http.StatusBadRequest { return errors.Errorf("request is invalid: %s", res.JSON400.Message) } else if res.StatusCode() == http.StatusNotFound { return errors.Errorf("resource type '%s' not found in org '%s'", args[0], orgId) } else if res.StatusCode() != http.StatusOK { return errors.Errorf("unexpected status code %d when updating resource type: %s", res.StatusCode(), string(res.Body)) } else { successMessageF("Resource type %s updated in organization %s.", args[0], orgId) printer := MustPrinter(cmd.Context()) return printer.Write(cmd.OutOrStdout(), *res.JSON200) } }, }
View Source
var UpdateRole = &cobra.Command{ Use: roleUse, Args: cobra.ExactArgs(1), Short: "Replace a configurable role's display name and permissions", Long: fmt.Sprintf(`Replace a configurable role's complete state. The following fields can be set using --set, --set-json, or --set-yaml: %s. `, generateTopLevelSetFields(iam.RoleWriteBody{})), RunE: func(cmd *cobra.Command, args []string) error { cmd.SilenceUsage = true roleID, err := uuid.Parse(args[0]) if err != nil { return errors.Wrap(err, "role ID must be a UUID") } body, err := readSetFlagsIntoType[iam.RoleWriteBody](cmd) if err != nil { return err } orgID, err := ShouldOrg(cmd.Context()) if err != nil { return err } res, err := MustIamClient(cmd.Context()).UpdateRoleWithResponse(cmd.Context(), orgID, roleID, *body) if err != nil { return errors.Wrap(err, "failed to update role") } switch res.StatusCode() { case http.StatusOK: changedMessageF("Role %s updated in organization %s.", roleID, orgID) return MustPrinter(cmd.Context()).Write(cmd.OutOrStdout(), *res.JSON200) case http.StatusBadRequest: return errors.Errorf("request is invalid: %s", res.JSON400.Message) case http.StatusNotFound: return errors.Errorf("role '%s' not found in organization '%s'", roleID, orgID) case http.StatusConflict: return errors.Errorf("role cannot be updated: %s", res.JSON409.Message) default: return errors.Errorf("unexpected status code %d when updating role: %s", res.StatusCode(), string(res.Body)) } }, }
View Source
var UpdateRunner = &cobra.Command{ Use: runnerUse, Aliases: ObjectTypeRunnerAliasesSingular, Args: cobra.ExactArgs(1), Short: "Update a runner by id", Long: fmt.Sprintf(`Update a runner in your organization. The following fields can be set using --set or --set-json: %s. `, generateTopLevelSetFields(cp.RunnerUpdateBody{})), RunE: func(cmd *cobra.Command, args []string) error { cmd.SilenceUsage = true x, err := readSetFlagsIntoType[cp.RunnerUpdateBody](cmd) if err != nil { return err } cpc := MustCpClient(cmd.Context()) orgId, err := ShouldOrg(cmd.Context()) if err != nil { return err } slog.Debug("Updating runner", slog.String("org_id", orgId), slog.String("id", args[0])) if res, err := cpc.UpdateRunnerWithResponse(cmd.Context(), orgId, args[0], *x); err != nil { return errors.Wrap(err, "failed to update runner") } else if res.StatusCode() == http.StatusBadRequest { return errors.Errorf("request is invalid: %s", res.JSON400.Message) } else if res.StatusCode() == http.StatusNotFound { return errors.Errorf("runner '%s' not found in org '%s'", args[0], orgId) } else if res.StatusCode() != http.StatusOK { return errors.Errorf("unexpected status code %d when updating runner: %s", res.StatusCode(), string(res.Body)) } else { successMessageF("Runner %s updated in organization %s.", args[0], orgId) printer := MustPrinter(cmd.Context()) return printer.Write(cmd.OutOrStdout(), *res.JSON200) } }, }
View Source
var UpdateScimGroupMapping = newUpsertScimGroupMappingCommand("Replace a SCIM group-to-role mapping")
View Source
var UpdateServiceUser = &cobra.Command{ Use: serviceUserUse, Args: cobra.ExactArgs(1), Short: "Replace all role assignments for a service user", Long: fmt.Sprintf(`Replace all role assignments for a service user. This is an authoritative replacement. The following fields can be set using --set, --set-json, or --set-yaml: %s. `, generateTopLevelSetFields(iam.ReplaceServiceUserRolesBody{})), RunE: func(cmd *cobra.Command, args []string) error { cmd.SilenceUsage = true serviceUserID, err := uuid.Parse(args[0]) if err != nil { return errors.Wrap(err, "service-user ID must be a UUID") } body, err := readSetFlagsIntoType[iam.ReplaceServiceUserRolesBody](cmd) if err != nil { return err } orgID, err := ShouldOrg(cmd.Context()) if err != nil { return err } res, err := MustIamClient(cmd.Context()).ReplaceServiceUserRolesWithResponse(cmd.Context(), orgID, serviceUserID, *body) if err != nil { return errors.Wrap(err, "failed to replace service-user roles") } switch res.StatusCode() { case http.StatusOK: changedMessageF("Role assignments for service user %s replaced in organization %s.", serviceUserID, orgID) return MustPrinter(cmd.Context()).Write(cmd.OutOrStdout(), *res.JSON200) case http.StatusBadRequest: return errors.Errorf("request is invalid: %s", res.JSON400.Message) case http.StatusNotFound: return errors.Errorf("service user or role not found in organization '%s'", orgID) case http.StatusConflict: return errors.Errorf("service-user roles cannot be replaced: %s", res.JSON409.Message) default: return errors.Errorf("unexpected status code %d when replacing service-user roles: %s", res.StatusCode(), string(res.Body)) } }, }
Functions ¶
func FindCommandTreeAnnotation ¶
FindCommandTreeAnnotation returns the first value set for the given annotation, or returns an empty string.
func GetFlagWithFallback ¶
func MustCpClient ¶
func MustCpClient(c context.Context) cp.ClientWithResponsesInterface
func MustDpClient ¶
func MustDpClient(c context.Context) dp.ClientWithResponsesInterface
func MustIamClient ¶
func MustIamClient(c context.Context) iam.ClientWithResponsesInterface
func PromptTextAndEnterToContinue ¶
PromptTextAndEnterToContinue attempts to wait for the required text and an enter character on stdin. An interrupt will cancel the context or will interrupt the whole process, either way closing the goroutine.
func PromptYesNo ¶
PromptYesNo prompts the user with a yes/no question and returns true if the user confirms with yes/y/Y. Returns false for any other input. An error is returned only on read failure or timeout.
Types ¶
type HintCommand ¶
type HintCommand struct {
// contains filtered or unexported fields
}
Source Files
¶
- active_resources.go
- annotations.go
- available_resource_types.go
- config.go
- create.go
- ctx.go
- current_user.go
- delete.go
- deploy.go
- deploy_rollback.go
- deployments.go
- environment_types.go
- environments.go
- flags.go
- get.go
- hints.go
- io.go
- login.go
- logs.go
- manifest.go
- manifest_overrides.go
- metadata_keys.go
- module_definitions.go
- module_providers.go
- module_rules.go
- projects.go
- regenerate.go
- resource_types.go
- roles.go
- root.go
- runner_rules.go
- runners.go
- scim_group_mappings.go
- score.go
- service_users.go
- tf.go
- update.go
- utils.go
Click to show internal directories.
Click to hide internal directories.