Google Cloudの設定は、もちろんウェブのUIを使って行うことができて、見落としとかもしにくいのでおすすめなのですが、定型的に行うのならばgcloudコマンドを使ってさくっとやりたいものです。ということで、2分で初期設定しちゃいましょ。
プロジェクトの作成と課金の有効化
gcloudコマンドで、とにかくプロジェクト作って課金を有効化。
#!/bin/bash
set -Ceu
config_name="config_name"
project_name="project_name"
account_id="gcloud billing accounts list"
gcloud config configurations create $config_name
gcloud config configurations activate $config_name
gcloud auth login
gcloud projects create $project_name
gcloud config set project $project_name
gcloud billing projects link $project_name --billing-account=$account_id
上の3つの変数を適切に設定する。アカウントIDは、
gcloud billing accounts list
コマンドで調べておく。
続いて必要なサービスを有効化する。
#!/bin/bash
set -Ceu
gcloud services enable run.googleapis.com
gcloud services enable cloudbuild.googleapis.com
gcloud services enable artifactregistry.googleapis.com # Buildpacks がイメージを保存するために必要
gcloud services enable iam.googleapis.com # IAM ポリシー管理に必要
gcloud services enable cloudresourcemanager.googleapis.com # プロジェクト情報取得などに必要
gcloud services enable secretmanager.googleapis.com # GitHub 接続トークン保存に必要
これで初期設定完了。
ソースコードの準備。
今回はPythonで書きますが、他の言語でも似たようなものでしょう。
- Procfile
- requirements.txt
- main.py
たったこれだけ、これが最低限です。
Procfile
# Procfile の例 (main.py 内の 'app' という Flask/WSGI アプリケーションオブジェクトを起動)
web: gunicorn -b :$PORT main:app
requirements.txt
Flask==3.1.0
gunicorn==23.0.0
requests==2.32.3
こちらはたった3つ。バージョンは適当に調べてくださいませ。
main.py
import signal
import sys
from types import FrameType
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello() -> str:
return "Hello, Google Cloud Run! Please enjoy!"
def shutdown_handler(signal_int: int, frame: FrameType) -> None:
# Safely exit program
sys.exit(0)
if __name__ == "__main__":
# Running application locally, outside of a Google Cloud Environment
# handles Ctrl-C termination
signal.signal(signal.SIGINT, shutdown_handler)
app.run(host="localhost", port=8080, debug=True)
else:
# handles Cloud Run container termination
signal.signal(signal.SIGTERM, shutdown_handler)
一応ローカルでもテストしてみましょう。
python -m venv venv
. ./venv/bin/activate
pip install -r requirements.txt
python main.app
ローカルホストでサーバが立ち上がりましたか?立ち上がればこれでOK!
では、デプロイしてみましょ。
#!/bin/bash
set Ceu
service_name=hoge_service
gcloud run deploy $service_name --region=asia-northeast1 --source=.
時間かかりますがそのうち終わります。これで完成!ここから本格的に開発を始めましょう。