はなちるのマイノート

Unityをメインとした技術ブログ。自分らしくまったりやっていきたいと思いますー!

【C#】.NETでGoogle Cloud Functionsを作成してデプロイをする方法メモ

はじめに

今回はGoogle Cloud Functions.NETを利用した関数をデプロイする方法について書きたいと思います。

内容的には以下の公式ドキュメントをミックスした感じです。
cloud.google.com
cloud.google.com
codelabs.developers.google.com

先に書いておくと、備忘録的な内容なので、公式ドキュメントを読んでいただいたほうが良いと思います。

セットアップ

Google Cloudにアカウントがない方は作っていただき、Google Cloud Consoleにアクセスします。

Google Cloud Console

Cloud Shellを起動する

まずはクラウドで実行されるコマンドライン環境であるCloud Shellを用いて利用するサービスの有効化したいと思います。

起動するにはGoogle Cloud Consoleの右上にあるターミナルのようなボタンを押します。

クラウドシェルの起動
起動したCloud Shell

利用サービスの有効化

今回は以下のサービスを有効化します。

cloud.google.com

$ gcloud services enable \
    artifactregistry.googleapis.com \
    cloudbuild.googleapis.com \
    cloudfunctions.googleapis.com \
    logging.googleapis.com \
    run.googleapis.com
Operation "operations----------" finished successfully.

Google Cloud SDKをインストールして初期化する

Google Cloud Shellを利用していましたが、ローカルで作業を行いたい場合はGoogle Cloud SDKをインストールします。
Windowsの場合はGoogle Cloud CLIインストーラをダウンロードしてそのまま従えばOKです。そのほかOSの場合は公式ドキュメントを参照してください。
gcloud CLI をインストールする  |  Google Cloud CLI のドキュメント

インストールが完了できたら立ち上げ、ログインとプロジェクトの選択を行ってください。

// 一部抜粋
You are logged in as: [---------].

Pick cloud project to use:
 [1] -----------
 [2] Enter a project ID
 [3] Create a new project
Please enter numeric choice or text value (must exactly match list item):  1

Your current project has been set to: [-------------].

無事に設定ができたかの確認もかねて、以下のコマンドを打ち込んでコンポーネント(個別にインストール可能な Google Cloud CLI の構成要素)の更新を行ってみましょう。

$ gcloud components update
To help improve the quality of this product, we collect anonymized usage data and anonymized stacktraces when crashes
are encountered; additional information is available at <https://cloud.google.com/sdk/usage-statistics>. This data is
handled in accordance with our privacy policy <https://cloud.google.com/terms/cloud-privacy-notice>. You may choose to
opt in this collection now (by choosing 'Y' at the below prompt), or at any time in the future by running the following
command:

    gcloud config set disable_usage_reporting false

Do you want to opt-in (y/N)?  y

Beginning update. This process may take several minutes.

All components are up to date.

ローカルでプロジェクトを作成する

以下の構成でファイルを生成します。

HelloWorld
 |-- Function.cs
 |-- HelloWorld.csproj
// Function.cs
using System.Threading.Tasks;
using Google.Cloud.Functions.Framework;
using Microsoft.AspNetCore.Http;

namespace HelloWorld
{
    public class Function : IHttpFunction
    {
        public async Task HandleAsync(HttpContext context)
        {
            await context.Response.WriteAsync("Hello, World!!");
        }
    }
}
// HelloWorld.csproj
<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net8.0</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Google.Cloud.Functions.Hosting" Version="2.1.0" />
        <PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
  </ItemGroup>
</Project>

特筆すべきことはGoogle.Cloud.Functions.Hostingへの依存を追加するくらいです。あとはIHttpFunctionを実装するだけで下準備はOKです。めちゃ簡単ですね。

詳細は以下のドキュメントを読んでみるとよいと思います。
HTTP 関数を作成する  |  Google Cloud Functions に関するドキュメント

ローカルでビルドしてみる

以下のコマンドを実行することで、localhostで立ち上げることができます。

$ dotnet run

コマンドを打った結果に表示されているhttp://localhostへのURLにアクセスすると、Hello, World!!と表示されているはずです。

localhostでの表示

関数をデプロイする

関数をデプロイするために先ほど作成したFunctions.csHelloWorld.csprojが含まれるディレクトリにGoogle Cloud SDK Shell上で移動し、以下のコマンドを打ち込みます。

$ gcloud functions deploy csharp-http-function --gen2 --entry-point=HelloWorld.Function  --runtime=dotnet8 --region=asia-northeast1 --source=. --trigger-http --allow-unauthenticated
  • csharp-http-function : 関数が Google Cloud コンソールで識別される登録名
  • --entry-point : 関数のエントリーポイントの完全修飾クラス名
  • --runtime : .NETのバージョン
  • --region : 関数をデプロイするGoogle Cloudリージョンの名前
  • --trigger-http : 関数が HTTP トリガーを使用することを指定
  • --allow-unauthenticated : 認証なしで関数にアクセス可能にする

無事に成功するとurl : というテキストが書かれているのですが、そこにアクセスするとlocalhostと同様の効果が得られます。

デプロイした関数をテストする

コマンドライン出力のURLを忘れてしまっても、次のコマンドを使用して取得できます。

$ gcloud functions describe csharp-http-function --region=asia-northeast1
....
url: https://-------------