Generate new version of SDK resources and Add Tests (#331)

This commit is contained in:
Todd Knight authored and GitHub committed 2020-09-08 16:27:51 -04:00
1 parent 96e4b1cdba
commit c3ecea172d
93 files changed
+3414 -2826

No files matched your search

+1 -37
View File
@@ -53,7 +53,6 @@ type Command struct {
flagsOnce sync.Once
flagAddr string
flagScope string
flagVerbose bool
flagTLSCACert string
@@ -69,6 +68,7 @@ type Command struct {
FlagRecoveryConfig string
flagOutputCurlString bool
FlagScopeId string
FlagId string
FlagName string
FlagDescription string
@@ -233,39 +233,12 @@ func (c *Command) Client(opt ...Option) (*api.Client, error) {
c.UI.Error(fmt.Sprintf("Error unmarshaling stored token information after reading from system credential store: %s", err))
} else {
c.client.SetToken(authToken.Token)
if !opts.withNoTokenScope {
c.client.SetScopeId(authToken.Scope.Id)
}
}
}
}
}
}
// We do this here so we override the stored token info if it's set above
if c.flagScope != NotSetValue {
c.client.SetScopeId(c.flagScope)
if c.flagFormat == "table" && c.flagVerbose {
if c.flagScope == os.Getenv("BOUNDARY_TOKEN") {
c.UI.Info(fmt.Sprintf("Scope of %q set from BOUNDARY_TOKEN env var", c.flagScope))
} else {
c.UI.Info(fmt.Sprintf("Scope of %q set from -scope command flag", c.flagScope))
}
}
} else if c.client.ScopeId() != "" && !opts.withNoTokenScope {
// If it didn't come from env or a flag but isn't empty, it must have come from the token
if c.flagFormat == "table" && c.flagVerbose {
c.UI.Info(fmt.Sprintf("Scope of %q set from saved token with name %q", c.client.ScopeId(), tokenName))
}
}
// At this point if we haven't figured out the scope, default to "global"
if c.client.ScopeId() == "" {
c.client.SetScopeId("global")
if c.flagFormat == "table" && c.flagVerbose {
c.UI.Info(`Scope of "global" set by default`)
}
}
if opts.withNoTokenValue {
c.client.SetToken("")
}
@@ -300,15 +273,6 @@ func (c *Command) FlagSet(bit FlagSetBit) *FlagSets {
Usage: "Addr of the Boundary controller, as a complete URL (e.g. https://boundary.example.com:9200).",
})
f.StringVar(&StringVar{
Name: FlagNameScope,
Target: &c.flagScope,
Default: NotSetValue,
EnvVar: api.EnvBoundaryScopeId,
Completion: complete.PredictAnything,
Usage: `Scope in which to make the request. If not specified, will default to the scope of a saved token (if found), otherwise will default to "global".`,
})
f.StringVar(&StringVar{
Name: FlagNameCACert,
Target: &c.flagTLSCACert,
-3
View File
@@ -4,9 +4,6 @@ const (
// FlagNameAddr is the flag used in the base command to read in the
// address of the Boundary server.
FlagNameAddr = "addr"
// FlagNameScope is the flag used in the base command to read in the scope
// in which to make a request.
FlagNameScope = "scope"
// FlagnameCACert is the flag used in the base command to read in the CA
// cert.
FlagNameCACert = "ca-cert"
+1 -1
View File
@@ -51,7 +51,7 @@ func WrapSlice(prefixSpaces int, input []string) string {
for _, v := range input {
ret = append(ret, fmt.Sprintf("%s%s",
strings.Repeat(" ", prefixSpaces),
fmt.Sprintf("%s: ", v),
v,
))
}
+172 -2
View File
@@ -6,6 +6,7 @@ import (
"syscall"
"github.com/hashicorp/boundary/internal/cmd/base"
"github.com/hashicorp/boundary/internal/cmd/commands/accounts"
"github.com/hashicorp/boundary/internal/cmd/commands/authenticate"
"github.com/hashicorp/boundary/internal/cmd/commands/authmethods"
"github.com/hashicorp/boundary/internal/cmd/commands/authtokens"
@@ -19,6 +20,7 @@ import (
"github.com/hashicorp/boundary/internal/cmd/commands/proxy"
"github.com/hashicorp/boundary/internal/cmd/commands/roles"
"github.com/hashicorp/boundary/internal/cmd/commands/scopes"
"github.com/hashicorp/boundary/internal/cmd/commands/targets"
"github.com/hashicorp/boundary/internal/cmd/commands/users"
"github.com/hashicorp/boundary/internal/cmd/commands/worker"
@@ -77,6 +79,66 @@ func initCommands(ui, serverCmdUi cli.Ui, runOpts *RunOptions) {
}, nil
},
"accounts": func() (cli.Command, error) {
return &accounts.Command{
Command: base.NewCommand(ui),
}, nil
},
"accounts read": func() (cli.Command, error) {
return &accounts.Command{
Command: base.NewCommand(ui),
Func: "read",
}, nil
},
"accounts delete": func() (cli.Command, error) {
return &accounts.Command{
Command: base.NewCommand(ui),
Func: "delete",
}, nil
},
"accounts list": func() (cli.Command, error) {
return &accounts.Command{
Command: base.NewCommand(ui),
Func: "list",
}, nil
},
"accounts set-password": func() (cli.Command, error) {
return &accounts.Command{
Command: base.NewCommand(ui),
Func: "set-password",
}, nil
},
"accounts change-password": func() (cli.Command, error) {
return &accounts.Command{
Command: base.NewCommand(ui),
Func: "change-password",
}, nil
},
"accounts create": func() (cli.Command, error) {
return &accounts.Command{
Command: base.NewCommand(ui),
Func: "create",
}, nil
},
"accounts create password": func() (cli.Command, error) {
return &accounts.PasswordCommand{
Command: base.NewCommand(ui),
Func: "create",
}, nil
},
"accounts update": func() (cli.Command, error) {
return &accounts.Command{
Command: base.NewCommand(ui),
Func: "update",
}, nil
},
"accounts update password": func() (cli.Command, error) {
return &accounts.PasswordCommand{
Command: base.NewCommand(ui),
Func: "update",
}, nil
},
"auth-methods": func() (cli.Command, error) {
return &authmethods.Command{
Command: base.NewCommand(ui),
@@ -335,11 +397,53 @@ func initCommands(ui, serverCmdUi cli.Ui, runOpts *RunOptions) {
}, nil
},
"hosts create": func() (cli.Command, error) {
return &hosts.CreateCommand{
"hosts": func() (cli.Command, error) {
return &hosts.Command{
Command: base.NewCommand(ui),
}, nil
},
"hosts read": func() (cli.Command, error) {
return &hosts.Command{
Command: base.NewCommand(ui),
Func: "read",
}, nil
},
"hosts delete": func() (cli.Command, error) {
return &hosts.Command{
Command: base.NewCommand(ui),
Func: "delete",
}, nil
},
"hosts list": func() (cli.Command, error) {
return &hosts.Command{
Command: base.NewCommand(ui),
Func: "list",
}, nil
},
"hosts create": func() (cli.Command, error) {
return &hosts.Command{
Command: base.NewCommand(ui),
Func: "create",
}, nil
},
"hosts create static": func() (cli.Command, error) {
return &hosts.StaticCommand{
Command: base.NewCommand(ui),
Func: "create",
}, nil
},
"hosts update": func() (cli.Command, error) {
return &hosts.Command{
Command: base.NewCommand(ui),
Func: "update",
}, nil
},
"hosts update static": func() (cli.Command, error) {
return &hosts.StaticCommand{
Command: base.NewCommand(ui),
Func: "update",
}, nil
},
"roles": func() (cli.Command, error) {
return &roles.Command{
@@ -449,6 +553,72 @@ func initCommands(ui, serverCmdUi cli.Ui, runOpts *RunOptions) {
}, nil
},
"targets": func() (cli.Command, error) {
return &targets.Command{
Command: base.NewCommand(ui),
}, nil
},
"targets read": func() (cli.Command, error) {
return &targets.Command{
Command: base.NewCommand(ui),
Func: "read",
}, nil
},
"targets delete": func() (cli.Command, error) {
return &targets.Command{
Command: base.NewCommand(ui),
Func: "delete",
}, nil
},
"targets list": func() (cli.Command, error) {
return &targets.Command{
Command: base.NewCommand(ui),
Func: "list",
}, nil
},
"targets create": func() (cli.Command, error) {
return &targets.Command{
Command: base.NewCommand(ui),
Func: "create",
}, nil
},
"targets create tcp": func() (cli.Command, error) {
return &targets.TcpCommand{
Command: base.NewCommand(ui),
Func: "create",
}, nil
},
"targets update": func() (cli.Command, error) {
return &targets.Command{
Command: base.NewCommand(ui),
Func: "update",
}, nil
},
"targets update tcp": func() (cli.Command, error) {
return &targets.TcpCommand{
Command: base.NewCommand(ui),
Func: "update",
}, nil
},
"targets add-host-sets": func() (cli.Command, error) {
return &targets.Command{
Command: base.NewCommand(ui),
Func: "add-host-sets",
}, nil
},
"targets remove-host-sets": func() (cli.Command, error) {
return &targets.Command{
Command: base.NewCommand(ui),
Func: "remove-host-sets",
}, nil
},
"targets set-host-sets": func() (cli.Command, error) {
return &targets.Command{
Command: base.NewCommand(ui),
Func: "set-host-sets",
}, nil
},
"users": func() (cli.Command, error) {
return &users.Command{
Command: base.NewCommand(ui),
+375
View File
@@ -0,0 +1,375 @@
package accounts
import (
"fmt"
"os"
"strings"
"github.com/hashicorp/boundary/api"
"github.com/hashicorp/boundary/api/accounts"
"github.com/hashicorp/boundary/internal/cmd/base"
"github.com/hashicorp/boundary/internal/cmd/common"
"github.com/hashicorp/boundary/internal/types/resource"
"github.com/hashicorp/vault/sdk/helper/password"
"github.com/hashicorp/vault/sdk/helper/strutil"
"github.com/kr/pretty"
"github.com/mitchellh/cli"
"github.com/posener/complete"
)
var _ cli.Command = (*Command)(nil)
var _ cli.CommandAutocomplete = (*Command)(nil)
type Command struct {
*base.Command
Func string
flagAuthMethodId string
flagPassword string
flagCurrentPassword string
flagNewPassword string
}
func (c *Command) Synopsis() string {
switch c.Func {
case "create":
return "Create account resources within Boundary"
case "update":
return "Update account resources within Boundary"
default:
return common.SynopsisFunc(c.Func, "account")
}
}
var flagsMap = map[string][]string{
"read": {"id"},
"delete": {"id"},
"list": {"auth-method-id"},
"set-password": {"id", "password", "version"},
"change-password": {"id", "current-password", "new-password", "version"},
}
func (c *Command) Help() string {
helpMap := common.HelpMap("account")
var helpStr string
switch c.Func {
case "":
return base.WrapForHelpText([]string{
"Usage: boundary accounts [sub command] [options] [args]",
"",
" This command allows operations on Boundary account resources. Example:",
"",
" Read a account:",
"",
` $ boundary accounts read -id apw_1234567890`,
"",
" Please see the accounts subcommand help for detailed usage information.",
})
case "create":
helpStr = base.WrapForHelpText([]string{
"Usage: boundary accounts create [type] [sub command] [options] [args]",
"",
" This command allows create operations on Boundary account resources. Example:",
"",
" Create a password-type account:",
"",
` $ boundary accounts create password -name prodops -description "For ProdOps usage"`,
"",
" Please see the typed subcommand help for detailed usage information.",
})
case "update":
helpStr = base.WrapForHelpText([]string{
"Usage: boundary accounts update [type] [sub command] [options] [args]",
"",
" This command allows update operations on Boundary account resources. Example:",
"",
" Update a password-type account:",
"",
` $ boundary accounts update password -id apw_1234567890 -name devops -description "For DevOps usage"`,
"",
" Please see the typed subcommand help for detailed usage information.",
})
case "set-password":
helpStr = base.WrapForHelpText([]string{
"Usage: boundary accounts set-password [sub command] [options] [args]",
"",
" This command allows setting the password on account-type resources, if the types match and the operation is allowed by the given account type. Example:",
"",
" Set the password on a password-type account:",
"",
` $ boundary accounts set-password -id apw_1234567890 -password <empty, to be read by stdin>`,
})
case "change-password":
helpStr = base.WrapForHelpText([]string{
"Usage: boundary accounts change-password [sub command] [options] [args]",
"",
" This command allows changing the password (with verification of the current password) on account-type resources, if the types match and the operation is allowed by the given account type. Example:",
"",
" Change the password on a password-type account:",
"",
` $ boundary accounts change-password -id apw_1234567890 -current-password <empty, to be read by stdin> -new-password <empty, to be read by stdin>`,
})
default:
helpStr = helpMap[c.Func]()
}
return helpStr + c.Flags().Help()
}
func (c *Command) Flags() *base.FlagSets {
set := c.FlagSet(base.FlagSetHTTP | base.FlagSetClient | base.FlagSetOutputFormat)
f := set.NewFlagSet("Command Options")
if len(flagsMap[c.Func]) > 0 {
common.PopulateCommonFlags(c.Command, f, resource.Account.String(), flagsMap[c.Func])
}
for _, name := range flagsMap[c.Func] {
switch name {
case "auth-method-id":
f.StringVar(&base.StringVar{
Name: "auth-method-id",
Target: &c.flagAuthMethodId,
Usage: "The auth-method resource in which to create or update the account resource",
})
case "password":
f.StringVar(&base.StringVar{
Name: "password",
Target: &c.flagPassword,
Usage: "The password for the account. If not specified, the command will prompt for the password to be entered in a non-echoing way.",
})
case "current-password":
f.StringVar(&base.StringVar{
Name: "current-password",
Target: &c.flagCurrentPassword,
Usage: "The current password for the account. If not specified, the command will prompt for the password to be entered in a non-echoing way.",
})
case "new-password":
f.StringVar(&base.StringVar{
Name: "new-password",
Target: &c.flagNewPassword,
Usage: "The new password for the account. If not specified, the command will prompt for the password to be entered in a non-echoing way.",
})
}
}
return set
}
func (c *Command) AutocompleteArgs() complete.Predictor {
return complete.PredictAnything
}
func (c *Command) AutocompleteFlags() complete.Flags {
return c.Flags().Completions()
}
func (c *Command) Run(args []string) int {
switch c.Func {
case "", "create", "update":
return cli.RunResultHelp
}
f := c.Flags()
if err := f.Parse(args); err != nil {
c.UI.Error(err.Error())
return 1
}
if strutil.StrListContains(flagsMap[c.Func], "id") && c.FlagId == "" {
c.UI.Error("ID is required but not passed in via -id")
return 1
}
if strutil.StrListContains(flagsMap[c.Func], "auth-method-id") && c.flagAuthMethodId == "" {
c.UI.Error("Auth Method ID must be passed in via -auth-method-id")
return 1
}
client, err := c.Client()
if err != nil {
c.UI.Error(fmt.Sprintf("Error creating API client: %s", err.Error()))
return 2
}
var opts []accounts.Option
switch c.FlagName {
case "":
case "null":
opts = append(opts, accounts.DefaultName())
default:
opts = append(opts, accounts.WithName(c.FlagName))
}
switch c.FlagDescription {
case "":
case "null":
opts = append(opts, accounts.DefaultDescription())
default:
opts = append(opts, accounts.WithDescription(c.FlagDescription))
}
if strutil.StrListContains(flagsMap[c.Func], "password") && c.flagPassword == "" {
fmt.Print("Password is not set as flag, please enter it now (will be hidden): ")
value, err := password.Read(os.Stdin)
fmt.Print("\n")
if err != nil {
c.UI.Error(fmt.Sprintf("An error occurred attempting to read the password. The raw error message is shown below but usually this is because you attempted to pipe a value into the command or you are executing outside of a terminal (TTY). The raw error was:\n\n%s", err.Error()))
return 2
}
c.flagPassword = strings.TrimSpace(value)
}
if strutil.StrListContains(flagsMap[c.Func], "current-password") && c.flagCurrentPassword == "" {
fmt.Print("Current password is not set as flag, please enter it now (will be hidden): ")
value, err := password.Read(os.Stdin)
fmt.Print("\n")
if err != nil {
c.UI.Error(fmt.Sprintf("An error occurred attempting to read the password. The raw error message is shown below but usually this is because you attempted to pipe a value into the command or you are executing outside of a terminal (TTY). The raw error was:\n\n%s", err.Error()))
return 2
}
c.flagCurrentPassword = strings.TrimSpace(value)
}
if strutil.StrListContains(flagsMap[c.Func], "new-password") && c.flagNewPassword == "" {
fmt.Print("New password is not set as flag, please enter it now (will be hidden): ")
value, err := password.Read(os.Stdin)
fmt.Print("\n")
if err != nil {
c.UI.Error(fmt.Sprintf("An error occurred attempting to read the password. The raw error message is shown below but usually this is because you attempted to pipe a value into the command or you are executing outside of a terminal (TTY). The raw error was:\n\n%s", err.Error()))
return 2
}
c.flagNewPassword = strings.TrimSpace(value)
}
// Perform check-and-set when needed
var version uint32
switch c.Func {
case "create":
// These don't update so don't need the existing version
default:
switch c.FlagVersion {
case 0:
opts = append(opts, accounts.WithAutomaticVersioning(true))
default:
version = uint32(c.FlagVersion)
}
}
accountClient := accounts.NewClient(client)
var existed bool
var account *accounts.Account
var listedAccounts []*accounts.Account
var apiErr *api.Error
switch c.Func {
case "read":
account, apiErr, err = accountClient.Read(c.Context, c.FlagId, opts...)
case "delete":
existed, apiErr, err = accountClient.Delete(c.Context, c.FlagId, opts...)
case "list":
listedAccounts, apiErr, err = accountClient.List(c.Context, c.flagAuthMethodId, opts...)
case "set-password":
account, apiErr, err = accountClient.SetPassword(c.Context, c.FlagId, c.flagPassword, version, opts...)
case "change-password":
account, apiErr, err = accountClient.ChangePassword(c.Context, c.FlagId, c.flagCurrentPassword, c.flagNewPassword, version, opts...)
}
plural := "account"
if c.Func == "list" {
plural = "accounts"
}
if err != nil {
c.UI.Error(fmt.Sprintf("Error trying to %s %s: %s", c.Func, plural, err.Error()))
return 2
}
if apiErr != nil {
c.UI.Error(fmt.Sprintf("Error from controller when performing %s on %s: %s", c.Func, plural, pretty.Sprint(apiErr)))
return 1
}
switch c.Func {
case "delete":
switch base.Format(c.UI) {
case "json":
c.UI.Output("null")
case "table":
output := "The delete operation completed successfully"
switch existed {
case true:
output += "."
default:
output += ", however the resource did not exist at the time."
}
c.UI.Output(output)
}
return 0
case "list":
switch base.Format(c.UI) {
case "json":
if len(listedAccounts) == 0 {
c.UI.Output("null")
return 0
}
b, err := base.JsonFormatter{}.Format(listedAccounts)
if err != nil {
c.UI.Error(fmt.Errorf("Error formatting as JSON: %w", err).Error())
return 1
}
c.UI.Output(string(b))
case "table":
if len(listedAccounts) == 0 {
c.UI.Output("No accounts found")
return 0
}
var output []string
output = []string{
"",
"Account information:",
}
for i, m := range listedAccounts {
if i > 0 {
output = append(output, "")
}
if true {
output = append(output,
fmt.Sprintf(" ID: %s", m.Id),
fmt.Sprintf(" Version: %d", m.Version),
fmt.Sprintf(" Type: %s", m.Type),
)
}
if m.Name != "" {
output = append(output,
fmt.Sprintf(" Name: %s", m.Name),
)
}
if m.Description != "" {
output = append(output,
fmt.Sprintf(" Description: %s", m.Description),
)
}
}
c.UI.Output(base.WrapForHelpText(output))
}
return 0
}
switch base.Format(c.UI) {
case "table":
c.UI.Output(generateAccountTableOutput(account))
case "json":
b, err := base.JsonFormatter{}.Format(account)
if err != nil {
c.UI.Error(fmt.Errorf("Error formatting as JSON: %w", err).Error())
return 1
}
c.UI.Output(string(b))
}
return 0
}
+74
View File
@@ -0,0 +1,74 @@
package accounts
import (
"fmt"
"time"
"github.com/hashicorp/boundary/api/accounts"
"github.com/hashicorp/boundary/internal/cmd/base"
)
func generateAccountTableOutput(in *accounts.Account) string {
var ret []string
nonAttributeMap := map[string]interface{}{
"ID": in.Id,
"Scope ID": in.Scope.Id,
"Version": in.Version,
"Type": in.Type,
"Created Time": in.CreatedTime.Local().Format(time.RFC3339),
"Updated Time": in.UpdatedTime.Local().Format(time.RFC3339),
"Auth Method ID": in.AuthMethodId,
}
if in.Name != "" {
nonAttributeMap["Name"] = in.Name
}
if in.Description != "" {
nonAttributeMap["Description"] = in.Description
}
maxLength := 0
for k := range nonAttributeMap {
if len(k) > maxLength {
maxLength = len(k)
}
}
if len(in.Attributes) > 0 {
for k, v := range in.Attributes {
if attributeMap[k] != "" {
in.Attributes[attributeMap[k]] = v
delete(in.Attributes, k)
}
}
for k := range in.Attributes {
if len(k) > maxLength {
maxLength = len(k)
}
}
}
ret = append(ret, "", "Account information:")
ret = append(ret,
// We do +2 because there is another +2 offset for attributes below
base.WrapMap(2, maxLength+2, nonAttributeMap),
)
if len(in.Attributes) > 0 {
if true {
ret = append(ret,
fmt.Sprintf(" Attributes: %s", ""),
)
}
ret = append(ret,
base.WrapMap(4, maxLength, in.Attributes),
)
}
return base.WrapForHelpText(ret)
}
var attributeMap = map[string]string{
"login_name": "Login Name",
}
+242
View File
@@ -0,0 +1,242 @@
package accounts
import (
"fmt"
"net/textproto"
"os"
"strings"
"github.com/hashicorp/boundary/api"
"github.com/hashicorp/boundary/api/accounts"
"github.com/hashicorp/boundary/internal/cmd/base"
"github.com/hashicorp/boundary/internal/cmd/common"
"github.com/hashicorp/vault/sdk/helper/password"
"github.com/hashicorp/vault/sdk/helper/strutil"
"github.com/kr/pretty"
"github.com/mitchellh/cli"
"github.com/posener/complete"
)
var _ cli.Command = (*PasswordCommand)(nil)
var _ cli.CommandAutocomplete = (*PasswordCommand)(nil)
type PasswordCommand struct {
*base.Command
Func string
flagAuthMethodId string
flagLoginName string
flagPassword string
}
func (c *PasswordCommand) Synopsis() string {
return fmt.Sprintf("%s a password-type account within Boundary", textproto.CanonicalMIMEHeaderKey(c.Func))
}
var passwordFlagsMap = map[string][]string{
"create": {"auth-method-id", "name", "description", "login-name", "password"},
"update": {"id", "name", "description", "version"},
}
func (c *PasswordCommand) Help() string {
var info string
switch c.Func {
case "create":
info = base.WrapForHelpText([]string{
"Usage: boundary accounts password create [options] [args]",
"",
" Create a password-type account. Example:",
"",
` $ boundary accounts password create -name prodops -description "Password account for ProdOps" -address "127.0.0.1"`,
"",
"",
})
case "update":
info = base.WrapForHelpText([]string{
"Usage: boundary accounts password update [options] [args]",
"",
" Update a password-type account given its ID. Example:",
"",
` $ boundary accounts password update -id hst_1234567890 -name "devops" -description "Password account for DevOps" -address "10.20.30.40"`,
"",
"",
})
}
return info + c.Flags().Help()
}
func (c *PasswordCommand) Flags() *base.FlagSets {
set := c.FlagSet(base.FlagSetHTTP | base.FlagSetClient | base.FlagSetOutputFormat)
f := set.NewFlagSet("Command Options")
if len(passwordFlagsMap[c.Func]) > 0 {
common.PopulateCommonFlags(c.Command, f, "password-type account", passwordFlagsMap[c.Func])
}
for _, name := range passwordFlagsMap[c.Func] {
switch name {
case "auth-method-id":
f.StringVar(&base.StringVar{
Name: "auth-method-id",
Target: &c.flagAuthMethodId,
Usage: "The auth-method resource in which to create or update the account resource",
})
}
}
f = set.NewFlagSet("Password Account Options")
for _, name := range passwordFlagsMap[c.Func] {
switch name {
case "login-name":
f.StringVar(&base.StringVar{
Name: "login-name",
Target: &c.flagLoginName,
Usage: "The login name for the account",
})
case "password":
f.StringVar(&base.StringVar{
Name: "password",
Target: &c.flagPassword,
Usage: "The password for the account. If not specified, the command will prompt for the password to be entered in a non-echoing way.",
})
}
}
return set
}
func (c *PasswordCommand) AutocompleteArgs() complete.Predictor {
return complete.PredictAnything
}
func (c *PasswordCommand) AutocompleteFlags() complete.Flags {
return c.Flags().Completions()
}
func (c *PasswordCommand) Run(args []string) int {
if c.Func == "" {
return cli.RunResultHelp
}
f := c.Flags()
if err := f.Parse(args); err != nil {
c.UI.Error(err.Error())
return 1
}
if strutil.StrListContains(passwordFlagsMap[c.Func], "id") && c.FlagId == "" {
c.UI.Error("ID is required but not passed in via -id")
return 1
}
if strutil.StrListContains(passwordFlagsMap[c.Func], "auth-method-id") && c.flagAuthMethodId == "" {
c.UI.Error("Auth Method ID must be passed in via -auth-method-id")
return 1
}
if c.Func == "create" && c.flagLoginName == "" {
c.UI.Error("Login Name must be passed in via -login-name")
return 1
}
client, err := c.Client()
if err != nil {
c.UI.Error(fmt.Sprintf("Error creating API client: %s", err.Error()))
return 2
}
var opts []accounts.Option
switch c.FlagName {
case "":
case "null":
opts = append(opts, accounts.DefaultName())
default:
opts = append(opts, accounts.WithName(c.FlagName))
}
switch c.FlagDescription {
case "":
case "null":
opts = append(opts, accounts.DefaultDescription())
default:
opts = append(opts, accounts.WithDescription(c.FlagDescription))
}
switch c.flagLoginName {
case "":
case "null":
opts = append(opts, accounts.DefaultPasswordAccountLoginName())
default:
opts = append(opts, accounts.WithPasswordAccountLoginName(c.flagLoginName))
}
if strutil.StrListContains(passwordFlagsMap[c.Func], "password") {
switch c.flagPassword {
case "":
fmt.Print("Password is not set as flag, please enter it now (will be hidden): ")
value, err := password.Read(os.Stdin)
fmt.Print("\n")
if err != nil {
c.UI.Error(fmt.Sprintf("An error occurred attempting to read the password. The raw error message is shown below but usually this is because you attempted to pipe a value into the command or you are executing outside of a terminal (TTY). The raw error was:\n\n%s", err.Error()))
return 2
}
opts = append(opts, accounts.WithPasswordAccountPassword(strings.TrimSpace(value)))
default:
opts = append(opts, accounts.WithPasswordAccountPassword(c.flagPassword))
}
}
accountClient := accounts.NewClient(client)
// Perform check-and-set when needed
var version uint32
switch c.Func {
case "create":
// These don't update so don't need the existing version
default:
switch c.FlagVersion {
case 0:
opts = append(opts, accounts.WithAutomaticVersioning(true))
default:
version = uint32(c.FlagVersion)
}
}
var account *accounts.Account
var apiErr *api.Error
switch c.Func {
case "create":
account, apiErr, err = accountClient.Create(c.Context, c.flagAuthMethodId, opts...)
case "update":
account, apiErr, err = accountClient.Update(c.Context, c.FlagId, version, opts...)
}
plural := "password-type account"
if err != nil {
c.UI.Error(fmt.Sprintf("Error trying to %s %s: %s", c.Func, plural, err.Error()))
return 2
}
if apiErr != nil {
c.UI.Error(fmt.Sprintf("Error from controller when performing %s on %s: %s", c.Func, plural, pretty.Sprint(apiErr)))
return 1
}
switch base.Format(c.UI) {
case "table":
c.UI.Output(generateAccountTableOutput(account))
case "json":
b, err := base.JsonFormatter{}.Format(account)
if err != nil {
c.UI.Error(fmt.Errorf("Error formatting as JSON: %w", err).Error())
return 1
}
c.UI.Output(string(b))
}
return 0
}
@@ -56,14 +56,14 @@ func (c *PasswordCommand) Flags() *base.FlagSets {
Name: "login-name",
Target: &c.flagLoginName,
EnvVar: envLoginName,
Usage: "Login name",
Usage: "The login name corresponding to an account within the given auth method",
})
f.StringVar(&base.StringVar{
Name: "password",
Target: &c.flagPassword,
EnvVar: envPassword,
Usage: "Password",
Usage: "The password associated with the login name",
})
f.StringVar(&base.StringVar{
@@ -121,7 +121,11 @@ func (c *PasswordCommand) Run(args []string) int {
// note: Authenticate() calls SetToken() under the hood to set the
// auth bearer on the client so we do not need to do anything with the
// returned token after this call, so we ignore it
result, apiErr, err := authmethods.NewClient(client).Authenticate(c.Context, c.flagAuthMethodId, c.flagLoginName, c.flagPassword)
result, apiErr, err := authmethods.NewClient(client).Authenticate(c.Context, c.flagAuthMethodId,
map[string]interface{}{
"login_name": c.flagLoginName,
"password": c.flagPassword,
})
if err != nil {
c.UI.Error(fmt.Sprintf("Error trying to perform authentication: %s", err.Error()))
return 2
@@ -37,10 +37,12 @@ func (c *Command) Synopsis() string {
var flagsMap = map[string][]string{
"read": {"id"},
"delete": {"id"},
"list": {"scope-id"},
}
func (c *Command) Help() string {
helpMap := common.HelpMap("auth-method")
var helpStr string
switch c.Func {
case "":
return base.WrapForHelpText([]string{
@@ -55,7 +57,7 @@ func (c *Command) Help() string {
" Please see the auth-methods subcommand help for detailed usage information.",
})
case "create":
return base.WrapForHelpText([]string{
helpStr = base.WrapForHelpText([]string{
"Usage: boundary auth-methods create [type] [sub command] [options] [args]",
"",
" This command allows create operations on Boundary auth-method resources. Example:",
@@ -67,7 +69,7 @@ func (c *Command) Help() string {
" Please see the typed subcommand help for detailed usage information.",
})
case "update":
return base.WrapForHelpText([]string{
helpStr = base.WrapForHelpText([]string{
"Usage: boundary auth-methods update [type] [sub command] [options] [args]",
"",
" This command allows update operations on Boundary auth-method resources. Example:",
@@ -79,8 +81,9 @@ func (c *Command) Help() string {
" Please see the typed subcommand help for detailed usage information.",
})
default:
return helpMap[c.Func]() + c.Flags().Help()
helpStr = helpMap[c.Func]()
}
return helpStr + c.Flags().Help()
}
func (c *Command) Flags() *base.FlagSets {
@@ -119,6 +122,10 @@ func (c *Command) Run(args []string) int {
c.UI.Error("ID is required but not passed in via -id")
return 1
}
if strutil.StrListContains(flagsMap[c.Func], "scope-id") && c.FlagScopeId == "" {
c.UI.Error("Scope ID must be passed in via -scope-id")
return 1
}
client, err := c.Client()
if err != nil {
@@ -157,7 +164,7 @@ func (c *Command) Run(args []string) int {
case "delete":
existed, apiErr, err = authmethodClient.Delete(c.Context, c.FlagId, opts...)
case "list":
listedMethods, apiErr, err = authmethodClient.List(c.Context, opts...)
listedMethods, apiErr, err = authmethodClient.List(c.Context, c.FlagScopeId, opts...)
}
plural := "auth method"
@@ -26,6 +26,7 @@ func generateAuthMethodTableOutput(in *authmethods.AuthMethod) string {
nonAttributeMap := map[string]interface{}{
"ID": in.Id,
"Scope ID": in.Scope.Id,
"Version": in.Version,
"Type": in.Type,
"Created Time": in.CreatedTime.Local().Format(time.RFC3339),
@@ -32,7 +32,7 @@ func (c *PasswordCommand) Synopsis() string {
}
var passwordFlagsMap = map[string][]string{
"create": {"name", "description"},
"create": {"scope-id", "name", "description"},
"update": {"id", "name", "description", "version"},
}
@@ -102,6 +102,10 @@ func (c *PasswordCommand) Run(args []string) int {
c.UI.Error("ID is required but not passed in via -id")
return 1
}
if strutil.StrListContains(passwordFlagsMap[c.Func], "scope-id") && c.FlagScopeId == "" {
c.UI.Error("Scope ID must be passed in via -scope-id")
return 1
}
client, err := c.Client()
if err != nil {
@@ -174,7 +178,7 @@ func (c *PasswordCommand) Run(args []string) int {
default:
switch c.FlagVersion {
case 0:
opts = append(opts, authmethods.WithAutomaticVersioning())
opts = append(opts, authmethods.WithAutomaticVersioning(true))
default:
version = uint32(c.FlagVersion)
}
@@ -185,7 +189,7 @@ func (c *PasswordCommand) Run(args []string) int {
switch c.Func {
case "create":
method, apiErr, err = authmethodClient.Create(c.Context, "password", opts...)
method, apiErr, err = authmethodClient.Create(c.Context, "password", c.FlagScopeId, opts...)
case "update":
method, apiErr, err = authmethodClient.Update(c.Context, c.FlagId, version, opts...)
}
@@ -31,6 +31,7 @@ func (c *Command) Synopsis() string {
var flagsMap = map[string][]string{
"read": {"id"},
"delete": {"id"},
"list": {"scope-id"},
}
func (c *Command) Help() string {
@@ -76,6 +77,10 @@ func (c *Command) Run(args []string) int {
c.UI.Error("ID is required but not passed in via -id")
return 1
}
if strutil.StrListContains(flagsMap[c.Func], "scope-id") && c.FlagScopeId == "" {
c.UI.Error("Scope ID must be passed in via -scope-id")
return 1
}
client, err := c.Client()
if err != nil {
@@ -96,7 +101,7 @@ func (c *Command) Run(args []string) int {
case "delete":
existed, apiErr, err = authtokenClient.Delete(c.Context, c.FlagId)
case "list":
listedTokens, apiErr, err = authtokenClient.List(c.Context)
listedTokens, apiErr, err = authtokenClient.List(c.Context, c.FlagScopeId)
}
plural := "auth token"
+1
View File
@@ -75,6 +75,7 @@ func generateGroupTableOutput(in *groups.Group) string {
nonAttributeMap := map[string]interface{}{
"ID": in.Id,
"Scope ID": in.Scope.Id,
"Version": in.Version,
"Created Time": in.CreatedTime.Local().Format(time.RFC3339),
"Updated Time": in.UpdatedTime.Local().Format(time.RFC3339),
+9 -4
View File
@@ -43,10 +43,11 @@ var helpMap = func() map[string]func() string {
}
var flagsMap = map[string][]string{
"create": {"name", "description"},
"create": {"scope-id", "name", "description"},
"update": {"id", "name", "description", "version"},
"read": {"id"},
"delete": {"id"},
"list": {"scope-id"},
"add-members": {"id", "member", "version"},
"set-members": {"id", "member", "version"},
"remove-members": {"id", "member", "version"},
@@ -95,6 +96,10 @@ func (c *Command) Run(args []string) int {
c.UI.Error("ID is required but not passed in via -id")
return 1
}
if strutil.StrListContains(flagsMap[c.Func], "scope-id") && c.FlagScopeId == "" {
c.UI.Error("Scope ID must be passed in via -scope-id")
return 1
}
client, err := c.Client()
if err != nil {
@@ -151,7 +156,7 @@ func (c *Command) Run(args []string) int {
default:
switch c.FlagVersion {
case 0:
opts = append(opts, groups.WithAutomaticVersioning())
opts = append(opts, groups.WithAutomaticVersioning(true))
default:
version = uint32(c.FlagVersion)
}
@@ -164,7 +169,7 @@ func (c *Command) Run(args []string) int {
switch c.Func {
case "create":
group, apiErr, err = groupClient.Create(c.Context, opts...)
group, apiErr, err = groupClient.Create(c.Context, c.FlagScopeId, opts...)
case "update":
group, apiErr, err = groupClient.Update(c.Context, c.FlagId, version, opts...)
case "read":
@@ -172,7 +177,7 @@ func (c *Command) Run(args []string) int {
case "delete":
existed, apiErr, err = groupClient.Delete(c.Context, c.FlagId, opts...)
case "list":
listedGroups, apiErr, err = groupClient.List(c.Context, opts...)
listedGroups, apiErr, err = groupClient.List(c.Context, c.FlagScopeId, opts...)
case "add-members":
group, apiErr, err = groupClient.AddMembers(c.Context, c.FlagId, version, members, opts...)
case "set-members":
+5 -6
View File
@@ -13,6 +13,7 @@ func generateHostCatalogTableOutput(in *hostcatalogs.HostCatalog) string {
nonAttributeMap := map[string]interface{}{
"ID": in.Id,
"Scope ID": in.Scope.Id,
"Version": in.Version,
"Type": in.Type,
"Created Time": in.CreatedTime.Local().Format(time.RFC3339),
@@ -54,12 +55,8 @@ func generateHostCatalogTableOutput(in *hostcatalogs.HostCatalog) string {
)
if len(in.Attributes) > 0 {
if true {
ret = append(ret,
fmt.Sprintf(" Attributes: %s", ""),
)
}
ret = append(ret,
fmt.Sprintf(" Attributes: %s", ""),
base.WrapMap(4, maxLength, in.Attributes),
)
}
@@ -67,4 +64,6 @@ func generateHostCatalogTableOutput(in *hostcatalogs.HostCatalog) string {
return base.WrapForHelpText(ret)
}
var attributeMap = map[string]string{}
var attributeMap = map[string]string{
"address": "Address",
}
@@ -26,7 +26,7 @@ type Command struct {
func (c *Command) Synopsis() string {
switch c.Func {
case "create":
return "Create host-catalolg resources within Boundary"
return "Create host-catalog resources within Boundary"
case "update":
return "Update host-catalog resources within Boundary"
default:
@@ -37,10 +37,12 @@ func (c *Command) Synopsis() string {
var flagsMap = map[string][]string{
"read": {"id"},
"delete": {"id"},
"list": {"scope-id"},
}
func (c *Command) Help() string {
helpMap := common.HelpMap("host-catalog")
var helpStr string
switch c.Func {
case "":
return base.WrapForHelpText([]string{
@@ -55,7 +57,7 @@ func (c *Command) Help() string {
" Please see the host-catalogs subcommand help for detailed usage information.",
})
case "create":
return base.WrapForHelpText([]string{
helpStr = base.WrapForHelpText([]string{
"Usage: boundary host-catalogs create [type] [sub command] [options] [args]",
"",
" This command allows create operations on Boundary host-catalog resources. Example:",
@@ -67,7 +69,7 @@ func (c *Command) Help() string {
" Please see the typed subcommand help for detailed usage information.",
})
case "update":
return base.WrapForHelpText([]string{
helpStr = base.WrapForHelpText([]string{
"Usage: boundary host-catalogs update [type] [sub command] [options] [args]",
"",
" This command allows update operations on Boundary host-catalog resources. Example:",
@@ -79,8 +81,9 @@ func (c *Command) Help() string {
" Please see the typed subcommand help for detailed usage information.",
})
default:
return helpMap[c.Func]() + c.Flags().Help()
helpStr = helpMap[c.Func]()
}
return helpStr + c.Flags().Help()
}
func (c *Command) Flags() *base.FlagSets {
@@ -119,6 +122,10 @@ func (c *Command) Run(args []string) int {
c.UI.Error("ID is required but not passed in via -id")
return 1
}
if strutil.StrListContains(flagsMap[c.Func], "scope-id") && c.FlagScopeId == "" {
c.UI.Error("Scope ID must be passed in via -scope-id")
return 1
}
client, err := c.Client()
if err != nil {
@@ -157,7 +164,7 @@ func (c *Command) Run(args []string) int {
case "delete":
existed, apiErr, err = hostcatalogClient.Delete(c.Context, c.FlagId, opts...)
case "list":
listedCatalogs, apiErr, err = hostcatalogClient.List(c.Context, opts...)
listedCatalogs, apiErr, err = hostcatalogClient.List(c.Context, c.FlagScopeId, opts...)
}
plural := "host catalog"
+7 -3
View File
@@ -28,7 +28,7 @@ func (c *StaticCommand) Synopsis() string {
}
var staticFlagsMap = map[string][]string{
"create": {"name", "description"},
"create": {"scope-id", "name", "description"},
"update": {"id", "name", "description", "version"},
}
@@ -95,6 +95,10 @@ func (c *StaticCommand) Run(args []string) int {
c.UI.Error("ID is required but not passed in via -id")
return 1
}
if strutil.StrListContains(staticFlagsMap[c.Func], "scope-id") && c.FlagScopeId == "" {
c.UI.Error("Scope ID must be passed in via -scope-id")
return 1
}
client, err := c.Client()
if err != nil {
@@ -130,7 +134,7 @@ func (c *StaticCommand) Run(args []string) int {
default:
switch c.FlagVersion {
case 0:
opts = append(opts, hostcatalogs.WithAutomaticVersioning())
opts = append(opts, hostcatalogs.WithAutomaticVersioning(true))
default:
version = uint32(c.FlagVersion)
}
@@ -141,7 +145,7 @@ func (c *StaticCommand) Run(args []string) int {
switch c.Func {
case "create":
catalog, apiErr, err = hostcatalogClient.Create(c.Context, "static", opts...)
catalog, apiErr, err = hostcatalogClient.Create(c.Context, "static", c.FlagScopeId, opts...)
case "update":
catalog, apiErr, err = hostcatalogClient.Update(c.Context, c.FlagId, version, opts...)
}
+75
View File
@@ -0,0 +1,75 @@
package hosts
import (
"fmt"
"time"
"github.com/hashicorp/boundary/api/hosts"
"github.com/hashicorp/boundary/internal/cmd/base"
)
func generateHostTableOutput(in *hosts.Host) string {
var ret []string
nonAttributeMap := map[string]interface{}{
"ID": in.Id,
"Scope ID": in.Scope.Id,
"Version": in.Version,
"Type": in.Type,
"Created Time": in.CreatedTime.Local().Format(time.RFC3339),
"Updated Time": in.UpdatedTime.Local().Format(time.RFC3339),
"Host Catalog ID": in.HostCatalogId,
}
if in.Name != "" {
nonAttributeMap["Name"] = in.Name
}
if in.Description != "" {
nonAttributeMap["Description"] = in.Description
}
maxLength := 0
for k := range nonAttributeMap {
if len(k) > maxLength {
maxLength = len(k)
}
}
if len(in.Attributes) > 0 {
for k, v := range in.Attributes {
if attributeMap[k] != "" {
in.Attributes[attributeMap[k]] = v
delete(in.Attributes, k)
}
}
for k := range in.Attributes {
if len(k) > maxLength {
maxLength = len(k)
}
}
}
ret = append(ret, "", "Host information:")
ret = append(ret,
// We do +2 because there is another +2 offset for attributes below
base.WrapMap(2, maxLength+2, nonAttributeMap),
)
if len(in.HostSetIds) > 0 {
ret = append(ret,
" Host Set IDs:",
base.WrapSlice(4, in.HostSetIds),
)
}
if len(in.Attributes) > 0 {
ret = append(ret,
fmt.Sprintf(" Attributes: %s", ""),
base.WrapMap(4, maxLength, in.Attributes),
)
}
return base.WrapForHelpText(ret)
}
var attributeMap = map[string]string{}
+278
View File
@@ -0,0 +1,278 @@
package hosts
import (
"fmt"
"github.com/hashicorp/boundary/api"
"github.com/hashicorp/boundary/api/hosts"
"github.com/hashicorp/boundary/internal/cmd/base"
"github.com/hashicorp/boundary/internal/cmd/common"
"github.com/hashicorp/boundary/internal/types/resource"
"github.com/hashicorp/vault/sdk/helper/strutil"
"github.com/kr/pretty"
"github.com/mitchellh/cli"
"github.com/posener/complete"
)
var _ cli.Command = (*Command)(nil)
var _ cli.CommandAutocomplete = (*Command)(nil)
type Command struct {
*base.Command
Func string
flagHostCatalogId string
}
func (c *Command) Synopsis() string {
switch c.Func {
case "create":
return "Create host resources within Boundary"
case "update":
return "Update host resources within Boundary"
default:
return common.SynopsisFunc(c.Func, "host")
}
}
var flagsMap = map[string][]string{
"read": {"id"},
"delete": {"id"},
"list": {"host-catalog-id"},
}
func (c *Command) Help() string {
helpMap := common.HelpMap("host")
var helpStr string
switch c.Func {
case "":
return base.WrapForHelpText([]string{
"Usage: boundary hosts [sub command] [options] [args]",
"",
" This command allows operations on Boundary host resources. Example:",
"",
" Read a host:",
"",
` $ boundary hosts read -id hst_1234567890`,
"",
" Please see the hosts subcommand help for detailed usage information.",
})
case "create":
helpStr = base.WrapForHelpText([]string{
"Usage: boundary hosts create [type] [sub command] [options] [args]",
"",
" This command allows create operations on Boundary host resources. Example:",
"",
" Create a static-type host:",
"",
` $ boundary hosts create static -name prodops -description "For ProdOps usage"`,
"",
" Please see the typed subcommand help for detailed usage information.",
})
case "update":
helpStr = base.WrapForHelpText([]string{
"Usage: boundary hosts update [type] [sub command] [options] [args]",
"",
" This command allows update operations on Boundary host resources. Example:",
"",
" Update a static-type host:",
"",
` $ boundary hosts update static -id hst_1234567890 -name devops -description "For DevOps usage"`,
"",
" Please see the typed subcommand help for detailed usage information.",
})
default:
helpStr = helpMap[c.Func]()
}
return helpStr + c.Flags().Help()
}
func (c *Command) Flags() *base.FlagSets {
set := c.FlagSet(base.FlagSetHTTP | base.FlagSetClient | base.FlagSetOutputFormat)
f := set.NewFlagSet("Command Options")
if len(flagsMap[c.Func]) > 0 {
common.PopulateCommonFlags(c.Command, f, resource.Host.String(), flagsMap[c.Func])
}
for _, name := range flagsMap[c.Func] {
switch name {
case "host-catalog-id":
f.StringVar(&base.StringVar{
Name: "host-catalog-id",
Target: &c.flagHostCatalogId,
Usage: "The host-catalog resource in which to create or update the host resource",
})
}
}
return set
}
func (c *Command) AutocompleteArgs() complete.Predictor {
return complete.PredictAnything
}
func (c *Command) AutocompleteFlags() complete.Flags {
return c.Flags().Completions()
}
func (c *Command) Run(args []string) int {
switch c.Func {
case "", "create", "update":
return cli.RunResultHelp
}
f := c.Flags()
if err := f.Parse(args); err != nil {
c.UI.Error(err.Error())
return 1
}
if strutil.StrListContains(flagsMap[c.Func], "id") && c.FlagId == "" {
c.UI.Error("ID is required but not passed in via -id")
return 1
}
if strutil.StrListContains(flagsMap[c.Func], "host-catalog-id") && c.flagHostCatalogId == "" {
c.UI.Error("Host Catalog ID must be passed in via -host-catalog-id")
return 1
}
client, err := c.Client()
if err != nil {
c.UI.Error(fmt.Sprintf("Error creating API client: %s", err.Error()))
return 2
}
var opts []hosts.Option
switch c.FlagName {
case "":
case "null":
opts = append(opts, hosts.DefaultName())
default:
opts = append(opts, hosts.WithName(c.FlagName))
}
switch c.FlagDescription {
case "":
case "null":
opts = append(opts, hosts.DefaultDescription())
default:
opts = append(opts, hosts.WithDescription(c.FlagDescription))
}
hostClient := hosts.NewClient(client)
var existed bool
var host *hosts.Host
var listedHosts []*hosts.Host
var apiErr *api.Error
switch c.Func {
case "read":
host, apiErr, err = hostClient.Read(c.Context, c.FlagId, opts...)
case "delete":
existed, apiErr, err = hostClient.Delete(c.Context, c.FlagId, opts...)
case "list":
listedHosts, apiErr, err = hostClient.List(c.Context, c.flagHostCatalogId, opts...)
}
plural := "host"
if c.Func == "list" {
plural = "hosts"
}
if err != nil {
c.UI.Error(fmt.Sprintf("Error trying to %s %s: %s", c.Func, plural, err.Error()))
return 2
}
if apiErr != nil {
c.UI.Error(fmt.Sprintf("Error from controller when performing %s on %s: %s", c.Func, plural, pretty.Sprint(apiErr)))
return 1
}
switch c.Func {
case "delete":
switch base.Format(c.UI) {
case "json":
c.UI.Output("null")
case "table":
output := "The delete operation completed successfully"
switch existed {
case true:
output += "."
default:
output += ", however the resource did not exist at the time."
}
c.UI.Output(output)
}
return 0
case "list":
switch base.Format(c.UI) {
case "json":
if len(listedHosts) == 0 {
c.UI.Output("null")
return 0
}
b, err := base.JsonFormatter{}.Format(listedHosts)
if err != nil {
c.UI.Error(fmt.Errorf("Error formatting as JSON: %w", err).Error())
return 1
}
c.UI.Output(string(b))
case "table":
if len(listedHosts) == 0 {
c.UI.Output("No hosts found")
return 0
}
var output []string
output = []string{
"",
"Host information:",
}
for i, m := range listedHosts {
if i > 0 {
output = append(output, "")
}
if true {
output = append(output,
fmt.Sprintf(" ID: %s", m.Id),
fmt.Sprintf(" Version: %d", m.Version),
fmt.Sprintf(" Type: %s", m.Type),
)
}
if m.Name != "" {
output = append(output,
fmt.Sprintf(" Name: %s", m.Name),
)
}
if m.Description != "" {
output = append(output,
fmt.Sprintf(" Description: %s", m.Description),
)
}
}
c.UI.Output(base.WrapForHelpText(output))
}
return 0
}
switch base.Format(c.UI) {
case "table":
c.UI.Output(generateHostTableOutput(host))
case "json":
b, err := base.JsonFormatter{}.Format(host)
if err != nil {
c.UI.Error(fmt.Errorf("Error formatting as JSON: %w", err).Error())
return 1
}
c.UI.Output(string(b))
}
return 0
}
-131
View File
@@ -1,131 +0,0 @@
package hosts
import (
"fmt"
"strings"
"github.com/hashicorp/boundary/api/hosts"
"github.com/hashicorp/boundary/internal/cmd/base"
"github.com/kr/pretty"
"github.com/mitchellh/cli"
"github.com/posener/complete"
)
var _ cli.Command = (*CreateCommand)(nil)
var _ cli.CommandAutocomplete = (*CreateCommand)(nil)
type CreateCommand struct {
*base.Command
flagAddress string
flagName string
flagCatalogId string
flagDescription string
}
func (c *CreateCommand) Synopsis() string {
return "Creates a host in the given host catalog"
}
func (c *CreateCommand) Help() string {
helpText := `
Usage: boundary hosts create
Creates a host in the given host catalog. This command will result in an
error for any catalog that does not support manual host creation.
Example:
$ boundary hosts create -catalog-id=<id> -address=<addr> -name=<name>
` + c.Flags().Help()
return strings.TrimSpace(helpText)
}
func (c *CreateCommand) Flags() *base.FlagSets {
set := c.FlagSet(base.FlagSetHTTP | base.FlagSetClient | base.FlagSetOutputFormat)
f := set.NewFlagSet("Command Options")
f.StringVar(&base.StringVar{
Name: "address",
Target: &c.flagAddress,
Completion: complete.PredictAnything,
Usage: "The host's address; can be an IP address or DNS name",
})
f.StringVar(&base.StringVar{
Name: "name",
Target: &c.flagName,
Completion: complete.PredictAnything,
Usage: "An optional name assigned to the host for display purposes",
})
f.StringVar(&base.StringVar{
Name: "catalog-id",
Target: &c.flagCatalogId,
Completion: complete.PredictAnything,
Usage: "The ID of the host catalog in which the host should be created",
})
f.StringVar(&base.StringVar{
Name: "description",
Target: &c.flagDescription,
Completion: complete.PredictNothing,
Usage: "An optional description assigned to the host for display purposes",
})
return set
}
func (c *CreateCommand) AutocompleteArgs() complete.Predictor {
return complete.PredictAnything
}
func (c *CreateCommand) AutocompleteFlags() complete.Flags {
return c.Flags().Completions()
}
func (c *CreateCommand) Run(args []string) int {
f := c.Flags()
if err := f.Parse(args); err != nil {
c.UI.Error(err.Error())
return 1
}
switch {
case c.flagCatalogId == "":
c.UI.Error("Catalog ID must be provided via -catalog-id")
return 1
case c.flagAddress == "":
c.UI.Error("Host address must be provided via -address")
return 1
}
client, err := c.Client()
if err != nil {
c.UI.Error(err.Error())
return 2
}
host, apiErr, err := hosts.NewClient(client).Create(c.Context,
c.flagCatalogId,
hosts.WithStaticHostAddress(c.flagAddress),
hosts.WithName(c.flagName),
hosts.WithDescription(c.flagDescription))
switch {
case err != nil:
c.UI.Error(fmt.Errorf("error creating host: %w", err).Error())
return 2
case apiErr != nil:
c.UI.Error(pretty.Sprint(apiErr))
return 2
default:
c.UI.Info(pretty.Sprint(host))
}
return 0
}
+216
View File
@@ -0,0 +1,216 @@
package hosts
import (
"fmt"
"net/textproto"
"github.com/hashicorp/boundary/api"
"github.com/hashicorp/boundary/api/hosts"
"github.com/hashicorp/boundary/internal/cmd/base"
"github.com/hashicorp/boundary/internal/cmd/common"
"github.com/hashicorp/vault/sdk/helper/strutil"
"github.com/kr/pretty"
"github.com/mitchellh/cli"
"github.com/posener/complete"
)
var _ cli.Command = (*StaticCommand)(nil)
var _ cli.CommandAutocomplete = (*StaticCommand)(nil)
type StaticCommand struct {
*base.Command
Func string
flagHostCatalogId string
flagAddress string
}
func (c *StaticCommand) Synopsis() string {
return fmt.Sprintf("%s a static-type host within Boundary", textproto.CanonicalMIMEHeaderKey(c.Func))
}
var staticFlagsMap = map[string][]string{
"create": {"host-catalog-id", "name", "description", "address"},
"update": {"id", "name", "description", "version", "address"},
}
func (c *StaticCommand) Help() string {
var info string
switch c.Func {
case "create":
info = base.WrapForHelpText([]string{
"Usage: boundary hosts static create [options] [args]",
"",
" Create a static-type host. Example:",
"",
` $ boundary hosts static create -name prodops -description "Static host for ProdOps" -address "127.0.0.1"`,
"",
"",
})
case "update":
info = base.WrapForHelpText([]string{
"Usage: boundary hosts static update [options] [args]",
"",
" Update a static-type host given its ID. Example:",
"",
` $ boundary hosts static update -id hst_1234567890 -name "devops" -description "Static host for DevOps" -address "10.20.30.40"`,
"",
"",
})
}
return info + c.Flags().Help()
}
func (c *StaticCommand) Flags() *base.FlagSets {
set := c.FlagSet(base.FlagSetHTTP | base.FlagSetClient | base.FlagSetOutputFormat)
f := set.NewFlagSet("Command Options")
if len(staticFlagsMap[c.Func]) > 0 {
common.PopulateCommonFlags(c.Command, f, "static-type host", staticFlagsMap[c.Func])
}
for _, name := range staticFlagsMap[c.Func] {
switch name {
case "host-catalog-id":
f.StringVar(&base.StringVar{
Name: "host-catalog-id",
Target: &c.flagHostCatalogId,
Usage: "The host-catalog resource in which to create or update the host resource",
})
}
}
f = set.NewFlagSet("Static Host Options")
for _, name := range staticFlagsMap[c.Func] {
switch name {
case "address":
f.StringVar(&base.StringVar{
Name: "address",
Target: &c.flagAddress,
Usage: "The address of the host",
})
}
}
return set
}
func (c *StaticCommand) AutocompleteArgs() complete.Predictor {
return complete.PredictAnything
}
func (c *StaticCommand) AutocompleteFlags() complete.Flags {
return c.Flags().Completions()
}
func (c *StaticCommand) Run(args []string) int {
if c.Func == "" {
return cli.RunResultHelp
}
f := c.Flags()
if err := f.Parse(args); err != nil {
c.UI.Error(err.Error())
return 1
}
if strutil.StrListContains(staticFlagsMap[c.Func], "id") && c.FlagId == "" {
c.UI.Error("ID is required but not passed in via -id")
return 1
}
if strutil.StrListContains(staticFlagsMap[c.Func], "host-catalog-id") && c.flagHostCatalogId == "" {
c.UI.Error("Host Catalog ID must be passed in via -host-catalog-id")
return 1
}
if c.Func == "create" && c.flagAddress == "" {
c.UI.Error("Address must be passed in via -address")
return 1
}
client, err := c.Client()
if err != nil {
c.UI.Error(fmt.Sprintf("Error creating API client: %s", err.Error()))
return 2
}
var opts []hosts.Option
switch c.FlagName {
case "":
case "null":
opts = append(opts, hosts.DefaultName())
default:
opts = append(opts, hosts.WithName(c.FlagName))
}
switch c.FlagDescription {
case "":
case "null":
opts = append(opts, hosts.DefaultDescription())
default:
opts = append(opts, hosts.WithDescription(c.FlagDescription))
}
switch c.flagAddress {
case "":
case "null":
opts = append(opts, hosts.DefaultStaticHostAddress())
default:
opts = append(opts, hosts.WithStaticHostAddress(c.flagAddress))
}
hostClient := hosts.NewClient(client)
// Perform check-and-set when needed
var version uint32
switch c.Func {
case "create":
// These don't update so don't need the existing version
default:
switch c.FlagVersion {
case 0:
opts = append(opts, hosts.WithAutomaticVersioning(true))
default:
version = uint32(c.FlagVersion)
}
}
var host *hosts.Host
var apiErr *api.Error
switch c.Func {
case "create":
host, apiErr, err = hostClient.Create(c.Context, c.flagHostCatalogId, opts...)
case "update":
host, apiErr, err = hostClient.Update(c.Context, c.FlagId, version, opts...)
}
plural := "static-type host"
if err != nil {
c.UI.Error(fmt.Sprintf("Error trying to %s %s: %s", c.Func, plural, err.Error()))
return 2
}
if apiErr != nil {
c.UI.Error(fmt.Sprintf("Error from controller when performing %s on %s: %s", c.Func, plural, pretty.Sprint(apiErr)))
return 1
}
switch base.Format(c.UI) {
case "table":
c.UI.Output(generateHostTableOutput(host))
case "json":
b, err := base.JsonFormatter{}.Format(host)
if err != nil {
c.UI.Error(fmt.Errorf("Error formatting as JSON: %w", err).Error())
return 1
}
c.UI.Output(string(b))
}
return 0
}
+3 -10
View File
@@ -13,6 +13,7 @@ func generateHostSetTableOutput(in *hostsets.HostSet) string {
nonAttributeMap := map[string]interface{}{
"ID": in.Id,
"Scope ID": in.Scope.Id,
"Version": in.Version,
"Type": in.Type,
"Created Time": in.CreatedTime.Local().Format(time.RFC3339),
@@ -55,23 +56,15 @@ func generateHostSetTableOutput(in *hostsets.HostSet) string {
)
if len(in.HostIds) > 0 {
if true {
ret = append(ret,
fmt.Sprintf(" Host IDs:"),
)
}
ret = append(ret,
" Host IDs:",
base.WrapSlice(4, in.HostIds),
)
}
if len(in.Attributes) > 0 {
if true {
ret = append(ret,
fmt.Sprintf(" Attributes: %s", ""),
)
}
ret = append(ret,
fmt.Sprintf(" Attributes: %s", ""),
base.WrapMap(4, maxLength, in.Attributes),
)
}
+25 -19
View File
@@ -46,6 +46,7 @@ func (c *Command) Synopsis() string {
var flagsMap = map[string][]string{
"read": {"id"},
"delete": {"id"},
"list": {"host-catalog-id"},
"add-hosts": {"id", "host", "version"},
"set-hosts": {"id", "host", "version"},
"remove-hosts": {"id", "host", "version"},
@@ -53,6 +54,7 @@ var flagsMap = map[string][]string{
func (c *Command) Help() string {
helpMap := common.HelpMap("host-set")
var helpStr string
switch c.Func {
case "":
return base.WrapForHelpText([]string{
@@ -67,7 +69,7 @@ func (c *Command) Help() string {
" Please see the host-sets subcommand help for detailed usage information.",
})
case "create":
return base.WrapForHelpText([]string{
helpStr = base.WrapForHelpText([]string{
"Usage: boundary host-sets create [type] [sub command] [options] [args]",
"",
" This command allows create operations on Boundary host-set resources. Example:",
@@ -79,7 +81,7 @@ func (c *Command) Help() string {
" Please see the typed subcommand help for detailed usage information.",
})
case "update":
return base.WrapForHelpText([]string{
helpStr = base.WrapForHelpText([]string{
"Usage: boundary host-sets update [type] [sub command] [options] [args]",
"",
" This command allows update operations on Boundary host-set resources. Example:",
@@ -91,7 +93,7 @@ func (c *Command) Help() string {
" Please see the typed subcommand help for detailed usage information.",
})
case "add-hosts":
return base.WrapForHelpText([]string{
helpStr = base.WrapForHelpText([]string{
"Usage: boundary host-sets add-hosts [sub command] [options] [args]",
"",
" This command allows adding hosts to host-set resources, if the types match and the operation is allowed by the given host-set type. Example:",
@@ -101,7 +103,7 @@ func (c *Command) Help() string {
` $ boundary host-sets add-hosts -id hsst_1234567890 -host hst_1234567890 -host hst_0987654321`,
})
case "remove-hosts":
return base.WrapForHelpText([]string{
helpStr = base.WrapForHelpText([]string{
"Usage: boundary host-sets remove-hosts [sub command] [options] [args]",
"",
" This command allows removing hosts from host-set resources, if the types match and the operation is allowed by the given host-set type. Example:",
@@ -111,7 +113,7 @@ func (c *Command) Help() string {
` $ boundary host-sets remove-hosts -id hsst_1234567890 -host hst_0987654321`,
})
case "set-hosts":
return base.WrapForHelpText([]string{
helpStr = base.WrapForHelpText([]string{
"Usage: boundary host-sets set-hosts [sub command] [options] [args]",
"",
" This command allows setting the complete set of hosts on host-set resources, if the types match and the operation is allowed by the given host-set type. Example:",
@@ -121,8 +123,9 @@ func (c *Command) Help() string {
` $ boundary host-sets remove-hosts -id hsst_1234567890 -host hst_1234567890`,
})
default:
return helpMap[c.Func]() + c.Flags().Help()
helpStr = helpMap[c.Func]()
}
return helpStr + c.Flags().Help()
}
func (c *Command) Flags() *base.FlagSets {
@@ -134,14 +137,14 @@ func (c *Command) Flags() *base.FlagSets {
common.PopulateCommonFlags(c.Command, f, resource.HostSet.String(), flagsMap[c.Func])
}
f.StringVar(&base.StringVar{
Name: "host-catalog-id",
Target: &c.flagHostCatalogId,
Usage: "The host-catalog resource in which to create or update the host-set resource",
})
for _, name := range flagsMap[c.Func] {
switch name {
case "host-catalog-id":
f.StringVar(&base.StringVar{
Name: "host-catalog-id",
Target: &c.flagHostCatalogId,
Usage: "The host-catalog resource in which to create or update the host-set resource",
})
case "host":
f.StringSliceVar(&base.StringSliceVar{
Name: "host",
@@ -174,11 +177,14 @@ func (c *Command) Run(args []string) int {
c.UI.Error(err.Error())
return 1
}
if strutil.StrListContains(flagsMap[c.Func], "id") && c.FlagId == "" {
c.UI.Error("ID is required but not passed in via -id")
return 1
}
if strutil.StrListContains(flagsMap[c.Func], "host-catalog-id") && c.flagHostCatalogId == "" {
c.UI.Error("Host Catalog ID must be passed in via -host-catalog-id")
return 1
}
client, err := c.Client()
if err != nil {
@@ -232,7 +238,7 @@ func (c *Command) Run(args []string) int {
case "add-hosts", "remove-hosts", "set-hosts":
switch c.FlagVersion {
case 0:
opts = append(opts, hostsets.WithAutomaticVersioning())
opts = append(opts, hostsets.WithAutomaticVersioning(true))
default:
version = uint32(c.FlagVersion)
}
@@ -250,17 +256,17 @@ func (c *Command) Run(args []string) int {
switch c.Func {
case "read":
set, apiErr, err = hostsetClient.Read(c.Context, c.flagHostCatalogId, c.FlagId, opts...)
set, apiErr, err = hostsetClient.Read(c.Context, c.FlagId, opts...)
case "delete":
existed, apiErr, err = hostsetClient.Delete(c.Context, c.flagHostCatalogId, c.FlagId, opts...)
existed, apiErr, err = hostsetClient.Delete(c.Context, c.FlagId, opts...)
case "list":
listedSets, apiErr, err = hostsetClient.List(c.Context, c.flagHostCatalogId, opts...)
case "add-hosts":
set, apiErr, err = hostsetClient.AddHosts(c.Context, c.flagHostCatalogId, c.FlagId, version, c.flagHosts, opts...)
set, apiErr, err = hostsetClient.AddHosts(c.Context, c.FlagId, version, c.flagHosts, opts...)
case "remove-hosts":
set, apiErr, err = hostsetClient.RemoveHosts(c.Context, c.flagHostCatalogId, c.FlagId, version, c.flagHosts, opts...)
set, apiErr, err = hostsetClient.RemoveHosts(c.Context, c.FlagId, version, c.flagHosts, opts...)
case "set-hosts":
set, apiErr, err = hostsetClient.SetHosts(c.Context, c.flagHostCatalogId, c.FlagId, version, c.flagHosts, opts...)
set, apiErr, err = hostsetClient.SetHosts(c.Context, c.FlagId, version, c.flagHosts, opts...)
}
plural := "host set"
+14 -10
View File
@@ -30,7 +30,7 @@ func (c *StaticCommand) Synopsis() string {
}
var staticFlagsMap = map[string][]string{
"create": {"name", "description"},
"create": {"host-catalog-id", "name", "description"},
"update": {"id", "name", "description", "version"},
}
@@ -71,11 +71,16 @@ func (c *StaticCommand) Flags() *base.FlagSets {
common.PopulateCommonFlags(c.Command, f, "static-type host-set", staticFlagsMap[c.Func])
}
f.StringVar(&base.StringVar{
Name: "host-catalog-id",
Target: &c.flagHostCatalogId,
Usage: "The host-catalog resource in which to create or update the host-set resource",
})
for _, name := range staticFlagsMap[c.Func] {
switch name {
case "host-catalog-id":
f.StringVar(&base.StringVar{
Name: "host-catalog-id",
Target: &c.flagHostCatalogId,
Usage: "The host-catalog resource in which to create or update the host-set resource",
})
}
}
return set
}
@@ -104,8 +109,7 @@ func (c *StaticCommand) Run(args []string) int {
c.UI.Error("ID is required but not passed in via -id")
return 1
}
if c.flagHostCatalogId == "" {
if strutil.StrListContains(staticFlagsMap[c.Func], "host-catalog-id") && c.flagHostCatalogId == "" {
c.UI.Error("Host Catalog ID must be passed in via -host-catalog-id")
return 1
}
@@ -144,7 +148,7 @@ func (c *StaticCommand) Run(args []string) int {
default:
switch c.FlagVersion {
case 0:
opts = append(opts, hostsets.WithAutomaticVersioning())
opts = append(opts, hostsets.WithAutomaticVersioning(true))
default:
version = uint32(c.FlagVersion)
}
@@ -157,7 +161,7 @@ func (c *StaticCommand) Run(args []string) int {
case "create":
set, apiErr, err = hostsetClient.Create(c.Context, c.flagHostCatalogId, opts...)
case "update":
set, apiErr, err = hostsetClient.Update(c.Context, c.flagHostCatalogId, c.FlagId, version, opts...)
set, apiErr, err = hostsetClient.Update(c.Context, c.FlagId, version, opts...)
}
plural := "static-type host-set"
+1
View File
@@ -91,6 +91,7 @@ func generateRoleTableOutput(in *roles.Role) string {
nonAttributeMap := map[string]interface{}{
"ID": in.Id,
"Scope ID": in.Scope.Id,
"Version": in.Version,
"Created Time": in.CreatedTime.Local().Format(time.RFC3339),
"Updated Time": in.UpdatedTime.Local().Format(time.RFC3339),
+10 -4
View File
@@ -22,6 +22,7 @@ type Command struct {
Func string
flagScope string
flagGrantScopeId string
flagPrincipals []string
flagGrants []string
@@ -51,10 +52,11 @@ var helpMap = func() map[string]func() string {
}
var flagsMap = map[string][]string{
"create": {"name", "description", "grantscopeid"},
"create": {"scope-id", "name", "description", "grantscopeid"},
"update": {"id", "name", "description", "grantscopeid", "version"},
"read": {"id"},
"delete": {"id"},
"list": {"scope-id"},
"add-principals": {"id", "principal", "version"},
"set-principals": {"id", "principal", "version"},
"remove-principals": {"id", "principal", "version"},
@@ -105,6 +107,10 @@ func (c *Command) Run(args []string) int {
c.UI.Error("ID is required but not passed in via -id")
return 1
}
if strutil.StrListContains(flagsMap[c.Func], "scope-id") && c.FlagScopeId == "" {
c.UI.Error("Scope ID must be passed in via -scope-id")
return 1
}
client, err := c.Client()
if err != nil {
@@ -198,7 +204,7 @@ func (c *Command) Run(args []string) int {
default:
switch c.FlagVersion {
case 0:
opts = append(opts, roles.WithAutomaticVersioning())
opts = append(opts, roles.WithAutomaticVersioning(true))
default:
version = uint32(c.FlagVersion)
}
@@ -211,7 +217,7 @@ func (c *Command) Run(args []string) int {
switch c.Func {
case "create":
role, apiErr, err = roleClient.Create(c.Context, opts...)
role, apiErr, err = roleClient.Create(c.Context, c.FlagScopeId, opts...)
case "update":
role, apiErr, err = roleClient.Update(c.Context, c.FlagId, version, opts...)
case "read":
@@ -219,7 +225,7 @@ func (c *Command) Run(args []string) int {
case "delete":
existed, apiErr, err = roleClient.Delete(c.Context, c.FlagId, opts...)
case "list":
listedRoles, apiErr, err = roleClient.List(c.Context, opts...)
listedRoles, apiErr, err = roleClient.List(c.Context, c.FlagScopeId, opts...)
case "add-principals":
role, apiErr, err = roleClient.AddPrincipals(c.Context, c.FlagId, version, principals, opts...)
case "set-principals":
+1
View File
@@ -12,6 +12,7 @@ func generateScopeTableOutput(in *scopes.Scope) string {
nonAttributeMap := map[string]interface{}{
"ID": in.Id,
"Scope ID": in.Scope.Id,
"Version": in.Version,
"Created Time": in.CreatedTime.Local().Format(time.RFC3339),
"Updated Time": in.UpdatedTime.Local().Format(time.RFC3339),
+9 -4
View File
@@ -30,10 +30,11 @@ func (c *Command) Synopsis() string {
}
var flagsMap = map[string][]string{
"create": {"name", "description", "skip-role-creation"},
"create": {"scope-id", "name", "description", "skip-role-creation"},
"update": {"id", "name", "description", "version"},
"read": {"id"},
"delete": {"id"},
"list": {"scope-id"},
}
func (c *Command) Help() string {
@@ -86,6 +87,10 @@ func (c *Command) Run(args []string) int {
c.UI.Error("ID is required but not passed in via -id")
return 1
}
if strutil.StrListContains(flagsMap[c.Func], "scope-id") && c.FlagScopeId == "" {
c.UI.Error("Scope ID must be passed in via -scope-id")
return 1
}
client, err := c.Client()
if err != nil {
@@ -123,7 +128,7 @@ func (c *Command) Run(args []string) int {
default:
switch c.FlagVersion {
case 0:
opts = append(opts, scopes.WithAutomaticVersioning())
opts = append(opts, scopes.WithAutomaticVersioning(true))
default:
version = uint32(c.FlagVersion)
}
@@ -136,7 +141,7 @@ func (c *Command) Run(args []string) int {
switch c.Func {
case "create":
scope, apiErr, err = scopeClient.Create(c.Context, client.ScopeId(), opts...)
scope, apiErr, err = scopeClient.Create(c.Context, c.FlagScopeId, opts...)
case "update":
scope, apiErr, err = scopeClient.Update(c.Context, c.FlagId, version, opts...)
case "read":
@@ -144,7 +149,7 @@ func (c *Command) Run(args []string) int {
case "delete":
existed, apiErr, err = scopeClient.Delete(c.Context, c.FlagId, opts...)
case "list":
listedScopes, apiErr, err = scopeClient.List(c.Context, client.ScopeId(), opts...)
listedScopes, apiErr, err = scopeClient.List(c.Context, c.FlagScopeId, opts...)
}
plural := "scope"
+101
View File
@@ -0,0 +1,101 @@
package targets
import (
"fmt"
"time"
"github.com/hashicorp/boundary/api/scopes"
"github.com/hashicorp/boundary/api/targets"
"github.com/hashicorp/boundary/internal/cmd/base"
)
func generateTargetTableOutput(in *targets.Target) string {
var ret []string
nonAttributeMap := map[string]interface{}{
"ID": in.Id,
"Scope ID": in.Scope.Id,
"Version": in.Version,
"Type": in.Type,
"Created Time": in.CreatedTime.Local().Format(time.RFC3339),
"Updated Time": in.UpdatedTime.Local().Format(time.RFC3339),
"Default Port": in.DefaultPort,
}
if in.Name != "" {
nonAttributeMap["Name"] = in.Name
}
if in.Description != "" {
nonAttributeMap["Description"] = in.Description
}
maxLength := 0
for k := range nonAttributeMap {
if len(k) > maxLength {
maxLength = len(k)
}
}
var hostSetMaps []map[string]interface{}
if len(in.HostSets) > 0 {
for _, set := range in.HostSets {
m := map[string]interface{}{
"ID": set.Id,
"Host Catalog ID": set.HostCatalogId,
}
hostSetMaps = append(hostSetMaps, m)
}
if l := len("Host Catalog ID"); l > maxLength {
maxLength = l
}
}
ret = append(ret, "", "Target information:")
ret = append(ret,
// We do +2 because there is another +2 offset for host sets below
base.WrapMap(2, maxLength+2, nonAttributeMap),
)
if len(in.HostSets) > 0 {
ret = append(ret,
fmt.Sprintf(" Host Sets: %s", ""),
)
for _, m := range hostSetMaps {
ret = append(ret,
base.WrapMap(4, maxLength, m),
"",
)
}
}
return base.WrapForHelpText(ret)
}
func exampleOutput() string {
in := &targets.Target{
Id: "ttcp_1234567890",
ScopeId: "global",
Scope: &scopes.ScopeInfo{
Id: "global",
},
Name: "foo",
Description: "The bar of foos",
CreatedTime: time.Now().Add(-5 * time.Minute),
UpdatedTime: time.Now(),
Version: 3,
Type: "tcp",
HostSetIds: []string{"hsst_1234567890", "hsst_0987654321"},
HostSets: []*targets.HostSet{
{
Id: "hsst_1234567890",
HostCatalogId: "hcst_1234567890",
},
{
Id: "hsst_0987654321",
HostCatalogId: "hcst_1234567890",
},
},
DefaultPort: 22,
}
return generateTargetTableOutput(in)
}
+360
View File
@@ -0,0 +1,360 @@
package targets
import (
"fmt"
"os"
"github.com/hashicorp/boundary/api"
"github.com/hashicorp/boundary/api/targets"
"github.com/hashicorp/boundary/internal/cmd/base"
"github.com/hashicorp/boundary/internal/cmd/common"
"github.com/hashicorp/boundary/internal/types/resource"
"github.com/hashicorp/vault/sdk/helper/strutil"
"github.com/kr/pretty"
"github.com/mitchellh/cli"
"github.com/posener/complete"
)
var _ cli.Command = (*Command)(nil)
var _ cli.CommandAutocomplete = (*Command)(nil)
type Command struct {
*base.Command
Func string
flagHostSets []string
}
func (c *Command) Synopsis() string {
switch c.Func {
case "create":
return "Create target resources within Boundary"
case "update":
return "Update target resources within Boundary"
default:
return common.SynopsisFunc(c.Func, "target")
}
}
var flagsMap = map[string][]string{
"read": {"id"},
"delete": {"id"},
"list": {"scope-id"},
"add-host-sets": {"id", "host-set", "version"},
"remove-host-sets": {"id", "host-set", "version"},
"set-host-sets": {"id", "host-set", "version"},
}
func (c *Command) Help() string {
helpMap := common.HelpMap("target")
var helpStr string
switch c.Func {
case "":
return base.WrapForHelpText([]string{
"Usage: boundary targets [sub command] [options] [args]",
"",
" This command allows operations on Boundary target resources. Example:",
"",
" Read a target:",
"",
` $ boundary targets read -id ttcp_1234567890`,
"",
" Please see the targets subcommand help for detailed usage information.",
})
case "create":
helpStr = base.WrapForHelpText([]string{
"Usage: boundary targets create [type] [sub command] [options] [args]",
"",
" This command allows create operations on Boundary target resources. Example:",
"",
" Create a tcp-type target:",
"",
` $ boundary targets create tcp -name prodops -description "For ProdOps usage"`,
"",
" Please see the typed subcommand help for detailed usage information.",
})
case "update":
helpStr = base.WrapForHelpText([]string{
"Usage: boundary targets update [type] [sub command] [options] [args]",
"",
" This command allows update operations on Boundary target resources. Example:",
"",
" Update a tcp-type target:",
"",
` $ boundary targets update tcp -id ttcp_1234567890 -name devops -description "For DevOps usage"`,
"",
" Please see the typed subcommand help for detailed usage information.",
})
case "add-host-sets":
helpStr = base.WrapForHelpText([]string{
"Usage: boundary target add-host-sets [sub command] [options] [args]",
"",
" This command allows adding host-set resources to target resources. Example:",
"",
" Add host-set resources to a tcp-type target:",
"",
` $ boundary targets add-host-sets -id ttcp_1234567890 -host-set hsst_1234567890 -host-set hsst_0987654321`,
})
case "remove-host-sets":
helpStr = base.WrapForHelpText([]string{
"Usage: boundary target remove-host-sets [sub command] [options] [args]",
"",
" This command allows removing host-set resources from target resources. Example:",
"",
" Remove host-set resources from a tcp-type target:",
"",
` $ boundary targets add-host-sets -id ttcp_1234567890 -host hsst_1234567890 -host-set hsst_0987654321`,
})
case "set-host-sets":
helpStr = base.WrapForHelpText([]string{
"Usage: boundary target set-host-sets [sub command] [options] [args]",
"",
" This command allows setting the complete set of host-set resources on a target resource. Example:",
"",
" Set host-set resources on a tcp-type target:",
"",
` $ boundary targets set-host-sets -id ttcp_1234567890 -host-set hsst_1234567890`,
})
default:
helpStr = helpMap[c.Func]()
}
return helpStr + c.Flags().Help()
}
func (c *Command) Flags() *base.FlagSets {
set := c.FlagSet(base.FlagSetHTTP | base.FlagSetClient | base.FlagSetOutputFormat)
f := set.NewFlagSet("Command Options")
if len(flagsMap[c.Func]) > 0 {
common.PopulateCommonFlags(c.Command, f, resource.Target.String(), flagsMap[c.Func])
}
for _, name := range flagsMap[c.Func] {
switch name {
case "host-set":
f.StringSliceVar(&base.StringSliceVar{
Name: "host-set",
Target: &c.flagHostSets,
Usage: "The host-set resources to add, remove, or set. May be specified multiple times.",
})
}
}
return set
}
func (c *Command) AutocompleteArgs() complete.Predictor {
return complete.PredictAnything
}
func (c *Command) AutocompleteFlags() complete.Flags {
return c.Flags().Completions()
}
func (c *Command) Run(args []string) int {
if os.Getenv("BOUNDARY_EXAMPLE_CLI_OUTPUT") != "" {
c.UI.Output(exampleOutput())
return 0
}
switch c.Func {
case "", "create", "update":
return cli.RunResultHelp
}
f := c.Flags()
if err := f.Parse(args); err != nil {
c.UI.Error(err.Error())
return 1
}
if strutil.StrListContains(flagsMap[c.Func], "id") && c.FlagId == "" {
c.UI.Error("ID is required but not passed in via -id")
return 1
}
if strutil.StrListContains(flagsMap[c.Func], "scope-id") && c.FlagScopeId == "" {
c.UI.Error("Scope ID must be passed in via -scope-id")
return 1
}
client, err := c.Client()
if err != nil {
c.UI.Error(fmt.Sprintf("Error creating API client: %s", err.Error()))
return 2
}
var opts []targets.Option
switch c.FlagName {
case "":
case "null":
opts = append(opts, targets.DefaultName())
default:
opts = append(opts, targets.WithName(c.FlagName))
}
switch c.FlagDescription {
case "":
case "null":
opts = append(opts, targets.DefaultDescription())
default:
opts = append(opts, targets.WithDescription(c.FlagDescription))
}
hostSets := c.flagHostSets
switch c.Func {
case "add-host-sets", "remove-host-sets":
if len(c.flagHostSets) == 0 {
c.UI.Error("No host-sets supplied via -host-set")
return 1
}
case "set-host-sets":
switch len(c.flagHostSets) {
case 0:
case 1:
if c.flagHostSets[0] == "null" {
hostSets = []string{}
}
}
if hostSets == nil {
c.UI.Error("No host-sets supplied via -host-set")
return 1
}
}
// Perform check-and-set when needed
var version uint32
switch c.Func {
case "add-host-sets", "remove-host-sets", "set-host-sets":
switch c.FlagVersion {
case 0:
opts = append(opts, targets.WithAutomaticVersioning(true))
default:
version = uint32(c.FlagVersion)
}
default:
// The only other one that needs it is update, handled by the static
// file
}
targetClient := targets.NewClient(client)
var existed bool
var target *targets.Target
var listedCatalogs []*targets.Target
var apiErr *api.Error
switch c.Func {
case "read":
target, apiErr, err = targetClient.Read(c.Context, c.FlagId, opts...)
case "delete":
existed, apiErr, err = targetClient.Delete(c.Context, c.FlagId, opts...)
case "list":
listedCatalogs, apiErr, err = targetClient.List(c.Context, c.FlagScopeId, opts...)
case "add-host-sets":
target, apiErr, err = targetClient.AddHostSets(c.Context, c.FlagId, version, c.flagHostSets, opts...)
case "remove-host-sets":
target, apiErr, err = targetClient.RemoveHostSets(c.Context, c.FlagId, version, c.flagHostSets, opts...)
case "set-host-sets":
target, apiErr, err = targetClient.SetHostSets(c.Context, c.FlagId, version, c.flagHostSets, opts...)
}
plural := "target"
if c.Func == "list" {
plural = "targets"
}
if err != nil {
c.UI.Error(fmt.Sprintf("Error trying to %s %s: %s", c.Func, plural, err.Error()))
return 2
}
if apiErr != nil {
c.UI.Error(fmt.Sprintf("Error from controller when performing %s on %s: %s", c.Func, plural, pretty.Sprint(apiErr)))
return 1
}
switch c.Func {
case "delete":
switch base.Format(c.UI) {
case "json":
c.UI.Output("null")
case "table":
output := "The delete operation completed successfully"
switch existed {
case true:
output += "."
default:
output += ", however the resource did not exist at the time."
}
c.UI.Output(output)
}
return 0
case "list":
switch base.Format(c.UI) {
case "json":
if len(listedCatalogs) == 0 {
c.UI.Output("null")
return 0
}
b, err := base.JsonFormatter{}.Format(listedCatalogs)
if err != nil {
c.UI.Error(fmt.Errorf("Error formatting as JSON: %w", err).Error())
return 1
}
c.UI.Output(string(b))
case "table":
if len(listedCatalogs) == 0 {
c.UI.Output("No targets found")
return 0
}
var output []string
output = []string{
"",
"Target information:",
}
for i, m := range listedCatalogs {
if i > 0 {
output = append(output, "")
}
if true {
output = append(output,
fmt.Sprintf(" ID: %s", m.Id),
fmt.Sprintf(" Version: %d", m.Version),
fmt.Sprintf(" Type: %s", m.Type),
)
}
if m.Name != "" {
output = append(output,
fmt.Sprintf(" Name: %s", m.Name),
)
}
if m.Description != "" {
output = append(output,
fmt.Sprintf(" Description: %s", m.Description),
)
}
}
c.UI.Output(base.WrapForHelpText(output))
}
return 0
}
switch base.Format(c.UI) {
case "table":
c.UI.Output(generateTargetTableOutput(target))
case "json":
b, err := base.JsonFormatter{}.Format(target)
if err != nil {
c.UI.Error(fmt.Errorf("Error formatting as JSON: %w", err).Error())
return 1
}
c.UI.Output(string(b))
}
return 0
}
+176
View File
@@ -0,0 +1,176 @@
package targets
import (
"fmt"
"net/textproto"
"github.com/hashicorp/boundary/api"
"github.com/hashicorp/boundary/api/targets"
"github.com/hashicorp/boundary/internal/cmd/base"
"github.com/hashicorp/boundary/internal/cmd/common"
"github.com/hashicorp/vault/sdk/helper/strutil"
"github.com/kr/pretty"
"github.com/mitchellh/cli"
"github.com/posener/complete"
)
var _ cli.Command = (*TcpCommand)(nil)
var _ cli.CommandAutocomplete = (*TcpCommand)(nil)
type TcpCommand struct {
*base.Command
Func string
}
func (c *TcpCommand) Synopsis() string {
return fmt.Sprintf("%s a tcp-type target within Boundary", textproto.CanonicalMIMEHeaderKey(c.Func))
}
var tcpFlagsMap = map[string][]string{
"create": {"scope-id", "name", "description"},
"update": {"id", "name", "description", "version"},
}
func (c *TcpCommand) Help() string {
var info string
switch c.Func {
case "create":
info = base.WrapForHelpText([]string{
"Usage: boundary targets tcp create [options] [args]",
"",
" Create a tcp-type target. Example:",
"",
` $ boundary targets tcp create -name prodops -description "Tcp target for ProdOps"`,
"",
"",
})
case "update":
info = base.WrapForHelpText([]string{
"Usage: boundary targets tcp update [options] [args]",
"",
" Update a tcp-type target given its ID. Example:",
"",
` $ boundary targets tcp update -id ttcp_1234567890 -name "devops" -description "Tcp target for DevOps"`,
"",
"",
})
}
return info + c.Flags().Help()
}
func (c *TcpCommand) Flags() *base.FlagSets {
set := c.FlagSet(base.FlagSetHTTP | base.FlagSetClient | base.FlagSetOutputFormat)
if len(tcpFlagsMap[c.Func]) > 0 {
f := set.NewFlagSet("Command Options")
common.PopulateCommonFlags(c.Command, f, "tcp-type target", tcpFlagsMap[c.Func])
}
return set
}
func (c *TcpCommand) AutocompleteArgs() complete.Predictor {
return complete.PredictAnything
}
func (c *TcpCommand) AutocompleteFlags() complete.Flags {
return c.Flags().Completions()
}
func (c *TcpCommand) Run(args []string) int {
if c.Func == "" {
return cli.RunResultHelp
}
f := c.Flags()
if err := f.Parse(args); err != nil {
c.UI.Error(err.Error())
return 1
}
if strutil.StrListContains(tcpFlagsMap[c.Func], "id") && c.FlagId == "" {
c.UI.Error("ID is required but not passed in via -id")
return 1
}
if strutil.StrListContains(tcpFlagsMap[c.Func], "scope-id") && c.FlagScopeId == "" {
c.UI.Error("Scope ID must be passed in via -scope-id")
return 1
}
client, err := c.Client()
if err != nil {
c.UI.Error(fmt.Sprintf("Error creating API client: %s", err.Error()))
return 2
}
var opts []targets.Option
switch c.FlagName {
case "":
case "null":
opts = append(opts, targets.DefaultName())
default:
opts = append(opts, targets.WithName(c.FlagName))
}
switch c.FlagDescription {
case "":
case "null":
opts = append(opts, targets.DefaultDescription())
default:
opts = append(opts, targets.WithDescription(c.FlagDescription))
}
targetClient := targets.NewClient(client)
// Perform check-and-set when needed
var version uint32
switch c.Func {
case "create":
// These don't update so don't need the existing version
default:
switch c.FlagVersion {
case 0:
opts = append(opts, targets.WithAutomaticVersioning(true))
default:
version = uint32(c.FlagVersion)
}
}
var catalog *targets.Target
var apiErr *api.Error
switch c.Func {
case "create":
catalog, apiErr, err = targetClient.Create(c.Context, "tcp", c.FlagScopeId, opts...)
case "update":
catalog, apiErr, err = targetClient.Update(c.Context, c.FlagId, version, opts...)
}
plural := "tcp-type target"
if err != nil {
c.UI.Error(fmt.Sprintf("Error trying to %s %s: %s", c.Func, plural, err.Error()))
return 2
}
if apiErr != nil {
c.UI.Error(fmt.Sprintf("Error from controller when performing %s on %s: %s", c.Func, plural, pretty.Sprint(apiErr)))
return 1
}
switch base.Format(c.UI) {
case "table":
c.UI.Output(generateTargetTableOutput(catalog))
case "json":
b, err := base.JsonFormatter{}.Format(catalog)
if err != nil {
c.UI.Error(fmt.Errorf("Error formatting as JSON: %w", err).Error())
return 1
}
c.UI.Output(string(b))
}
return 0
}
+1
View File
@@ -12,6 +12,7 @@ func generateUserTableOutput(in *users.User) string {
nonAttributeMap := map[string]interface{}{
"ID": in.Id,
"Scope ID": in.Scope.Id,
"Version": in.Version,
"Created Time": in.CreatedTime.Local().Format(time.RFC3339),
"Updated Time": in.UpdatedTime.Local().Format(time.RFC3339),
+9 -4
View File
@@ -28,10 +28,11 @@ func (c *Command) Synopsis() string {
}
var flagsMap = map[string][]string{
"create": {"name", "description"},
"create": {"scope-id", "name", "description"},
"update": {"id", "name", "description", "version"},
"read": {"id"},
"delete": {"id"},
"list": {"scope-id"},
}
func (c *Command) Help() string {
@@ -77,6 +78,10 @@ func (c *Command) Run(args []string) int {
c.UI.Error("ID is required but not passed in via -id")
return 1
}
if strutil.StrListContains(flagsMap[c.Func], "scope-id") && c.FlagScopeId == "" {
c.UI.Error("Scope ID must be passed in via -scope-id")
return 1
}
client, err := c.Client()
if err != nil {
@@ -112,7 +117,7 @@ func (c *Command) Run(args []string) int {
default:
switch c.FlagVersion {
case 0:
opts = append(opts, users.WithAutomaticVersioning())
opts = append(opts, users.WithAutomaticVersioning(true))
default:
version = uint32(c.FlagVersion)
}
@@ -125,7 +130,7 @@ func (c *Command) Run(args []string) int {
switch c.Func {
case "create":
user, apiErr, err = userClient.Create(c.Context, opts...)
user, apiErr, err = userClient.Create(c.Context, c.FlagScopeId, opts...)
case "update":
user, apiErr, err = userClient.Update(c.Context, c.FlagId, version, opts...)
case "read":
@@ -133,7 +138,7 @@ func (c *Command) Run(args []string) int {
case "delete":
existed, apiErr, err = userClient.Delete(c.Context, c.FlagId, opts...)
case "list":
listedUsers, apiErr, err = userClient.List(c.Context, opts...)
listedUsers, apiErr, err = userClient.List(c.Context, c.FlagScopeId, opts...)
}
plural := "user"
+9
View File
@@ -4,11 +4,20 @@ import (
"fmt"
"github.com/hashicorp/boundary/internal/cmd/base"
"github.com/posener/complete"
)
func PopulateCommonFlags(c *base.Command, f *base.FlagSet, resourceType string, flagNames []string) {
for _, name := range flagNames {
switch name {
case "scope-id":
f.StringVar(&base.StringVar{
Name: "scope-id",
Target: &c.FlagScopeId,
Default: "global",
Completion: complete.PredictAnything,
Usage: `Scope in which to make the request. Defaults to "global".`,
})
case "id":
f.StringVar(&base.StringVar{
Name: "id",