Google Cloud CLI を使用して Cloud Functions を作成する

このページでは、Google Cloud CLI を使用し、Cloud Functions(第 2 世代)を作成してデプロイする方法について説明します。

始める前に

  1. Google Cloud アカウントにログインします。Google Cloud を初めて使用する場合は、アカウントを作成して、実際のシナリオでの Google プロダクトのパフォーマンスを評価してください。新規のお客様には、ワークロードの実行、テスト、デプロイができる無料クレジット $300 分を差し上げます。
  2. Google Cloud Console の [プロジェクト セレクタ] ページで、Google Cloud プロジェクトを選択または作成します。

    プロジェクト セレクタに移動

  3. Google Cloud プロジェクトで課金が有効になっていることを確認します

  4. Cloud Functions, Cloud Build, Artifact Registry, Cloud Run, and Logging API を有効にします。

    API を有効にする

  5. Google Cloud CLI をインストールします。
  6. gcloud CLI を初期化するには:

    gcloud init
  7. Google Cloud Console の [プロジェクト セレクタ] ページで、Google Cloud プロジェクトを選択または作成します。

    プロジェクト セレクタに移動

  8. Google Cloud プロジェクトで課金が有効になっていることを確認します

  9. Cloud Functions, Cloud Build, Artifact Registry, Cloud Run, and Logging API を有効にします。

    API を有効にする

  10. Google Cloud CLI をインストールします。
  11. gcloud CLI を初期化するには:

    gcloud init
  12. コマンド プロンプトが必要な場合は、Google Cloud Shell を使用できます。Google Cloud Shell は、Google Cloud CLI がすでに含まれているコマンドライン環境であるため、インストールする必要はありません(Google Cloud CLI は、Google Compute Engine の仮想マシンにもプリインストールされています)。

  13. 開発環境を準備します。

サンプルコードを取得する

  1. ローカルマシンにサンプル リポジトリのクローンを作成します。

    Node.js

    git clone https://github.com/GoogleCloudPlatform/nodejs-docs-samples.git

    また、zip 形式のサンプルをダウンロードしてファイルを抽出してもかまいません。

    Python

    git clone https://github.com/GoogleCloudPlatform/python-docs-samples.git

    また、zip 形式のサンプルをダウンロードしてファイルを抽出してもかまいません。

    Go

    git clone https://github.com/GoogleCloudPlatform/golang-samples.git

    また、zip 形式のサンプルをダウンロードしてファイルを抽出してもかまいません。

    Java

    git clone https://github.com/GoogleCloudPlatform/java-docs-samples.git

    また、zip 形式のサンプルをダウンロードしてファイルを抽出してもかまいません。

    C#

    git clone https://github.com/GoogleCloudPlatform/dotnet-docs-samples.git

    また、zip 形式のサンプルをダウンロードしてファイルを抽出してもかまいません。

    Ruby

    git clone https://github.com/GoogleCloudPlatform/ruby-docs-samples.git

    また、zip 形式のサンプルをダウンロードし、ファイルを抽出してもかまいません。

    PHP

    git clone https://github.com/GoogleCloudPlatform/php-docs-samples.git

    または、zip 形式のサンプルをダウンロードし、ファイルを抽出してもかまいません。

  2. Cloud Functions のサンプルコードが含まれているディレクトリに移動します。

    Node.js

    cd nodejs-docs-samples/functions/helloworld/helloworldGet/

    Python

    cd python-docs-samples/functions/helloworld/

    Go

    cd golang-samples/functions/functionsv2/helloworld/

    Java

    cd java-docs-samples/functions/helloworld/helloworld/

    C#

    cd dotnet-docs-samples/functions/helloworld/HelloWorld/

    Ruby

    cd ruby-docs-samples/functions/helloworld/get/

    PHP

    cd php-docs-samples/functions/helloworld_get/

  3. サンプルコードを見てみましょう。

    Node.js

    const functions = require('@google-cloud/functions-framework');
    
    // Register an HTTP function with the Functions Framework that will be executed
    // when you make an HTTP request to the deployed function's endpoint.
    functions.http('helloGET', (req, res) => {
      res.send('Hello World!');
    });

    Python

    import functions_framework
    @functions_framework.http
    def hello_get(request):
        """HTTP Cloud Function.
        Args:
            request (flask.Request): The request object.
            <https://flask.palletsprojects.com/en/1.1.x/api/#incoming-request-data>
        Returns:
            The response text, or any set of values that can be turned into a
            Response object using `make_response`
            <https://flask.palletsprojects.com/en/1.1.x/api/#flask.make_response>.
        Note:
            For more information on how Flask integrates with Cloud
            Functions, see the `Writing HTTP functions` page.
            <https://cloud.google.com/functions/docs/writing/http#http_frameworks>
        """
        return "Hello World!"
    
    

    Go

    
    // Package helloworld provides a set of Cloud Functions samples.
    package helloworld
    
    import (
    	"fmt"
    	"net/http"
    
    	"github.com/GoogleCloudPlatform/functions-framework-go/functions"
    )
    
    func init() {
    	functions.HTTP("HelloGet", helloGet)
    }
    
    // helloGet is an HTTP Cloud Function.
    func helloGet(w http.ResponseWriter, r *http.Request) {
    	fmt.Fprint(w, "Hello, World!")
    }
    

    Java

    
    package functions;
    
    import com.google.cloud.functions.HttpFunction;
    import com.google.cloud.functions.HttpRequest;
    import com.google.cloud.functions.HttpResponse;
    import java.io.BufferedWriter;
    import java.io.IOException;
    
    public class HelloWorld implements HttpFunction {
      // Simple function to return "Hello World"
      @Override
      public void service(HttpRequest request, HttpResponse response)
          throws IOException {
        BufferedWriter writer = response.getWriter();
        writer.write("Hello World!");
      }
    }

    C#

    using Google.Cloud.Functions.Framework;
    using Microsoft.AspNetCore.Http;
    using System.Threading.Tasks;
    
    namespace HelloWorld;
    
    public class Function : IHttpFunction
    {
        public async Task HandleAsync(HttpContext context)
        {
            await context.Response.WriteAsync("Hello World!");
        }
    }

    Ruby

    require "functions_framework"
    
    FunctionsFramework.http "hello_get" do |_request|
      # The request parameter is a Rack::Request object.
      # See https://www.rubydoc.info/gems/rack/Rack/Request
    
      # Return the response body as a string.
      # You can also return a Rack::Response object, a Rack response array, or
      # a hash which will be JSON-encoded into a response.
      "Hello World!"
    end

    PHP

    
    use Psr\Http\Message\ServerRequestInterface;
    
    function helloGet(ServerRequestInterface $request): string
    {
        return 'Hello, World!' . PHP_EOL;
    }
    

関数のデプロイ

HTTP トリガーを使用して関数をデプロイするには、サンプルコード(Java の場合は pom.xml ファイル)を含むディレクトリで次のコマンドを実行します。

Node.js

gcloud functions deploy nodejs-http-function \
--gen2 \
--runtime=nodejs20 \
--region=REGION \
--source=. \
--entry-point=helloGET \
--trigger-http

サポートされている Node.js バージョンのランタイム ID を指定して関数を実行するには、--runtime フラグを使用します。

Python

gcloud functions deploy python-http-function \
--gen2 \
--runtime=python312 \
--region=REGION \
--source=. \
--entry-point=hello_get \
--trigger-http

サポートされている Python バージョンのランタイム ID を指定して関数を実行するには、--runtime フラグを使用します。

Go

gcloud functions deploy go-http-function \
--gen2 \
--runtime=go121 \
--region=REGION \
--source=. \
--entry-point=HelloGet \
--trigger-http

サポートされている Go バージョンのランタイム ID を指定して関数を実行するには、--runtime フラグを使用します。

Java

gcloud functions deploy java-http-function \
--gen2 \
--runtime=java17 \
--region=REGION \
--source=. \
--entry-point=functions.HelloWorld \
--memory=512MB \
--trigger-http

サポートされている Java バージョンのランタイム ID を指定して関数を実行するには、--runtime フラグを使用します。

C#

gcloud functions deploy csharp-http-function \
--gen2 \
--runtime=dotnet6 \
--region=REGION \
--source=. \
--entry-point=HelloWorld.Function \
--trigger-http

サポートされている .NET バージョンのランタイム ID を指定して関数を実行するには、--runtime フラグを使用します。

Ruby

gcloud functions deploy ruby-http-function \
--gen2 \
--runtime=ruby32 \
--region=REGION \
--source=. \
--entry-point=hello_get \
--trigger-http

サポートされている Ruby バージョンのランタイム ID を指定して関数を実行するには、--runtime フラグを使用します。

PHP

gcloud functions deploy php-http-function \
--gen2 \
--runtime=php82 \
--region=REGION \
--source=. \
--entry-point=helloGet \
--trigger-http

サポートされている PHP バージョンのランタイム ID を指定して関数を実行するには、--runtime フラグを使用します。

必要なら --allow-unauthenticated フラグを使用し、認証なしで関数にアクセスできます。これはテストに便利ですが、公開 API やウェブサイトを作成する場合を除き、本番環境でこの設定を使用することはおすすめしません。また、会社のポリシーの設定によっては、これは機能しない可能性があります。認証が必要な関数を呼び出す方法については、呼び出しの認証をご覧ください。

リージョン

第 2 世代の関数をデプロイする場合は、リージョンを指定する必要があります。利用可能なリージョンの一覧については、ロケーションをご覧ください。gcloud CLI 構成にはデフォルトのリージョンが関連付けられていますが、deploy コマンドでサポートされている任意のリージョンを使用できます。

gcloud CLI の構成に関連付けられているデフォルトのリージョンを確認するには、次のコマンドを実行します。

gcloud config list

デフォルト リージョンは、次の手順で変更できます。

gcloud config set functions/region REGION

関数をデフォルトのリージョンにデプロイする場合でも、deploy コマンドラインにリージョンを含める必要があります。

関数のトリガー

  1. 関数がデプロイされたら、uri プロパティをメモするか、次のコマンドを使用して検索します。

    Node.js

    gcloud functions describe nodejs-http-function --gen2 --region REGION --format="value(serviceConfig.uri)"

    Python

    gcloud functions describe python-http-function --gen2 --region REGION --format="value(serviceConfig.uri)"

    Go

    gcloud functions describe go-http-function --gen2 --region REGION --format="value(serviceConfig.uri)"

    Java

    gcloud functions describe java-http-function --gen2 --region REGION --format="value(serviceConfig.uri)"

    C#

    gcloud functions describe csharp-http-function --gen2 --region REGION --format="value(serviceConfig.uri)"

    Ruby

    gcloud functions describe ruby-http-function --gen2 --region REGION --format="value(serviceConfig.uri)"

    PHP

    gcloud functions describe php-http-function --gen2 --region REGION --format="value(serviceConfig.uri)"

  2. 独自の URI を使用するように次のコマンドを編集して実行すると、Hello World! メッセージが表示されます。

    curl -m 70 -X POST URI \
        -H "Authorization: Bearer $(gcloud auth print-identity-token)" \
        -H "Content-Type: application/json" \
        -d '{}'
    

Cloud Functions の削除

このチュートリアルで作成した Cloud Functions の関数を削除するには、次のコマンドを実行します。

Node.js

gcloud functions delete nodejs-http-function --gen2 --region REGION 

Python

gcloud functions delete python-http-function --gen2 --region REGION 

Go

gcloud functions delete go-http-function --gen2 --region REGION 

Java

gcloud functions delete java-http-function --gen2 --region REGION 

C#

gcloud functions delete csharp-http-function --gen2 --region REGION 

Ruby

gcloud functions delete ruby-http-function --gen2 --region REGION 

PHP

gcloud functions delete php-http-function --gen2 --region REGION 

Google Cloud コンソールから Cloud Functions を削除することもできます。

次のステップ