在 firebase 函数中创建 Google Cloud Task

creating Google Cloud Task in a firebase function

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

Error: 7 PERMISSION_DENIED: The principal (user or service account) lacks IAM permission "cloudtasks.tasks.create" for the resource "projects/my-gcloud-project-id/locations/us-central1/queues/myqueuename" (or the resource may not exist).

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

编辑:我已通过 运行 gcloud --project my-gcloud-project-id tasks locations list

确认我的位置是 us-central1

或者我可能需要设置权限?

我的代码:



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);
});

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

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