在 firebase 函数中创建 Google Cloud Task

ast*_*mme 3 node.js firebase google-cloud-functions google-cloud-tasks

调用尝试创建任务的 firebase HTTP 函数时,我在 firebase 控制台函数日志中收到错误。

错误:7 PERMISSION_DENIED:主体(用户或服务帐户)缺少资源“projects/my-gcloud-project-id/locations/us-central1/queues/myqueuename”(或资源可能不存在)。

也许我对 gcloud id 和位置与 firebase id 和位置之间感到困惑?

编辑:我已通过运行确认我的位置是 us-central1gcloud --project my-gcloud-project-id tasks locations list

或者也许我需要设置权限?

我的代码:



const functions = require('firebase-functions');
const { CloudTasksClient } = require('@google-cloud/tasks')

const projectId = 'my-firebase-project-id';
const location = 'us-central1'
const queue = 'myqueuename'

exports.onFormSubmit = functions.https.onRequest(async (req, res) => {
  const tasksClient = new CloudTasksClient()
  const queuePath = tasksClient.queuePath('my-gcloud-project-id', location, queue);

  const url = `https://google.com/` // edited for stack overflow
  const delaySeconds = 5;
  console.log('delaying for ', delaySeconds, ' seconds');

  const task = {
      httpRequest: {
          httpMethod: 'POST',
          url,
          body: '',
          headers: {
              'Content-Type': 'application/json',
          },
      },
      scheduleTime: {
          seconds: delaySeconds
      }
  }

  const [ response ] = await tasksClient.createTask({ parent: queuePath, task })

  console.log('task name', response.name);
});

Run Code Online (Sandbox Code Playgroud)

Emm*_*uel 7

为了创建 Google 任务,您必须在 IAM 上添加正确的权限,在这种情况下,如错误消息所示,您必须cloudtasks.tasks.create向调用云功能的服务帐户添加权限。

这可以通过进入云控制台然后进入 IAM 来完成,搜索服务帐户通常类似于service-project-number@gcf-admin-robot.iam.gserviceaccount.com更新:它是my-project-id@appspot.gserviceaccount.com)并添加所需的权限,如果您有基于角色的权限Cloud Tasks Enqueuer应该足以创建任务。