Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 13 additions & 3 deletions cmd/aws_devops_agent/confirm_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,17 @@ func setupTestCmd(t *testing.T, stdin string) (*cobra.Command, *bytes.Buffer) {
}

func newSpaceOptions() awsdevops.SetupOptions {
return awsdevops.SetupOptions{AgentSpaceName: "ld-devops-agent", AuthFlow: "iam", LDAccessToken: "api-token"}
return awsdevops.SetupOptions{AgentSpaceName: "ld-devops-agent", NewAgentSpace: true, AuthFlow: "iam", LDAccessToken: "api-token"}
}

// existingSpaceOptions picks the space with this name. An empty name lets
// setup ask, or pick the space that setup made.
func existingSpaceOptions(name string) awsdevops.SetupOptions {
opts := newSpaceOptions()
opts.NewAgentSpace = false
opts.AgentSpaceName = name

return opts
}

// A json run in a terminal asks too, because the question goes to stderr.
Expand Down Expand Up @@ -289,7 +299,7 @@ func TestSetupConfirmsAfterTheSpaceChoice(t *testing.T) {
Name: aws.String("platform"),
})

err := setupWith(cmd, clients, newSpaceOptions(), true, true)
err := setupWith(cmd, clients, existingSpaceOptions(""), true, true)

require.Error(t, err)
assert.Contains(t, strings.ToLower(err.Error()), "cancel")
Expand Down Expand Up @@ -328,7 +338,7 @@ func TestSetupPromptsGoToStderr(t *testing.T) {
Name: aws.String("platform"),
})

_ = setupWith(cmd, clients, newSpaceOptions(), true, true)
_ = setupWith(cmd, clients, existingSpaceOptions(""), true, true)

assert.Contains(t, stderrOf(cmd), "Which one should LaunchDarkly connect to?")
assert.Contains(t, stderrOf(cmd), "Continue? [y/N]")
Expand Down
23 changes: 12 additions & 11 deletions cmd/aws_devops_agent/plan_print_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,10 @@ func TestSetupConnectWithoutATokenStops(t *testing.T) {
cmd, _ := setupTestCmd(t, "2\n\n")
clients, w := twoSimilarSpaces()

err := setupWith(cmd, clients, noTokenOptions(), true, true)
opts := existingSpaceOptions("")
opts.LDAccessToken = ""

err := setupWith(cmd, clients, opts, true, true)

require.Error(t, err)
assert.Contains(t, err.Error(), "nothing to do on agent space LaunchDarkly (space-2)")
Expand Down Expand Up @@ -229,8 +232,7 @@ func TestSetupWithYesSkipsSpaceChoice(t *testing.T) {
cmd.SetIn(noReadStdin{t})
require.NoError(t, cmd.Flags().Set(yesFlag, "true"))
clients, w := countingClients(agenttypes.AgentSpace{AgentSpaceId: aws.String("space-2"), Name: aws.String("platform")})
opts := newSpaceOptions()
opts.AgentSpaceName = ""
opts := existingSpaceOptions("")

err := setupWith(cmd, clients, opts, true, true)

Expand Down Expand Up @@ -262,7 +264,7 @@ func TestSetupWithYesStopsOnTwoSpacesWithTheName(t *testing.T) {
agenttypes.AgentSpace{AgentSpaceId: aws.String("space-2"), Name: aws.String("LD-DevOps-Agent")},
)

err := setupWith(cmd, clients, newSpaceOptions(), true, true)
err := setupWith(cmd, clients, existingSpaceOptions("ld-devops-agent"), true, true)

require.Error(t, err)
assert.Contains(t, err.Error(), "space-1")
Expand All @@ -277,7 +279,7 @@ func TestSetupWithYesReusesMatchingSpace(t *testing.T) {
require.NoError(t, cmd.Flags().Set(yesFlag, "true"))
clients, w := countingClients(ldcliSpace("space-2", "ld-devops-agent"))

require.NoError(t, setupWith(cmd, clients, newSpaceOptions(), true, true))
require.NoError(t, setupWith(cmd, clients, existingSpaceOptions("ld-devops-agent"), true, true))

assert.NotContains(t, w.calls, "CreateAgentSpace")
assert.Contains(t, w.calls, "EnableOperatorApp")
Expand All @@ -298,7 +300,7 @@ func TestSetupWithYesConnectsToANamedSpaceItDidNotMake(t *testing.T) {
require.NoError(t, cmd.Flags().Set(yesFlag, "true"))
clients, w := countingClients(agenttypes.AgentSpace{AgentSpaceId: aws.String("space-2"), Name: aws.String("ld-devops-agent")})

require.NoError(t, setupWith(cmd, clients, newSpaceOptions(), true, true))
require.NoError(t, setupWith(cmd, clients, existingSpaceOptions("ld-devops-agent"), true, true))

assert.Contains(t, stderrOf(cmd), "Connect to agent space ld-devops-agent (space-2)")
assert.Contains(t, w.calls, "AssociateService")
Expand All @@ -315,7 +317,7 @@ func TestSetupEnterGivesFullSetupOnTheSpaceSetupMade(t *testing.T) {
ldcliSpace("space-2", "ld-devops-agent"),
)

require.NoError(t, setupWith(cmd, clients, newSpaceOptions(), true, true))
require.NoError(t, setupWith(cmd, clients, existingSpaceOptions("ld-devops-agent"), true, true))

assert.Contains(t, out.String(), "connect to? [2] ")
assert.Contains(t, out.String(), "Reuse agent space ld-devops-agent (space-2)")
Expand All @@ -331,8 +333,7 @@ func TestSetupEnterWithoutANamePicksTheSpaceSetupMade(t *testing.T) {
agenttypes.AgentSpace{AgentSpaceId: aws.String("space-1"), Name: aws.String("platform")},
ldcliSpace("space-2", "ld-devops-agent"),
)
opts := newSpaceOptions()
opts.AgentSpaceName = ""
opts := existingSpaceOptions("")

require.NoError(t, setupWith(cmd, clients, opts, true, true))

Expand Down Expand Up @@ -382,7 +383,7 @@ func TestSetupChosenSpaceWithoutAuthFlowConnects(t *testing.T) {
cmd, _ := setupTestCmd(t, "2\ny\n")
clients, w := twoSimilarSpaces()

require.NoError(t, setupWith(cmd, clients, newSpaceOptions(), true, true))
require.NoError(t, setupWith(cmd, clients, existingSpaceOptions(""), true, true))

assert.NotContains(t, w.calls, "EnableOperatorApp")
assert.NotContains(t, w.calls, "CreateRole")
Expand All @@ -399,7 +400,7 @@ func TestSetupNewSpaceChoiceAsksForAnUnusedName(t *testing.T) {
cmd, out := setupTestCmd(t, "2\nld-devops-agent\nfresh\ny\n")
clients, w := countingClients(agenttypes.AgentSpace{AgentSpaceId: aws.String("space-2"), Name: aws.String("ld-devops-agent")})

require.NoError(t, setupWith(cmd, clients, newSpaceOptions(), true, true))
require.NoError(t, setupWith(cmd, clients, existingSpaceOptions(""), true, true))

assert.Contains(t, out.String(), "An agent space named ld-devops-agent already exists")
assert.Contains(t, out.String(), "Create agent space fresh")
Expand Down
65 changes: 44 additions & 21 deletions cmd/aws_devops_agent/select_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"bytes"
"context"
"errors"
"fmt"
"strings"
"testing"

Expand Down Expand Up @@ -152,25 +153,52 @@ func TestSelectAgentSpaceDefaultsToTheSpaceWithTheName(t *testing.T) {
assert.NotContains(t, out.String(), "named")
}

func TestSelectAgentSpaceDefaultsToANewSpaceWithAnUnusedName(t *testing.T) {
cmd, out := testCmd("\n")
// A name that no space has cannot create a space, with or without a terminal.
func TestResolveAgentSpaceStopsOnANameThatNoSpaceHas(t *testing.T) {
for name, clients := range map[string]awsdevops.Clients{
"no spaces": newStubClients(),
"other spaces": newStubClients(agenttypes.AgentSpace{
AgentSpaceId: aws.String("space-2"),
Name: aws.String("platform"),
}),
} {
for _, interactive := range []bool{true, false} {
t.Run(fmt.Sprintf("%s, interactive %t", name, interactive), func(t *testing.T) {
cmd, out := testCmd("1\n")
opts := awsdevops.SetupOptions{AgentSpaceName: "test"}

_, err := resolveAgentSpace(cmd, clients, &opts, interactive)

require.Error(t, err)
assert.Contains(t, err.Error(), "no agent space in us-east-1 is named test")
assert.Contains(t, err.Error(), "--new-agent-space")
assert.False(t, opts.NewAgentSpace)
assert.NotContains(t, out.String(), "connect to?")
})
}
}
}

chosen, err := selectAgentSpace(cmd, testSpaces(), "us-east-1", "payments")
require.NoError(t, err)
func TestResolveAgentSpaceErrorListsTheSpaces(t *testing.T) {
cmd, _ := testCmd("")
opts := awsdevops.SetupOptions{AgentSpaceName: "test"}
clients := newStubClients(agenttypes.AgentSpace{AgentSpaceId: aws.String("space-2"), Name: aws.String("platform")})

_, err := resolveAgentSpace(cmd, clients, &opts, false)

assert.Equal(t, spaceChoice{newSpace: true, name: "payments"}, chosen)
assert.Contains(t, out.String(), "3) provision a new agent space named payments")
assert.Contains(t, out.String(), "4) provision a new agent space\n")
assert.Contains(t, out.String(), "connect to? [3] ")
require.Error(t, err)
assert.Contains(t, err.Error(), "The agent spaces in us-east-1 are platform space-2")
}

func TestSelectAgentSpaceLetsYouNameANewSpaceAfterAName(t *testing.T) {
cmd, _ := testCmd("4\n")
func TestSelectAgentSpaceOffersOneNewSpaceChoice(t *testing.T) {
cmd, out := testCmd("3\n")

chosen, err := selectAgentSpace(cmd, testSpaces(), "us-east-1", "payments")
chosen, err := selectAgentSpace(cmd, testSpaces(), "us-east-1", "")
require.NoError(t, err)

assert.Equal(t, spaceChoice{newSpace: true}, chosen)
assert.Contains(t, out.String(), "3) provision a new agent space\n")
assert.NotContains(t, out.String(), "4)")
}

func TestSelectAgentSpaceMarksTheSpacesSetupMade(t *testing.T) {
Expand Down Expand Up @@ -250,14 +278,15 @@ func newStubClients(spaces ...agenttypes.AgentSpace) awsdevops.Clients {
}

func TestResolveAgentSpaceProvisionsWhenTheAccountHasNone(t *testing.T) {
cmd, _ := testCmd("")
opts := awsdevops.SetupOptions{AgentSpaceName: "launchdarkly"}
cmd, _ := testCmd("launchdarkly\n")
opts := awsdevops.SetupOptions{}

provision, err := resolveAgentSpace(cmd, newStubClients(), &opts, false)
provision, err := resolveAgentSpace(cmd, newStubClients(), &opts, true)
require.NoError(t, err)

assert.True(t, provision)
assert.Empty(t, opts.AgentSpaceID)
assert.Equal(t, "launchdarkly", opts.AgentSpaceName)
}

func TestResolveAgentSpaceTakesTheFlaggedSpace(t *testing.T) {
Expand Down Expand Up @@ -300,7 +329,7 @@ func TestResolveAgentSpaceFailsOnSomeoneElsesSpaceWithoutATerminal(t *testing.T)

func TestResolveAgentSpaceAsksAndConnectsToTheChosenSpace(t *testing.T) {
cmd, _ := testCmd("1\n")
opts := awsdevops.SetupOptions{AgentSpaceName: "launchdarkly"}
opts := awsdevops.SetupOptions{}
clients := newStubClients(agenttypes.AgentSpace{
AgentSpaceId: aws.String("space-2"),
Name: aws.String("platform"),
Expand Down Expand Up @@ -501,12 +530,6 @@ func TestPickWithoutAskingUsesANameBesideAHiddenSpace(t *testing.T) {
require.NoError(t, err)
assert.True(t, provision)
assert.Equal(t, "space-1", opts.AgentSpaceID)

opts = awsdevops.SetupOptions{AgentSpaceName: "new-space"}
provision, err = pickWithoutAsking(spaces, &opts, "us-east-1")
require.NoError(t, err)
assert.True(t, provision)
assert.True(t, opts.NewAgentSpace)
}

// One failed tag lookup leaves the other spaces in the list.
Expand Down
39 changes: 23 additions & 16 deletions cmd/aws_devops_agent/setup.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ for --access-token.`,
cmd.Flags().String(regionFlag, "", "AWS region to provision in. Defaults to the region of the current AWS session")
cmd.Flags().String(profileFlag, "", "Named AWS profile to use. Overrides AWS_PROFILE for this command")
cmd.Flags().String(agentSpaceIDFlag, "", "Use this agent space. --auth-flow runs full setup on a space that setup did not make")
cmd.Flags().String(agentSpaceNameFlag, "", "Name of the agent space to use or create. In a terminal, setup asks for a name if it needs one")
cmd.Flags().String(agentSpaceNameFlag, "", "Name of an existing agent space to use. With --new-agent-space, the name of the new space")
cmd.Flags().Bool(newAgentSpaceFlag, false, "Provision a new agent space instead of asking which existing one to use")
cmd.MarkFlagsMutuallyExclusive(agentSpaceIDFlag, newAgentSpaceFlag)
cmd.Flags().String(authFlowFlag, "iam", "Operator app sign-in method: iam, idc or idp")
Expand Down Expand Up @@ -236,6 +236,10 @@ func resolveAgentSpace(
if err != nil {
return false, err
}
if opts.AgentSpaceName != "" && !hasSpaceNamed(spaces, opts.AgentSpaceName) {
// A name picks an existing space, so a wrong name cannot create one.
return false, noSpaceNamed(spaces, opts.AgentSpaceName, clients.Region)
}
if len(spaces) == 0 {
opts.NewAgentSpace = true

Expand Down Expand Up @@ -299,8 +303,8 @@ func summaryOf(spaces []awsdevops.AgentSpaceSummary, id string) awsdevops.AgentS
}

// pickWithoutAsking picks a space for a run that cannot ask. With a name, it
// does what Enter does at the list: it uses the one space with that name, or
// creates the space when no space has the name. Without a name, it reuses the
// does what Enter does at the list: it uses the one space with that name.
// Without a name, it reuses the
// one space that setup made, so an unattended re-run stays idempotent. It never
// guesses between spaces that setup did not make.
//
Expand Down Expand Up @@ -328,12 +332,6 @@ func pickWithoutAsking(all []awsdevops.AgentSpaceSummary, opts *awsdevops.SetupO

return opts.AuthFlowSet || spaces[i].ManagedByLDCLI, nil
}
if !hasSpaceNamed(spaces, name) {
opts.NewAgentSpace = true

return true, nil
}

var named []awsdevops.AgentSpaceSummary
for _, space := range spaces {
if strings.EqualFold(space.Name, name) {
Expand All @@ -354,12 +352,26 @@ func pickWithoutAsking(all []awsdevops.AgentSpaceSummary, opts *awsdevops.SetupO
}

return false, fmt.Errorf(
"this AWS account already has agent spaces in %s (%s); pass --%s to connect "+
"LaunchDarkly to one of them, or --%s to use or create a space by name",
"this AWS account already has agent spaces in %s (%s); pass --%s or --%s to connect "+
"LaunchDarkly to one of them, or --%s to provision a new space",
region,
strings.Join(agentSpaceLabels(spaces), ", "),
agentSpaceIDFlag,
agentSpaceNameFlag,
newAgentSpaceFlag,
)
}

// noSpaceNamed is the error for a name that no space in the region has.
func noSpaceNamed(spaces []awsdevops.AgentSpaceSummary, name, region string) error {
listing := ""
if len(spaces) > 0 {
listing = fmt.Sprintf(". The agent spaces in %s are %s", region, strings.Join(agentSpaceLabels(spaces), ", "))
}

return fmt.Errorf(
"no agent space in %s is named %s%s. To provision a new agent space with that name, also pass --%s",
region, name, listing, newAgentSpaceFlag,
)
}

Expand Down Expand Up @@ -560,11 +572,6 @@ func selectAgentSpace(
if hasSpaceNamed(unread, name) {
defaultIndex = -1
}
if name != "" && !hasSpaceNamed(all, name) {
defaultIndex = len(choices)
choices = append(choices, spaceChoice{newSpace: true, name: name})
labels = append(labels, "provision a new agent space named "+name)
}
choices = append(choices, spaceChoice{newSpace: true})
labels = append(labels, "provision a new agent space")

Expand Down
2 changes: 1 addition & 1 deletion internal/awsdevops/runplan_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -340,7 +340,7 @@ func TestRunPlanNewSpaceRefusesAUsedName(t *testing.T) {
require.Error(t, err)
assert.NotErrorIs(t, err, awsdevops.ErrPlanChanged)
assert.Contains(t, err.Error(), "space-7")
assert.Contains(t, err.Error(), "--agent-space-name")
assert.Contains(t, err.Error(), "--agent-space-id space-7")
assert.NotContains(t, agent.calls, "CreateAgentSpace")
assert.Empty(t, iamClient.createdRoles)
}
Expand Down
13 changes: 10 additions & 3 deletions internal/awsdevops/setup.go
Original file line number Diff line number Diff line change
Expand Up @@ -494,10 +494,17 @@ func planAgentSpace(ctx context.Context, clients Clients, opts SetupOptions, pro
case err != nil:
return SpaceStep{}, err
case len(seen) > 0 && opts.NewAgentSpace && provision:
// Two spaces with one name make the next run unable to pick.
// Two spaces with one name make the next run unable to pick. A
// re-run after a failed run gets here, so name how to use the space.
id := "<id>"
if len(seen) == 1 {
id = seen[0]
}

return SpaceStep{}, fmt.Errorf(
"an agent space named %s already exists (%s). Pass --agent-space-name with another name",
opts.AgentSpaceName, strings.Join(seen, ", "),
"an agent space named %s already exists (%s). To use it, remove --new-agent-space and run setup again. "+
"To pick the space by its ID, also replace --agent-space-name with --agent-space-id %s",
opts.AgentSpaceName, strings.Join(seen, ", "), id,
)
case len(seen) > 1:
return SpaceStep{}, fmt.Errorf(
Expand Down
3 changes: 3 additions & 0 deletions internal/awsdevops/setup_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,9 @@ func TestPlanSetupRefusesANewSpaceWithAUsedName(t *testing.T) {

require.Error(t, err)
assert.Contains(t, err.Error(), "an agent space named launchdarkly already exists (space-existing)")
// A re-run of the command that created the space gets here.
assert.Contains(t, err.Error(), "remove --new-agent-space and run setup again. To pick the space by its ID, also replace --agent-space-name with --agent-space-id space-existing")
assert.NotContains(t, err.Error(), "another name")
assert.Equal(t, awsdevops.SpaceStep{}, plan.Space)
}

Expand Down
Loading