Visitar URL original
cli/cloud: add `pulumi insights resource search` by i-am-tom · Pull Request #23087 · pulumi/pulumi · GitHub
Skip to content

cli/cloud: add pulumi insights resource search - #23087

Merged
i-am-tom merged 4 commits into
masterfrom
claude/loving-kirch-77519b
May 13, 2026
Merged

i-am-tom merged 4 commits into
masterfrom
claude/loving-kirch-77519b

Conversation

@i-am-tom

@i-am-tom i-am-tom commented May 13, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Adds pulumi insights resource search, the second leaf command under the Cloud-Ready CLI epic for pulumi insights. Closes #22975.

The command wraps the GetOrgResourceSearchV2Query endpoint:

pulumi insights resource search
  [--org <org-name>]            # context; defaults to the current default org
  [--query, -q <pulumi-query>]  # filter; empty matches all
  [--sort <field>...]           # repeat or comma-separate; whitelist enforced
  [--asc]                       # flip direction; defaults to descending
  [--page <n>]                  # 1-based, up to 10,000 total results
  [--page-size <n>]
  [--cursor <opaque>]           # beyond 10,000 (Enterprise plans only)
  [--properties]                # include input/output values; 402 on unsupported subs
  [--collapse]                  # consolidate IaC+Insights duplicates
  [--output, -o default|json]   # default: tab-aligned text

--sort is validated against the documented whitelist before the API call so a typo doesn't burn a request. --asc defaults to descending; the flag is only sent when set so the server's default applies otherwise. The same is true of every other zero-valued query parameter — they're stripped via url:"...,omitempty" tags on apitype.InsightsResourceSearchParams.

The command follows the CLI Command Guidelines and CLI Option Guidelines:

  • search is a leaf verb under the resource noun, which nests under insights.
  • All inputs are contextual or filters — none are required positional arguments.
  • Default output is human-readable, not JSON.
  • --output and --sort are validated before the API call.
  • Constructed via newInsightsResourceSearchCmd(factory) for injection-based unit testing; passing nil installs the production factory that wraps cloud.ResolveContext.

New apitypes mirror the OpenAPI response schema: InsightsResourceSearchParams, InsightsResourceSearchResponse, InsightsResourceSearchResult, InsightsResourceSearchPagination, InsightsResourceSearchAggregation. A new *client.Client.SearchInsightsResources method takes the params struct directly — go-querystring handles the URL encoding via struct tags.

Sample output

Captured by running the renderer against a representative InsightsResourceSearchResponse fixture.

Default (tab-aligned text)

$ pulumi insights resource search --query 'type:aws:s3/bucket:Bucket'
URN                                                    TYPE                  STACK  ACCOUNT   MODIFIED
urn:pulumi:prod::api::aws:s3/bucket:Bucket::my-bucket  aws:s3/bucket:Bucket  prod   prod-aws  2026-05-01T14:30:00Z
aws:s3/bucket:Bucket::other-bucket                     aws:s3/bucket:Bucket  -      prod-aws  -

Showing 2 of 2 resources.
More results available. Re-run with --cursor "next-token" to continue.

Rows without a URN (Insights-only records that weren't deployed via Pulumi) fall back to <type>::<id> in the URN column so every row stays identifiable. Empty columns render as - to keep alignment.

Empty result set:

$ pulumi insights resource search --query 'type:aws:nonexistent'
No resources found.

Last page (no pagination.next):

$ pulumi insights resource search --query 'type:aws:s3'
URN                                                    TYPE                  STACK  ACCOUNT   MODIFIED
urn:pulumi:prod::api::aws:s3/bucket:Bucket::my-bucket  aws:s3/bucket:Bucket  prod   prod-aws  2026-05-01T14:30:00Z
…
Showing 12 of 12 resources.

--output json

$ pulumi insights resource search --query 'type:aws:s3/bucket:Bucket' --output json
{
  "total": 2,
  "resources": [
    {
      "account": "prod-aws",
      "custom": true,
      "id": "my-bucket",
      "modified": "2026-05-01T14:30:00Z",
      "project": "api",
      "stack": "prod",
      "type": "aws:s3/bucket:Bucket",
      "urn": "urn:pulumi:prod::api::aws:s3/bucket:Bucket::my-bucket"
    },
    {
      "account": "prod-aws",
      "id": "other-bucket",
      "type": "aws:s3/bucket:Bucket"
    }
  ],
  "pagination": {
    "next": "/api/orgs/acme/search/resourcesv2?query=foo&cursor=next-token&size=2",
    "cursor": "bookmark"
  }
}

Errors

Invalid --sort is caught before the API call:

$ pulumi insights resource search --sort bogus
error: invalid --sort value "bogus" (allowed: category, created, custom, delete, dependencies, id, managed, modified, module, name, package, parentUrn, project, protected, providerUrn, stack, type, urn)

Invalid --output is caught before the API call:

$ pulumi insights resource search --output yaml
error: invalid --output value "yaml" (must be 'default' or 'json')

Server-side errors propagate via the existing API client error path, e.g. --properties=true against an unsupported subscription:

$ pulumi insights resource search --properties
error: searching insights resources: [402] Payment Required: …

Test plan

  • Added appropriate unit tests - For all changes
  • Added a test in pkg/engine/lifecycletest - For all engine/protocol changes
  • Added a conformance test in pkg/testing/pulumi-test-language - For language protocol changes
  • Added a golden test in pkg/backend/display - For changes to the output renderers

pkg/cmd/pulumi/insights/insights_resource_search_test.go covers:

  • Default text output, including URN fallback for rows without a URN, the - filler for empty cells, and the pagination-hint that surfaces the cursor extracted from pagination.next
  • Empty result set ("No resources found.")
  • Last page (no pagination.next → no hint)
  • JSON output (assert.Equal against the fixture)
  • Default org vs --org override propagation
  • Full param propagation (--query, --sort repeated, --asc, --page, --page-size, --cursor, --properties, --collapse)
  • Invalid --sort rejected with a message listing allowed values
  • Invalid --output rejected before the API call
  • Client error propagation (e.g. 402) and factory error propagation (not logged in)
  • Full cobra-level flag binding through newInsightsResourceSearchCmd(factory).Execute
  • newInsightsResourceSearchCmd(nil) installs the production factory
  • cursorFromNextLink extracts the cursor from both relative and absolute URLs, and degrades gracefully when the link is empty or has no cursor

pkg/backend/httpstate/client/client_insights_test.go covers SearchInsightsResources against a httptest.NewServer:

  • Round-trip of a populated response (including Custom *bool, pagination, etc.)
  • Query parameter encoding — confirms query, sort (repeated), asc, page, size, properties, collapse all reach the server
  • Zero-valued parameters are omitted (empty query string)
  • HTTP error propagation (402 Payment Required)

Validation

  • make lint — clean (golangci-lint run --tests over the affected packages reports 0 issues)
  • make test_fast — relevant package tests pass (insightscmd, httpstate/client, plus the broader ./cmd/pulumi/... sweep)
  • make tidy_fix — clean (no go.mod changes; only existing in-tree imports)
  • make format — clean (gofmt -l reports no diffs on touched files)
  • Relevant SDK tests pass (if SDK changes) — sdk/go/common/apitype tests pass
  • make check_proto — n/a, no proto changes

Changelog

  • Changelog entry added: cli/cloud: Add \pulumi insights resource search` to search for resources discovered by Pulumi Insights`

Risk

Strictly additive: new apitypes in sdk/go/common/apitype/insights.go, a new *client.Client.SearchInsightsResources method, a new endpoint registration in pkg/backend/httpstate/client/api_endpoints.go, and the full pulumi insights resource search command replacing the previous stub. The stub was already wired in via newInsightsResourceCmd (added in #23077), so the wiring lines in pkg/cmd/pulumi/pulumi.go don't change.

The pulumi insights tree is still marked [EXPERIMENTAL] in --help text, matching the get command added in #23077.

🤖 Generated with Claude Code

Implements the second leaf command under the Cloud-Ready CLI epic for
`pulumi insights`, wrapping the `GetOrgResourceSearchV2Query` Pulumi
Cloud REST endpoint.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
@i-am-tom
i-am-tom marked this pull request as ready for review May 13, 2026 07:40
@i-am-tom
i-am-tom requested a review from a team as a code owner May 13, 2026 07:40
…by offset

The v2 endpoint returns either a cursor or a `page`/`size` pair in
`pagination.next`. The hint only recognised cursors, so the non-Enterprise
default landed on a raw URL the user couldn't usefully copy back into the
shell.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
@tgummerer

Copy link
Copy Markdown
Collaborator

Have we decided on this layout vs table format now? I've been going with table format rather than tab separated, but I'm happy to change to whatever. We should try to find some consistency though.

@tgummerer tgummerer left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Only superficially reviewed this, but I trust you tested it.

client := newMockClient(server)
_, err := client.SearchInsightsResources(t.Context(), "acme",
apitype.InsightsResourceSearchParams{Properties: true})
require.Error(t, err)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

probably want to assert on the error text here.

i-am-tom and others added 2 commits May 13, 2026 13:22
Aligns the default output with `pulumi stack webhook list` and
`pulumi org search`, both of which use `go-pretty`'s StyleLight box drawing.
Drops optional columns (STACK/ACCOUNT/MODIFIED) when no row carries a value
so a search that only matches IaC-only or Insights-only resources doesn't
show an empty column. URN absorbs the leftover terminal width with wrapping,
falling back to 120 cols when stdout isn't a TTY. `--output table` is
accepted as an alias for `default` to match the convention.

Also asserts on the error body in the `propagates HTTP errors` subtest so a
regression that swallows the server message or the status code is caught.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
…-77519b

# Conflicts:
#	pkg/cmd/pulumi/insights/insights_resource.go
@i-am-tom
i-am-tom enabled auto-merge May 13, 2026 11:49
@i-am-tom
i-am-tom added this pull request to the merge queue May 13, 2026
Merged via the queue into master with commit c7ddd56 May 13, 2026
230 of 232 checks passed
@i-am-tom
i-am-tom deleted the claude/loving-kirch-77519b branch May 13, 2026 16:20
@pulumi-bot

Copy link
Copy Markdown
Contributor

This PR has been shipped in release v3.238.0.

tgummerer pushed a commit that referenced this pull request May 14, 2026
## Summary

Adds `pulumi insights resource search`, the second leaf command under
the [Cloud-Ready CLI](#22959)
epic for `pulumi insights`. Closes
[#22975](#22975).

The command wraps the
[`GetOrgResourceSearchV2Query`](https://www.pulumi.com/docs/reference/cloud-rest-api/resource-search/#get-apiorgsorgnamesearchresourcesv2)
endpoint:

```
pulumi insights resource search
  [--org <org-name>]            # context; defaults to the current default org
  [--query, -q <pulumi-query>]  # filter; empty matches all
  [--sort <field>...]           # repeat or comma-separate; whitelist enforced
  [--asc]                       # flip direction; defaults to descending
  [--page <n>]                  # 1-based, up to 10,000 total results
  [--page-size <n>]
  [--cursor <opaque>]           # beyond 10,000 (Enterprise plans only)
  [--properties]                # include input/output values; 402 on unsupported subs
  [--collapse]                  # consolidate IaC+Insights duplicates
  [--output, -o default|json]   # default: tab-aligned text
```

`--sort` is validated against the documented whitelist before the API
call so a typo doesn't burn a request. `--asc` defaults to descending;
the flag is only sent when set so the server's default applies
otherwise. The same is true of every other zero-valued query parameter —
they're stripped via `url:"...,omitempty"` tags on
`apitype.InsightsResourceSearchParams`.

The command follows the [CLI Command
Guidelines](https://www.notion.so/CLI-Command-Guidelines-350fdbdf1cce80b89367c16b7b421e3d)
and [CLI Option
Guidelines](https://www.notion.so/CLI-Option-Guidelines-357fdbdf1cce8043af51c13f8246b5ce):

- `search` is a leaf verb under the `resource` noun, which nests under
`insights`.
- All inputs are contextual or filters — none are required positional
arguments.
- Default output is human-readable, not JSON.
- `--output` and `--sort` are validated before the API call.
- Constructed via `newInsightsResourceSearchCmd(factory)` for
injection-based unit testing; passing `nil` installs the production
factory that wraps `cloud.ResolveContext`.

New apitypes mirror the OpenAPI response schema:
`InsightsResourceSearchParams`, `InsightsResourceSearchResponse`,
`InsightsResourceSearchResult`, `InsightsResourceSearchPagination`,
`InsightsResourceSearchAggregation`. A new
`*client.Client.SearchInsightsResources` method takes the params struct
directly — `go-querystring` handles the URL encoding via struct tags.

## Sample output

Captured by running the renderer against a representative
`InsightsResourceSearchResponse` fixture.

### Default (tab-aligned text)

```
$ pulumi insights resource search --query 'type:aws:s3/bucket:Bucket'
URN                                                    TYPE                  STACK  ACCOUNT   MODIFIED
urn:pulumi:prod::api::aws:s3/bucket:Bucket::my-bucket  aws:s3/bucket:Bucket  prod   prod-aws  2026-05-01T14:30:00Z
aws:s3/bucket:Bucket::other-bucket                     aws:s3/bucket:Bucket  -      prod-aws  -

Showing 2 of 2 resources.
More results available. Re-run with --cursor "next-token" to continue.
```

Rows without a URN (Insights-only records that weren't deployed via
Pulumi) fall back to `<type>::<id>` in the URN column so every row stays
identifiable. Empty columns render as `-` to keep alignment.

Empty result set:

```
$ pulumi insights resource search --query 'type:aws:nonexistent'
No resources found.
```

Last page (no `pagination.next`):

```
$ pulumi insights resource search --query 'type:aws:s3'
URN                                                    TYPE                  STACK  ACCOUNT   MODIFIED
urn:pulumi:prod::api::aws:s3/bucket:Bucket::my-bucket  aws:s3/bucket:Bucket  prod   prod-aws  2026-05-01T14:30:00Z
…
Showing 12 of 12 resources.
```

### `--output json`

```
$ pulumi insights resource search --query 'type:aws:s3/bucket:Bucket' --output json
{
  "total": 2,
  "resources": [
    {
      "account": "prod-aws",
      "custom": true,
      "id": "my-bucket",
      "modified": "2026-05-01T14:30:00Z",
      "project": "api",
      "stack": "prod",
      "type": "aws:s3/bucket:Bucket",
      "urn": "urn:pulumi:prod::api::aws:s3/bucket:Bucket::my-bucket"
    },
    {
      "account": "prod-aws",
      "id": "other-bucket",
      "type": "aws:s3/bucket:Bucket"
    }
  ],
  "pagination": {
    "next": "/api/orgs/acme/search/resourcesv2?query=foo&cursor=next-token&size=2",
    "cursor": "bookmark"
  }
}
```

### Errors

Invalid `--sort` is caught before the API call:

```
$ pulumi insights resource search --sort bogus
error: invalid --sort value "bogus" (allowed: category, created, custom, delete, dependencies, id, managed, modified, module, name, package, parentUrn, project, protected, providerUrn, stack, type, urn)
```

Invalid `--output` is caught before the API call:

```
$ pulumi insights resource search --output yaml
error: invalid --output value "yaml" (must be 'default' or 'json')
```

Server-side errors propagate via the existing API client error path,
e.g. `--properties=true` against an unsupported subscription:

```
$ pulumi insights resource search --properties
error: searching insights resources: [402] Payment Required: …
```

## Test plan

- [x] Added appropriate unit tests - For all changes
- [ ] Added a test in `pkg/engine/lifecycletest` - For all
engine/protocol changes
- [ ] Added a conformance test in `pkg/testing/pulumi-test-language` -
For language protocol changes
- [ ] Added a golden test in `pkg/backend/display` - For changes to the
output renderers

`pkg/cmd/pulumi/insights/insights_resource_search_test.go` covers:
- Default text output, including URN fallback for rows without a URN,
the `-` filler for empty cells, and the pagination-hint that surfaces
the cursor extracted from `pagination.next`
- Empty result set ("No resources found.")
- Last page (no `pagination.next` → no hint)
- JSON output (`assert.Equal` against the fixture)
- Default org vs `--org` override propagation
- Full param propagation (`--query`, `--sort` repeated, `--asc`,
`--page`, `--page-size`, `--cursor`, `--properties`, `--collapse`)
- Invalid `--sort` rejected with a message listing allowed values
- Invalid `--output` rejected before the API call
- Client error propagation (e.g. 402) and factory error propagation (not
logged in)
- Full cobra-level flag binding through
`newInsightsResourceSearchCmd(factory).Execute`
- `newInsightsResourceSearchCmd(nil)` installs the production factory
- `cursorFromNextLink` extracts the cursor from both relative and
absolute URLs, and degrades gracefully when the link is empty or has no
cursor

`pkg/backend/httpstate/client/client_insights_test.go` covers
`SearchInsightsResources` against a `httptest.NewServer`:
- Round-trip of a populated response (including `Custom *bool`,
pagination, etc.)
- Query parameter encoding — confirms `query`, `sort` (repeated), `asc`,
`page`, `size`, `properties`, `collapse` all reach the server
- Zero-valued parameters are omitted (empty query string)
- HTTP error propagation (402 Payment Required)

## Validation

- [x] `make lint` — clean (`golangci-lint run --tests` over the affected
packages reports 0 issues)
- [x] `make test_fast` — relevant package tests pass (`insightscmd`,
`httpstate/client`, plus the broader `./cmd/pulumi/...` sweep)
- [x] `make tidy_fix` — clean (no `go.mod` changes; only existing
in-tree imports)
- [x] `make format` — clean (`gofmt -l` reports no diffs on touched
files)
- [x] Relevant SDK tests pass (if SDK changes) — `sdk/go/common/apitype`
tests pass
- [ ] `make check_proto` — n/a, no proto changes

## Changelog

- [x] Changelog entry added: `cli/cloud: Add \`pulumi insights resource
search\` to search for resources discovered by Pulumi Insights`

## Risk

Strictly additive: new apitypes in `sdk/go/common/apitype/insights.go`,
a new `*client.Client.SearchInsightsResources` method, a new endpoint
registration in `pkg/backend/httpstate/client/api_endpoints.go`, and the
full `pulumi insights resource search` command replacing the previous
stub. The stub was already wired in via `newInsightsResourceCmd` (added
in #23077), so the wiring lines in `pkg/cmd/pulumi/pulumi.go` don't
change.

The `pulumi insights` tree is still marked `[EXPERIMENTAL]` in `--help`
text, matching the get command added in #23077.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
i-am-tom added a commit that referenced this pull request May 14, 2026
Adds the third leaf command under the Cloud-Ready CLI epic for `pulumi
deployment`, closing #22985. The command wraps the `CancelDeployment`
endpoint and follows the same patterns established by `pulumi deployment
list` (#23114), `pulumi insights resource get` (#23077), and
`pulumi insights resource search` (#23087):

- Injection-based client factory (`newDeploymentCancelCmdWith`) so unit
  tests can stub the cloud API and confirmation prompt without touching
  the real backend; passing `nil` installs the production wiring.
- `--output default|json` validated before the API call so a typo
  doesn't burn a request.
- `--yes/-y` skips the destructive-action confirmation prompt; the
  prompt itself reuses `ui.ConfirmPrompt` and gracefully no-ops in
  non-interactive sessions so CI runs aren't blocked.
- New `*client.Client.CancelStackDeployment` method plus endpoint
  registration; tests cover the happy path, 404 propagation, and the
  request URI shape.

The placeholder `newDeploymentCancelCmd` in `deployment_cmds.go` is
removed; the parent `pulumi deployment` command stays hidden until the
rest of the new subcommand tree lands.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

The Cloud-Ready CLI: pulumi insights resource search

3 participants