• home
  • about
  • 全ての投稿
  • ソフトウェア・ハードウェアの設定のまとめ
  • 分析関連のまとめ
  • ヘルスケア関連のまとめ
  • 生涯学習関連のまとめ

gcp cloud functions

date: 2022-08-11 excerpt: gcp cloud functionsの使い方

tag: gcpgcloudcloud functions


gcp cloud functionsの使い方

概要

  • python, nodejs, goで関数単位でデプロイできるクラウドサービス
    • pythonで動作させる場合、flaskのrequestに相当する引数を与えることができる
  • デプロイ時に環境変数をセットすることができる
  • ユースケース
    • redisの内容を取得、更新するためのAPIを提供するなど
    • cloud functionsにはサービスアカウントを設定でき、アクセスせキュティを緩和できるので、他のAWSなどと連携するときに窓口として使える

Pythonで使用する場合

  • main.pyと依存が必要ならば、requirements.txtを用意する
  • どのバージョンのpythonで動作させるかを指定できる
from flask import escape
import functions_framework

@functions_framework.http
def hello_http(request):
    request_json = request.get_json(silent=True)
    # getパラメータ
    request_args = request.args
    if request_json and 'name' in request_json:
        name = request_json['name']
    elif request_args and 'name' in request_args:
        name = request_args['name']
    else:
        name = 'World'
    return 'Hello {}!'.format(escape(name))

デプロイ

$ gcloud functions deploy hello_http \
    --runtime python310 \
    --trigger-http \
    --allow-unauthenticated \
    --region=asia-northeast2 \
    --set-env-vars ENV_VAR0=[ENV_VAR0],ENV_VAR1=[ENV_VAR1]

プロパティの確認

$ gcloud functions describe hello_http

テストクエリ

$ curl "https://asia-northeast2-starry-lattice-256603.cloudfunctions.net/hello_http?name=うんち"
Hello うんち!

ローカルでの開発について

functions-frameworkというソフトウェアを使い、ローカルにサーバを立ててテストする

$ functions_framework --target=<function-name>
  • 参考
    • Function Frameworks を使用した関数の実行

設定されたサービスアカウントを使用して、bearer tokenを取得する例

import google.auth
import google.auth.transport.requests

def get_token(request):
    credentials, project = google.auth.default(
      scopes=['https://www.googleapis.com/auth/cloud-platform']
    )
    auth_req = google.auth.transport.requests.Request()
    credentials.refresh(auth_req)
    access_token = credentials.token
    return f'project = {project}, access_token = {access_token}'

参考

  • PythonでHTTP Cloud Functionsの関数を作成してデプロイする
  • Cloud FunctionsからRedisインスタンスへの接続


gcpgcloudcloud functions Share Tweet