Skip to content

Commit c7ddd56

Browse files
i-am-tomclaude
andauthored
cli/cloud: add pulumi insights resource search (#23087)
## 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) <[email protected]>
1 parent 3b02eb9 commit c7ddd56

8 files changed

Lines changed: 1099 additions & 40 deletions

File tree

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
changes:
2+
- type: feat
3+
scope: cli/cloud
4+
description: Add `pulumi insights resource search` to search for resources discovered by Pulumi Insights

‎pkg/backend/httpstate/client/api_endpoints.go‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -137,6 +137,7 @@ func init() {
137137
// APIs for managing Search capabilities
138138
addEndpoint("GET", "/api/orgs/{orgName}/search/resources", "getSearchResources")
139139
addEndpoint("GET", "/api/orgs/{orgName}/search/resources/parse", "getSearchResourcesParse")
140+
addEndpoint("GET", "/api/orgs/{orgName}/search/resourcesv2", "getOrgResourceSearchV2")
140141

141142
// APIs for interacting with the Package Registry
142143
addEndpoint("POST", "/api/registry/packages/{source}/{publisher}/{name}/versions", "publishPackage")

‎pkg/backend/httpstate/client/client.go‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2322,3 +2322,20 @@ func (pc *Client) GetInsightsResource(
23222322
}
23232323
return resp, nil
23242324
}
2325+
2326+
// SearchInsightsResources runs a resource search against the v2 endpoint
2327+
// (`GetOrgResourceSearchV2Query`).
2328+
//
2329+
// Zero-valued fields on params are omitted from the query string so the server
2330+
// can apply its own defaults — see [apitype.InsightsResourceSearchParams] for
2331+
// the per-field semantics.
2332+
func (pc *Client) SearchInsightsResources(
2333+
ctx context.Context, org string, params apitype.InsightsResourceSearchParams,
2334+
) (apitype.InsightsResourceSearchResponse, error) {
2335+
path := fmt.Sprintf("/api/orgs/%s/search/resourcesv2", url.PathEscape(org))
2336+
var resp apitype.InsightsResourceSearchResponse
2337+
if err := pc.restCall(ctx, "GET", path, &params, nil, &resp); err != nil {
2338+
return apitype.InsightsResourceSearchResponse{}, err
2339+
}
2340+
return resp, nil
2341+
}

‎pkg/backend/httpstate/client/client_insights_test.go‎

Lines changed: 126 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ import (
1818
"encoding/json"
1919
"net/http"
2020
"net/http/httptest"
21+
"net/url"
2122
"testing"
2223
"time"
2324

@@ -99,3 +100,128 @@ func TestGetInsightsResource(t *testing.T) {
99100
require.Error(t, err)
100101
})
101102
}
103+
104+
func TestSearchInsightsResources(t *testing.T) {
105+
t.Parallel()
106+
107+
t.Run("returns parsed response", func(t *testing.T) {
108+
t.Parallel()
109+
110+
truthy := true
111+
want := apitype.InsightsResourceSearchResponse{
112+
Total: 2,
113+
Resources: []apitype.InsightsResourceSearchResult{
114+
{
115+
Account: "prod-aws",
116+
Type: "aws:s3/bucket:Bucket",
117+
ID: "my-bucket",
118+
URN: "urn:pulumi:prod::api::aws:s3/bucket:Bucket::my-bucket",
119+
Stack: "prod",
120+
Project: "api",
121+
Modified: "2026-05-01T14:30:00Z",
122+
Managed: "managed",
123+
Custom: &truthy,
124+
},
125+
{
126+
Account: "prod-aws",
127+
Type: "aws:s3/bucket:Bucket",
128+
ID: "other-bucket",
129+
},
130+
},
131+
Pagination: &apitype.InsightsResourceSearchPagination{
132+
Cursor: "bookmark",
133+
Next: "/api/orgs/acme/search/resourcesv2?cursor=next-token",
134+
},
135+
}
136+
137+
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
138+
w.Header().Set("Content-Type", "application/json")
139+
require.NoError(t, json.NewEncoder(w).Encode(want))
140+
}))
141+
defer server.Close()
142+
143+
client := newMockClient(server)
144+
got, err := client.SearchInsightsResources(t.Context(), "acme",
145+
apitype.InsightsResourceSearchParams{Query: "type:aws:s3"})
146+
require.NoError(t, err)
147+
assert.Equal(t, want, got)
148+
})
149+
150+
t.Run("encodes query parameters", func(t *testing.T) {
151+
t.Parallel()
152+
153+
var (
154+
capturedPath string
155+
capturedQuery url.Values
156+
)
157+
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
158+
capturedPath = r.URL.Path
159+
capturedQuery = r.URL.Query()
160+
w.Header().Set("Content-Type", "application/json")
161+
_, _ = w.Write([]byte(`{}`))
162+
}))
163+
defer server.Close()
164+
165+
client := newMockClient(server)
166+
_, err := client.SearchInsightsResources(t.Context(), "acme",
167+
apitype.InsightsResourceSearchParams{
168+
Query: "type:aws:s3",
169+
Sort: []string{"modified", "name"},
170+
Ascending: true,
171+
Page: 2,
172+
Size: 50,
173+
Properties: true,
174+
Collapse: true,
175+
})
176+
require.NoError(t, err)
177+
178+
assert.Equal(t, "/api/orgs/acme/search/resourcesv2", capturedPath)
179+
assert.Equal(t, "type:aws:s3", capturedQuery.Get("query"))
180+
assert.Equal(t, []string{"modified", "name"}, capturedQuery["sort"])
181+
assert.Equal(t, "true", capturedQuery.Get("asc"))
182+
assert.Equal(t, "2", capturedQuery.Get("page"))
183+
assert.Equal(t, "50", capturedQuery.Get("size"))
184+
assert.Equal(t, "true", capturedQuery.Get("properties"))
185+
assert.Equal(t, "true", capturedQuery.Get("collapse"))
186+
})
187+
188+
t.Run("omits zero-valued parameters", func(t *testing.T) {
189+
t.Parallel()
190+
191+
// Default-valued bool/int/string fields must not appear on the wire,
192+
// so the server's defaults take effect.
193+
var capturedQuery url.Values
194+
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
195+
capturedQuery = r.URL.Query()
196+
w.Header().Set("Content-Type", "application/json")
197+
_, _ = w.Write([]byte(`{}`))
198+
}))
199+
defer server.Close()
200+
201+
client := newMockClient(server)
202+
_, err := client.SearchInsightsResources(t.Context(), "acme",
203+
apitype.InsightsResourceSearchParams{})
204+
require.NoError(t, err)
205+
206+
assert.Empty(t, capturedQuery)
207+
})
208+
209+
t.Run("propagates HTTP errors", func(t *testing.T) {
210+
t.Parallel()
211+
212+
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
213+
w.WriteHeader(http.StatusPaymentRequired)
214+
_, _ = w.Write([]byte("subscription required"))
215+
}))
216+
defer server.Close()
217+
218+
client := newMockClient(server)
219+
_, err := client.SearchInsightsResources(t.Context(), "acme",
220+
apitype.InsightsResourceSearchParams{Properties: true})
221+
require.Error(t, err)
222+
// The 402 status code and the server's body message both make it
223+
// through the apitype.ErrorResponse formatter ("[code] message").
224+
assert.Contains(t, err.Error(), "402")
225+
assert.Contains(t, err.Error(), "subscription required")
226+
})
227+
}

‎pkg/cmd/pulumi/insights/insights_resource.go‎

Lines changed: 1 addition & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,6 @@
1515
package insights
1616

1717
import (
18-
"errors"
19-
2018
"github.com/spf13/cobra"
2119

2220
"github.com/pulumi/pulumi/pkg/v3/cmd/pulumi/constrictor"
@@ -34,44 +32,7 @@ func newInsightsResourceCmd() *cobra.Command {
3432
constrictor.AttachArguments(cmd, constrictor.NoArgs)
3533

3634
cmd.AddCommand(newInsightsResourceGetCmd(nil))
37-
cmd.AddCommand(newInsightsResourceSearchCmd())
38-
39-
return cmd
40-
}
41-
42-
// TODO[https://github.com/pulumi/pulumi/issues/22975]: Not yet implemented.
43-
func newInsightsResourceSearchCmd() *cobra.Command {
44-
var (
45-
org string
46-
query string
47-
sort string
48-
page int
49-
size int
50-
cursor string
51-
properties bool
52-
collapse bool
53-
)
54-
55-
cmd := &cobra.Command{
56-
Hidden: true,
57-
Use: "search",
58-
Short: "Search for resources within an organization",
59-
Long: "[EXPERIMENTAL] Search for resources within an organization.",
60-
RunE: func(cmd *cobra.Command, args []string) error {
61-
return errors.New("not yet implemented")
62-
},
63-
}
64-
65-
constrictor.AttachArguments(cmd, constrictor.NoArgs)
66-
67-
cmd.Flags().StringVar(&org, "org", "", "The organization to search within")
68-
cmd.Flags().StringVarP(&query, "query", "q", "", "The query string to filter resources by")
69-
cmd.Flags().StringVar(&sort, "sort", "", "The field to sort results by")
70-
cmd.Flags().IntVar(&page, "page", 0, "The page of results to return (max 10,000 total)")
71-
cmd.Flags().IntVar(&size, "page-size", 0, "The number of results per page")
72-
cmd.Flags().StringVar(&cursor, "cursor", "", "The cursor to continue pagination from (Enterprise only)")
73-
cmd.Flags().BoolVar(&properties, "properties", false, "Include resource input/output values in results")
74-
cmd.Flags().BoolVar(&collapse, "collapse", false, "Consolidate resources that exist in multiple sources")
35+
cmd.AddCommand(newInsightsResourceSearchCmd(nil))
7536

7637
return cmd
7738
}

0 commit comments

Comments
 (0)