LoginSignup
11
8

More than 5 years have passed since last update.

Google Cloud Functions(Python)からCloud Buildでビルド実行してみる

Last updated at Posted at 2018-10-02

概要

Google Cloud Next ’18で発表されたCI/CDサービスのGoogle Cloud Buildですが、現状、トリガーは以下のgitリポジトリへのpushのみとなります。(2018/10/01時点)

  • Cloud Source Repositories
  • Bitbucket
  • GitHub

ソースとしてCloud Storageにある圧縮ファイル(zip、tar.gz)を指定することができるので、Cloud Storageとも連携できるよね?と思ったので試してみました。

Google Cloud Buildについては以下をご参考ください。

Google Cloud Build
https://cloud.google.com/cloud-build/?hl=ja

Google Cloud Buildとは一体何者なのか
https://swet.dena.com/entry/2018/08/20/170836

実装

Cloud Functionsにビルドするソースは以下のような感じです。

Google API Clientが利用できるようにrequirements.txt に含めておきます。

requirements.txt
google-api-python-client

Cloud Build APIでビルドリクエストの送信をする場合、JSONまたはYAML形式でパラメータを設定する必要があります。今回はJSON形式を利用しています。

詳しくは下記をご参考ください。

REST Resource: projects.builds
https://cloud.google.com/cloud-build/docs/api/reference/rest/v1/projects.builds

今回はJSON形式で、source.storageSource でCloud Storageから読み込むソースを指定して、steps で、ls -l を指定して、ソースが解凍されて展開されたかを確認しています。

PythonのCloud Build API Clientについては下記ページからドキュメントやAPIのお試しができるAPIs Explorerへのリンクが用意されていました。

Cloud Build API Client Library for Python
https://developers.google.com/api-client-library/python/apis/cloudbuild/v1

main.py
from googleapiclient import discovery
import json

def cloud_build_create_test(event, context):
  requestBody = '''
{
  "source": {
    "storageSource": {
      "bucket": "任意のバケット名",
      "object": "任意のファイル名(zip か tar.gz)"
    }
  },
  "steps": [
    {
      "name": "gcr.io/cloud-builders/docker",
      "entrypoint": "bash",
      "args": [
        "-c",
        "ls -l"
      ]
    }
  ]
}
  '''

  cloudBuild = discovery.build('cloudbuild', 'v1')
  request = cloudBuild.projects().builds().create(
    body=json.load(requestBody), projectId='[GCPのプロジェクトID]')
  response = request.execute()

とりあえず、API叩けば、Cloud Build実行できることが確認できました。
ちょっとしたバッチ処理なんかであれば、Cloud Buildを利用するのもありかもしれません。

参考

Google Cloud Build
https://cloud.google.com/cloud-build/?hl=ja

Google Cloud Buildとは一体何者なのか
https://swet.dena.com/entry/2018/08/20/170836

REST Resource: projects.builds
https://cloud.google.com/cloud-build/docs/api/reference/rest/v1/projects.builds

Cloud Build API Client Library for Python
https://developers.google.com/api-client-library/python/apis/cloudbuild/v1

11
8
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
11
8