Calculate total app memory allocation for Cloud Foundry

Somtimes you want to know how much memory has been allocated by the apps in your Cloud Foundry cluster. The easiest way to do this is by using the cf cli in combination with a utility called jq.

The cf cli curretly does not implement a command to give directly what we want but we can use cf curl to query the Cloud Foundry api directly.

For this blog post we are interested in the memory usage endpoint. Which requires an organization_guid so we first need to retreive those from the organization list endpoint.

Lets start by using jq to parse the output of the organization list and extract the url:

> cf curl /v2/organizations | jq -r '.resources[].metadata.url'
/v2/organizations/65b0afdf-37a1-414f-85fc-4d46a9909534
/v2/organizations/6a9543b0-c4c8-4efa-a185-fb86d88588f1
/v2/organizations/f1f97ef8-ab2a-4604-980f-9a931aaf8817

Then we pass this list to a second cf curl by using xargs:

> cf curl /v2/organizations | jq -r '.resources[].metadata.url' | \
xargs -I %s cf curl %s/memory_usage
{
   "memory_usage_in_mb": 128
}
{
   "memory_usage_in_mb": 2560
}
{
   "memory_usage_in_mb": 13312
}

In the last step we will sum the results by using jq reduce:

> cf curl /v2/organizations | jq -r '.resources[].metadata.url' | \
xargs -I %s cf curl %s/memory_usage | \
jq -s 'reduce .[].memory_usage_in_mb as $item (0; . + $item)'

Spread the word

twitter icon facebook icon linkedin icon