Skip to content

Commit

Permalink
Add ancestors column to gcp_project table (#664)
Browse files Browse the repository at this point in the history
  • Loading branch information
pdecat authored Oct 4, 2024
1 parent e5a6651 commit 39b16ae
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 1 deletion.
25 changes: 24 additions & 1 deletion docs/tables/gcp_project.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,4 +55,27 @@ select
access_approval_settings
from
gcp_project;
```
```

### Get parent and organization ID for all projects
Get the parent resource and organization ID across your various projects.

```sql+postgres
select
project_id,
parent ->> 'id' as parent_id,
parent ->> 'type' as parent_type,
case when jsonb_array_length(ancestors) > 1 then ancestors -> -1 -> 'resourceId' ->> 'id' else null end as organization_id
from
gcp_project;
```

```sql+sqlite
select
project_id,
parent ->> 'id' as parent_id,
parent ->> 'type' as parent_type,
case when json_array_length(ancestors) > 1 then ancestors -> -1 -> 'resourceId' ->> 'id' else null end as organization_id
from
gcp_project;
```
33 changes: 33 additions & 0 deletions gcp/table_gcp_project.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,13 @@ func tableGcpProject(_ context.Context) *plugin.Table {
Hydrate: getProjectAccessApprovalSettings,
Transform: transform.FromValue(),
},
{
Name: "ancestors",
Description: "The ancestors of the project in the resource hierarchy, from bottom to top.",
Type: proto.ColumnType_JSON,
Hydrate: getProjectAncestors,
Transform: transform.FromValue(),
},

// Steampipe standard columns
{
Expand Down Expand Up @@ -162,6 +169,32 @@ func getProjectAccessApprovalSettings(ctx context.Context, d *plugin.QueryData,
return resp, nil
}

func getProjectAncestors(ctx context.Context, d *plugin.QueryData, h *plugin.HydrateData) (interface{}, error) {
// Create Service Connection
service, err := CloudResourceManagerService(ctx, d)
if err != nil {
plugin.Logger(ctx).Error("gcp_project.getProjectAncestors", "connection_error", err)
return nil, err
}

// Get project details
projectId, err := getProject(ctx, d, h)
if err != nil {
return nil, err
}
project := projectId.(string)

resp, err := service.Projects.GetAncestry(project, &cloudresourcemanager.GetAncestryRequest{}).Do()
if err != nil {
if strings.Contains(err.Error(), "404") {
return nil, nil
}
plugin.Logger(ctx).Error("gcp_project.getProjectAncestors", "api_err", err)
return nil, err
}
return resp.Ancestor, nil
}

func projectSelfLink(_ context.Context, d *transform.TransformData) (interface{}, error) {
data := d.HydrateItem.(*cloudresourcemanager.Project)
selfLink := "https://cloudresourcemanager.googleapis.com/v1/projects/" + data.Name
Expand Down

0 comments on commit 39b16ae

Please sign in to comment.