且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何通过身份验证从 Cloud Scheduler 调用 Cloud Function

更新时间:2023-12-05 19:47:46

这些是您必须采取的确切步骤.确保不要跳过第二步,它会设置服务帐户的调用者权限,以便调度程序能够使用该服务帐户的 OIDC 信息调用 HTTP 云函数.注意:为简单起见,我在这里选择默认服务帐户,但是,为此目的创建一个具有较少权限的单独服务帐户是明智的.

These are the exact steps you have to take. Be sure not to skip the second step, it sets invoker permissions on the service account so that the scheduler is able to invoke the HTTP Cloud Function with that service account's OIDC information. Note: for simplicity, I choose the default service account here, however, it would be wise to create a separate service account for this purpose with less privileges.

# Create cloud function
gcloud functions deploy my_function 
  --entry-point=my_entrypoint 
  --runtime=python37 
  --trigger-http 
  --region=europe-west1 
  --project=${PROJECT_ID}

# Set invoke permissions
gcloud functions add-iam-policy-binding my_function 
  --region=europe-west1 
  --member=serviceAccount:${PROJECT_ID}@appspot.gserviceaccount.com 
  --role="roles/cloudfunctions.invoker" 
  --project=${PROJECT_ID}

# Deploy scheduler
gcloud scheduler jobs create http my_job 
  --schedule="every 60 minutes" 
  --uri="https://europe-west1-${PROJECT_ID}.cloudfunctions.net/my_function/" 
  --http-method=POST 
  --oidc-service-account-email="${PROJECT_ID}@appspot.gserviceaccount.com" 
  --oidc-token-audience="https://europe-west1-${PROJECT_ID}.cloudfunctions.net/my_function" 
  --project=${PROJECT_ID}