Skip to content
Closed
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
6 changes: 5 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,11 @@ ldcli aws-devops-agent setup

The AWS DevOps Agent is available in `us-east-1`, `us-west-2`, `ca-central-1`, `sa-east-1`, `ap-south-1`, `ap-southeast-1`, `ap-southeast-2`, `ap-northeast-1`, `eu-central-1`, `eu-west-1` and `eu-west-2`, and requires AWS CLI 2.36 or later if you also use the AWS CLI directly. `setup` warns when the `aws` binary on your PATH is missing or older than that; the command itself uses the AWS SDK, so it still runs.

`setup` is safe to re-run: it reuses the IAM roles, the agent space matching `--agent-space-name`, the account and MCP associations on it, and any LaunchDarkly MCP server already registered on the account. Pass `--new-agent-space` to create an additional agent space instead. The IAM roles are account-wide and trust the agent spaces in every region, so running `setup` in a second region leaves the first one working; a role named `DevOpsAgentRole-AgentSpace` or `DevOpsAgentRole-WebappAdmin` that `setup` did not create is reused untouched, and it has to trust `aidevops.amazonaws.com` itself.
If the account already runs the AWS DevOps Agent, `setup` lists its agent spaces and asks which one to connect LaunchDarkly to. It then only registers and associates the LaunchDarkly MCP server on the space you pick, leaving its IAM roles, account association and operator app sign-in configuration alone. Pass `--agent-space-id <id>` to pick one without being asked, or `--new-agent-space` to provision another space.

Without a terminal — in CI, or with `--output json` — `setup` reuses the space matching `--agent-space-name` so an unattended re-run stays idempotent, and fails asking for `--agent-space-id` or `--new-agent-space` when the only spaces are ones it did not create.

Otherwise `setup` is safe to re-run: it reuses the IAM roles, the agent space, the account and MCP associations on it, and any LaunchDarkly MCP server already registered on the account. The IAM roles are account-wide and trust the agent spaces in every region, so running `setup` in a second region leaves the first one working; a role named `DevOpsAgentRole-AgentSpace` or `DevOpsAgentRole-WebappAdmin` that `setup` did not create is reused untouched, and it has to trust `aidevops.amazonaws.com` itself.

`--access-token` is optional. The first available token — the flag, then `LD_ACCESS_TOKEN`, then the one already in your ldcli configuration — is registered with AWS as the bearer token the agent uses to call the LaunchDarkly MCP server, so it should be a [service token](https://launchdarkly.com/docs/home/account/api-create) whose permissions match what you want the agent to do. AWS keeps it until the MCP server is re-registered, so a session token written by `ldcli login` eventually expires and the agent then fails with `unauthorized` errors. Re-run with `--access-token <token> --replace-mcp-token` to re-register an MCP server with a different token; the token is checked against LaunchDarkly first, because AWS stores it write-only and the previous registration cannot be restored. The MCP server already registered on the account is the one serving `https://mcp.launchdarkly.com/mcp/launchdarkly`, whatever it is named: pass `--mcp-endpoint` to connect a LaunchDarkly MCP server you host yourself, or `--mcp-service-id` to point at a specific registration. The agent may call `list-projects`, `list-flags` and `get-flag` without asking, and must ask for approval before calling `toggle-flag`.

Expand Down
213 changes: 213 additions & 0 deletions cmd/aws_devops_agent/select_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,213 @@
package awsdevopsagent

import (
"bytes"
"context"
"strings"
"testing"

"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/devopsagent"
agenttypes "github.com/aws/aws-sdk-go-v2/service/devopsagent/types"
"github.com/spf13/cobra"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"

"github.com/launchdarkly/ldcli/internal/awsdevops"
)

type stubAgent struct {
spaces []agenttypes.AgentSpace
}

func (s stubAgent) AssociateService(context.Context, *devopsagent.AssociateServiceInput, ...func(*devopsagent.Options)) (*devopsagent.AssociateServiceOutput, error) {
return nil, nil
}

func (s stubAgent) CreateAgentSpace(context.Context, *devopsagent.CreateAgentSpaceInput, ...func(*devopsagent.Options)) (*devopsagent.CreateAgentSpaceOutput, error) {
return nil, nil
}

func (s stubAgent) DeregisterService(context.Context, *devopsagent.DeregisterServiceInput, ...func(*devopsagent.Options)) (*devopsagent.DeregisterServiceOutput, error) {
return nil, nil
}

func (s stubAgent) DisassociateService(context.Context, *devopsagent.DisassociateServiceInput, ...func(*devopsagent.Options)) (*devopsagent.DisassociateServiceOutput, error) {
return nil, nil
}

func (s stubAgent) EnableOperatorApp(context.Context, *devopsagent.EnableOperatorAppInput, ...func(*devopsagent.Options)) (*devopsagent.EnableOperatorAppOutput, error) {
return nil, nil
}

func (s stubAgent) GetAgentSpace(context.Context, *devopsagent.GetAgentSpaceInput, ...func(*devopsagent.Options)) (*devopsagent.GetAgentSpaceOutput, error) {
return nil, nil
}

func (s stubAgent) ListAgentSpaces(context.Context, *devopsagent.ListAgentSpacesInput, ...func(*devopsagent.Options)) (*devopsagent.ListAgentSpacesOutput, error) {
return &devopsagent.ListAgentSpacesOutput{AgentSpaces: s.spaces}, nil
}

func (s stubAgent) ListAssociations(context.Context, *devopsagent.ListAssociationsInput, ...func(*devopsagent.Options)) (*devopsagent.ListAssociationsOutput, error) {
return &devopsagent.ListAssociationsOutput{}, nil
}

func (s stubAgent) ListServices(context.Context, *devopsagent.ListServicesInput, ...func(*devopsagent.Options)) (*devopsagent.ListServicesOutput, error) {
return &devopsagent.ListServicesOutput{}, nil
}

func (s stubAgent) RegisterService(context.Context, *devopsagent.RegisterServiceInput, ...func(*devopsagent.Options)) (*devopsagent.RegisterServiceOutput, error) {
return nil, nil
}

func testCmd(stdin string) (*cobra.Command, *bytes.Buffer) {
out := &bytes.Buffer{}
cmd := &cobra.Command{}
cmd.SetOut(out)
cmd.SetErr(out)
cmd.SetIn(strings.NewReader(stdin))

return cmd, out
}

func testSpaces() []awsdevops.AgentSpaceSummary {
return []awsdevops.AgentSpaceSummary{
{AgentSpaceID: "space-1", Name: "launchdarkly"},
{AgentSpaceID: "space-2", Name: "platform"},
}
}

func TestSelectAgentSpaceTakesTheChosenSpace(t *testing.T) {
cmd, out := testCmd("2\n")

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

assert.Equal(t, "space-2", chosen)
assert.Contains(t, out.String(), "2) platform (space-2)")
}

func TestSelectAgentSpaceDefaultsToTheFirstSpace(t *testing.T) {
cmd, _ := testCmd("\n")

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

assert.Equal(t, "space-1", chosen)
}

func TestSelectAgentSpaceAsksAgainAfterAnInvalidAnswer(t *testing.T) {
cmd, out := testCmd("9\nnope\n1\n")

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

assert.Equal(t, "space-1", chosen)
assert.Equal(t, 2, strings.Count(out.String(), "Enter a number between 1 and 3"))
}

func TestSelectAgentSpaceProvisionsANewSpaceOnTheLastChoice(t *testing.T) {
cmd, out := testCmd("3\n")

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

assert.Empty(t, chosen)
assert.Contains(t, out.String(), "3) provision a new agent space")
}

func TestSelectAgentSpaceFailsWithoutAnAnswer(t *testing.T) {
cmd, _ := testCmd("")

_, err := selectAgentSpace(cmd, testSpaces(), "us-east-1")

assert.ErrorContains(t, err, "no agent space was chosen")
}

func newStubClients(spaces ...agenttypes.AgentSpace) awsdevops.Clients {
return awsdevops.Clients{Agent: stubAgent{spaces: spaces}, Region: "us-east-1"}
}

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

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

assert.True(t, provision)
assert.Empty(t, opts.AgentSpaceID)
}

func TestResolveAgentSpaceTakesTheFlaggedSpace(t *testing.T) {
cmd, _ := testCmd("")
opts := awsdevops.SetupOptions{AgentSpaceID: "space-2", AgentSpaceName: "launchdarkly"}

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

assert.False(t, provision)
}

// Without a terminal there is nobody to ask, so a space this command owns is
// reused and anything else is an error rather than a guess.
func TestResolveAgentSpaceReusesTheOwnSpaceWithoutATerminal(t *testing.T) {
cmd, _ := testCmd("")
opts := awsdevops.SetupOptions{AgentSpaceName: "launchdarkly"}
clients := newStubClients(agenttypes.AgentSpace{
AgentSpaceId: aws.String("space-1"),
Name: aws.String("launchdarkly"),
})

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

assert.True(t, provision)
}

func TestResolveAgentSpaceFailsOnSomeoneElsesSpaceWithoutATerminal(t *testing.T) {
cmd, _ := testCmd("")
opts := awsdevops.SetupOptions{AgentSpaceName: "launchdarkly"}
clients := newStubClients(agenttypes.AgentSpace{
AgentSpaceId: aws.String("space-2"),
Name: aws.String("platform"),
})

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

assert.ErrorContains(t, err, "platform space-2")
assert.ErrorContains(t, err, "--agent-space-id")
}

func TestResolveAgentSpaceAsksAndConnectsToTheChosenSpace(t *testing.T) {
cmd, _ := testCmd("1\n")
opts := awsdevops.SetupOptions{AgentSpaceName: "launchdarkly"}
clients := newStubClients(agenttypes.AgentSpace{
AgentSpaceId: aws.String("space-2"),
Name: aws.String("platform"),
})

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

assert.False(t, provision)
assert.Equal(t, "space-2", opts.AgentSpaceID)
}

func TestResolveAgentSpaceProvisionsANewSpaceWhenAsked(t *testing.T) {
cmd, _ := testCmd("2\n")
opts := awsdevops.SetupOptions{AgentSpaceName: "launchdarkly"}
clients := newStubClients(agenttypes.AgentSpace{
AgentSpaceId: aws.String("space-1"),
Name: aws.String("launchdarkly"),
})

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

assert.True(t, provision)
assert.Empty(t, opts.AgentSpaceID)
// Without this the matching name makes Setup reuse the space the answer
// declined.
assert.True(t, opts.NewAgentSpace)
}
133 changes: 127 additions & 6 deletions cmd/aws_devops_agent/setup.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
package awsdevopsagent

import (
"bufio"
"fmt"
"os"
"strconv"
"strings"

"github.com/spf13/cobra"
Expand Down Expand Up @@ -34,9 +36,11 @@ func NewSetupCmd(analyticsTrackerFn analytics.TrackerFn) *cobra.Command {
Long: `Create the IAM roles, agent space, AWS account association, operator app and
LaunchDarkly MCP server connection the AWS DevOps Agent needs.

Re-running is safe: setup reuses the agent space matching --agent-space-name
along with anything already attached to it. The run ends with the operator app
URL, where the agent is used.
When the account already has agent spaces, setup asks which one to connect
LaunchDarkly to and only registers the MCP server on it, leaving the rest of
that space as it is. Pass --agent-space-id to pick one without being asked, or
--new-agent-space to provision another space. The run ends with the operator
app URL, where the agent is used.

The MCP server is connected with --access-token, or with the token in your
ldcli configuration when you do not pass one. With neither, setup asks for a
Expand All @@ -50,9 +54,9 @@ expires.`,

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, "", "Existing agent space to add to instead of creating one")
cmd.Flags().String(agentSpaceIDFlag, "", "Connect LaunchDarkly to this existing agent space instead of asking which one to use")
cmd.Flags().String(agentSpaceNameFlag, "launchdarkly", "Name of the agent space to create")
cmd.Flags().Bool(newAgentSpaceFlag, false, "Create another agent space instead of reusing the one matching --agent-space-name")
cmd.Flags().Bool(newAgentSpaceFlag, false, "Provision a new agent space instead of asking which existing one to use")
cmd.Flags().String(authFlowFlag, "iam", "Operator app sign-in method: iam, idc or idp")
cmd.Flags().String(idcInstanceARNFlag, "", "IAM Identity Center instance ARN, required when --auth-flow=idc")
cmd.Flags().String(issuerURLFlag, "", "OIDC issuer URL, required when --auth-flow=idp")
Expand Down Expand Up @@ -95,7 +99,17 @@ func runSetup(cmd *cobra.Command, args []string) error {
}
}

result, err := awsdevops.Setup(cmd.Context(), clients, opts)
provision, err := resolveAgentSpace(cmd, clients, &opts, plaintext && canPrompt())
if err != nil {
return err
}

run := awsdevops.Setup
if !provision {
run = awsdevops.ConnectExisting
}

result, err := run(cmd.Context(), clients, opts)
if err != nil {
return err
}
Expand All @@ -115,6 +129,113 @@ func runSetup(cmd *cobra.Command, args []string) error {
return mcpErr
}

// resolveAgentSpace picks the agent space for this run. If no flag picks one,
// it asks in a terminal. It returns true if setup must provision a new space.
// Otherwise, it sets opts.AgentSpaceID to the chosen space.
func resolveAgentSpace(
cmd *cobra.Command,
clients awsdevops.Clients,
opts *awsdevops.SetupOptions,
interactive bool,
) (bool, error) {
if opts.NewAgentSpace {
return true, nil
}
if opts.AgentSpaceID != "" {
return false, nil
}

spaces, err := awsdevops.AgentSpaces(cmd.Context(), clients)
if err != nil {
return false, err
}
if len(spaces) == 0 {
return true, nil
}

if !interactive {
// Reuse the space this command provisions by name, so an unattended
// re-run stays idempotent, but never guess between spaces someone
// else set up.
for _, space := range spaces {
if strings.EqualFold(space.Name, opts.AgentSpaceName) {
return true, nil
}
}

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 provision another",
clients.Region,
strings.Join(agentSpaceLabels(spaces), ", "),
agentSpaceIDFlag,
newAgentSpaceFlag,
)
}

choice, err := selectAgentSpace(cmd, spaces, clients.Region)
if err != nil {
return false, err
}
if choice == "" {
opts.NewAgentSpace = true

return true, nil
}
opts.AgentSpaceID = choice

return false, nil
}

// selectAgentSpace asks which agent space to connect LaunchDarkly to, and
// returns an empty string when the answer is to provision a new one.
func selectAgentSpace(cmd *cobra.Command, spaces []awsdevops.AgentSpaceSummary, region string) (string, error) {
out := cmd.OutOrStdout()
_, _ = fmt.Fprintf(out, "\nThis AWS account already runs the DevOps Agent in %s:\n\n", region)
for i, space := range spaces {
_, _ = fmt.Fprintf(out, " %d) %s (%s)\n", i+1, space.Name, space.AgentSpaceID)
}
newSpaceChoice := len(spaces) + 1
_, _ = fmt.Fprintf(out, " %d) provision a new agent space\n\n", newSpaceChoice)

// One reader for the whole prompt, so a retry does not lose input the
// previous read already buffered.
reader := bufio.NewReader(cmd.InOrStdin())
for {
_, _ = fmt.Fprint(out, "Which one should LaunchDarkly connect to? [1]: ")
line, err := reader.ReadString('\n')
if err != nil && line == "" {
return "", fmt.Errorf("no agent space was chosen; pass --%s or --%s", agentSpaceIDFlag, newAgentSpaceFlag)
}

answer := strings.TrimSpace(line)
if answer == "" {
return spaces[0].AgentSpaceID, nil
}

choice, err := strconv.Atoi(answer)
if err != nil || choice < 1 || choice > newSpaceChoice {
_, _ = fmt.Fprintf(cmd.ErrOrStderr(), "Enter a number between 1 and %d\n", newSpaceChoice)

continue
}
if choice == newSpaceChoice {
return "", nil
}

return spaces[choice-1].AgentSpaceID, nil
}
}

func agentSpaceLabels(spaces []awsdevops.AgentSpaceSummary) []string {
labels := make([]string, 0, len(spaces))
for _, space := range spaces {
labels = append(labels, fmt.Sprintf("%s %s", space.Name, space.AgentSpaceID))
}

return labels
}

// connectMCPServer collects a LaunchDarkly service token and registers the MCP
// server with it, for a run that started without a token to register.
func connectMCPServer(
Expand Down
Loading
Loading