前回書いた「【Cloud Functions】Functions Framework for Rubyを試す(ローカルからデプロイ編) 」の続きで、今回はGitHub Actionsからデプロイしてみる
手順 🔗
サービスアカウントの作成 🔗
以下URLからサービスアカウント作成し、「Cloud Functions 開発者」のロールを付与する https://console.cloud.google.com/projectselector2/iam-admin/serviceaccounts/create
サービスアカウントキーをダウンロードして、そのJSONをGitHub Secretsに「GCP_SA_KEY」というキー名で登録する
ワークフローファイルの作成 🔗
$ mkdir .github/workflows
$ vim .github/workflows/deploy.yml
copy
mainブランチにプッシュもしくはマージされたらデプロイが走る設定
name: Deploy
on:
push:
branches: [ main ]
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: google-github-actions/deploy-cloud-functions@main
with:
credentials: ${{ secrets.GCP_SA_KEY }}
name: hello
runtime: ruby27
copy
動作確認 🔗
デプロイができているかわかるようにコードを書き換えておく
require "functions_framework"
FunctionsFramework.http("hello") do |request|
- "Hello, world!\n"
+ "Hello, world! (Deploy from GitHub Actions)\n"
end
copy
プッシュしたあと、ghコマンドで実行中のワークフローを確認する
$ git push
$ gh run watch
Refreshing run status every 3 seconds. Press Ctrl+C to quit.
✓ main Deploy · 1246588184
Triggered via push about 20 hours ago
JOBS
✓ deploy in 1m6s (ID 3640768767)
✓ Set up job
✓ Run actions/checkout@v2
✓ Run google-github-actions/deploy-cloud-functions@main
✓ Post Run actions/checkout@v2
✓ Complete job
✓ Run Deploy (1246588184) completed with 'success'
copy
curlで叩いてデプロイができているか確認する
$ curl https://us-central1-masamune-287217.cloudfunctions.net/hello
Hello, world! (Deploy from GitHub Actions)
copy
いい感じ
補足 🔗
IAM権限エラー 🔗
1回目のデプロイでは問題なかったが、2回目でエラーが出るようになった
[Missing necessary permission iam.serviceAccounts.actAs for on the service account PROJECT_ID@appspot.gserviceaccount.com.
Ensure that service account PROJECT_ID@appspot.gserviceaccount.com is a member of the project PROJECT_ID, and then grant the roles/iam.serviceAccountUser role.
You can do that by running 'gcloud iam service-accounts add-iam-policy-binding PROJECT_ID@appspot.gserviceaccount.com --member=$member --role=roles/iam.serviceAccountUser'
In case the member is a service account please use the prefix 'serviceAccount:' instead of 'user:'.]
copy
以下のようなコマンドで解決
$ gcloud iam service-accounts add-iam-policy-binding PROJECT_ID@appspot.gserviceaccount.com \
--member='serviceAccount:deploy-account@PROJECT_ID.iam.gserviceaccount.com' \
--role=roles/iam.serviceAccountUser
copy
リポジトリ 🔗
今回やった内容のリポジトリ
https://github.com/ytkg/sample-functions-framework-ruby