Google Cloud CLI を使用して Cloud Functions(第 1 世代)を作成する

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

始める前に

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

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

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

  4. Cloud Functions and Cloud Build API を有効にします。

    API を有効にする

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

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

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

  7. Cloud Functions and Cloud Build API を有効にします。

    API を有効にする

  8. gcloud CLI をインストールして初期化します
  9. gcloud コンポーネントを更新します。
    gcloud components update
  10. コマンド プロンプトが必要な場合は、Google Cloud Shell を使用できます。Google Cloud Shell は、Google Cloud CLI がすでに含まれているコマンドライン環境であるため、インストールする必要はありません(Google Cloud CLI は、Google Compute Engine の仮想マシンにもプリインストールされています)。

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

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

  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/

    Python

    cd python-docs-samples/functions/helloworld/

    Go

    cd golang-samples/functions/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"
    )
    
    // 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 トリガーを使用して関数をデプロイするには、関数を含むディレクトリで次のコマンドを実行します。

Node.js

gcloud functions deploy helloGET \
--runtime nodejs20 --trigger-http

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

Python

gcloud functions deploy hello_get \
--runtime python312 --trigger-http

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

Go

gcloud functions deploy HelloGet \
--runtime go121 --trigger-http

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

Java

gcloud functions deploy java-helloworld \
--entry-point functions.HelloWorld \
--runtime java17 \
--memory 512MB --trigger-http

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

C#

gcloud functions deploy csharp-helloworld \
--entry-point HelloWorld.Function \
--runtime dotnet6 --trigger-http

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

Ruby

gcloud functions deploy hello_get --runtime ruby32 --trigger-http

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

PHP

 gcloud functions deploy helloGet --runtime php82 --trigger-http

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

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

関数をテストする

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

    Node.js

    gcloud functions describe helloGET

    Python

    gcloud functions describe hello_get

    Go

    gcloud functions describe HelloGet

    Java

    gcloud functions describe java-helloworld

    C#

    gcloud functions describe csharp-helloworld

    Ruby

    gcloud functions describe hello_get

    PHP

    gcloud functions describe helloGet

    次のようになります。

    Node.js

    https://GCP_REGION-PROJECT_ID.cloudfunctions.net/helloGET

    Python

    https://GCP_REGION-PROJECT_ID.cloudfunctions.net/hello_get

    Go

    https://GCP_REGION-PROJECT_ID.cloudfunctions.net/HelloGet

    Java

    https://GCP_REGION-PROJECT_ID.cloudfunctions.net/java-helloworld

    C#

    https://GCP_REGION-PROJECT_ID.cloudfunctions.net/csharp-helloworld

    Ruby

    https://GCP_REGION-PROJECT_ID.cloudfunctions.net/hello_get

    PHP

    https://GCP_REGION-PROJECT_ID.cloudfunctions.net/helloGet

  2. ブラウザで、この URL にアクセスします。Hello World! というメッセージが表示されます。

関数を削除する

関数を削除するには、次のコマンドを実行します。

Node.js

gcloud functions delete helloGET 

Python

gcloud functions delete hello_get 

Go

gcloud functions delete HelloGet 

Java

gcloud functions delete java-helloworld 

C#

gcloud functions delete csharp-helloworld 

Ruby

gcloud functions delete hello_get 

PHP

gcloud functions delete helloGet 

次のステップ

ご使用のランタイムに関連する開発環境の設定、新しい関数の作成、依存関係の指定、関数のデプロイ、関数のテスト、ログの表示の方法については、次の「最初の関数」ガイドをご覧ください。これらのガイドは Cloud Functions(第 1 世代)専用です。