Creator of this small website
Jun 2, 2020 1 min read

Easy import of user defined metrics in GCP

thumbnail for this post

It’s super easy and fast to create metrics in the GCP console, especially in the rush of debugging. Unfortunately, if you want them to be available in another project (let’s say you have foo-dev and foo-prod projects) for later use then you have to recreate them. And for this you want them to be in your IaC repository.

But that’s quite a grunt work, and if you have many, then it’s even more error prone. Since I’ve been facing this I will share how I do this :)

Warning : this is NOT a pretty way (hello the string of pipes) to do it but a quick and dirty one, just to illustrate the method. It can easily be refined and enhanced

#!/usr/bin/env bash

for m in $(gcloud logging metrics list --format="value(name)")
  resource_name=$(echo $m | sed 's/\//_/g' | tr -s [A-Z] [a-z])
  echo -n resource \"google_logging_metric\" \"${resource_name}\"\ 
  gcloud logging metrics describe $m --format json | jq 'del(.createTime, .updateTime, .metricDescriptor.type,, .metricDescriptor.description)' | perl -pe 's/([a-z0-9])([A-Z])/$1_\L$2/g' | perl -pe 's/\"(.*)\":/$1 =/g' | sed s/,$//g | perl -pe 's/= {/{/g'

Send the output to a .tf file and you will be able to terraform apply it as-is