3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

シェルスクリプトでBigQueryからデータ取得

Posted at

シェルスクリプトでBigQueryからデータ取得(bqコマンドの活用)
(サンプルはGCP課金を取得するクエリ)

前提

gcloudアカウント認証済み(gcloud auth login)の環境。

シェルスクリプト

countGCPbilling.sh
#!/bin/bash
# GCP課金の集計

# 1時間前に出力されたGCP課金を集計(export_timeがUTCなので、JST時差9時間+1時間の10時間をマイナス)
YMDH=`date -d '10 hour ago' "+%Y-%m-%d %H"`
bqSQL="select project.id as project_id, replace(service.description, \" \", \"-\") as descript, round(sum(cost), 2) as total_cost from \`project-id.billing.gcp_billing_export_v1_XXXXXX_XXXXXX_XXXXXX\` where cost>0 and export_time between timestamp('${YMDH}:00:00') and timestamp('${YMDH}:59:59') group by project_id, descript order by project_id, descript"
echo "bqSQL=$bqSQL"
# bqコマンドで、BigQuery実行
bqResult=(`bq query -n 15000 --format=csv --use_legacy_sql=false "$bqSQL"`)
echo ""

# 集計結果の出力
i=1
while [ "$i" -lt "${#bqResult[*]}" ]
do
	j="${bqResult[$i]}"
	k=${j//,/ }
	m=(${k})
	# ここを改造してSlackに投げたり、prometheusでデータ取得できるようにしたり等用途は色々
	echo "count_gcp_billing_1hour:${m[0]} ${m[1]}=${m[2]}"
	
	i=`expr $i + 1`
done

参考情報

https://cloud.google.com/billing/docs/how-to/export-data-bigquery
https://cloud.google.com/bigquery/docs/reference/bq-cli-reference?hl=ja#bq_query

3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?