Wednesday, November 11, 2020

Distinct Count with JsonAta of the resources in GCP project

 Scenario 

I need to get a quick picture of what resources a GCP project has and how many 

so according to this https://stackoverflow.com/a/60550886/60114 

I do 

gcloud asset search-all-resources --format=json --scope=projects/<GCP-PROJECT-ID>


I get a JSON that is an array of objects like 

```

{

    "additionalAttributes": {},

    "assetType": "compute.googleapis.com/Disk",

    "displayName": "terraform-demo-api",

    "location": "us-central1-c",

    "name": "//compute.googleapis.com/projects/prodeo-kn-demo/zones/us-central1-c/disks/terraform-demo-api",

    "project": "projects/857463209268"

  },

```

that I need to do distinct count by the assetType 


for this the JsonAta https://try.jsonata.org/  proved to be useful


this is the expression 


$merge(
$sort(
$merge(
$map(
$distinct($.assetType),
function($current)
{
{
$current : $count(
$filter(
$.assetType,
function($value, $index,$array){$value= $current}
)
)
}
}
)
)
)
)


output is like that 


{
"iam.googleapis.com/ServiceAccountKey": 8,
"compute.googleapis.com/Instance": 4,
"compute.googleapis.com/Disk": 4,
"compute.googleapis.com/Address": 1,
"compute.googleapis.com/Firewall": 6,
"compute.googleapis.com/InstanceTemplate": 4,
"compute.googleapis.com/Route": 25,
"compute.googleapis.com/Subnetwork": 24,
"compute.googleapis.com/Network": 1,
"cloudresourcemanager.googleapis.com/Project": 1,
"iam.googleapis.com/ServiceAccount": 4,
"appengine.googleapis.com/Application": 1
}

Followers