node.jsgoogle-cloud-platformgoogle-auth-librarygoogle-auth-library-nodejs

Error: User is not authorized while creating GCP project using service account


I am trying to create GCP project programmatically using Google API. Here is the sample code:

const {JWT} = require('google-auth-library')

async function main (keyFile = {PATH_TO_CREDENTIAL_FILE}) {
  const keys = require(keyFile)
  const client = new JWT({
    email: keys.client_email,
    key: keys.private_key,
    scopes: ['https://www.googleapis.com/auth/cloud-platform']
  })
  const url = 'https://cloudresourcemanager.googleapis.com/v1beta1/projects/'
  const data = {
    projectId: 'my-first-project',
    name: 'My First Project',
    parent: {
      type: 'organization',
      id: {ORGANIZATION_ID}
    }
  }
  const res = await client.request({
    url,
    method: 'POST',
    data: JSON.stringify(data)
  })
  console.log('project Info:')
  console.log(res.data)

  const tokenInfo = await client.getTokenInfo(client.credentials.access_token)
  console.log('tokenInfo', tokenInfo)
}

const args = process.argv.slice(2)
main(...args).catch(console.error)

After running this code I am getting the following error:

UnhandledPromiseRejectionWarning: Error: User is not authorized.

Can anyone help me why I am getting this error? And how can I fix this?

P.S.


Solution

  • You are creating a project within an organization. Does the user have the Project Creator role in the organization?

    When the organization is created, all users in your domain are automatically granted Project Creator and Billing Account Creator IAM roles at the organization level. This enables users in your domain to continue creating projects with no disruption.

    The Organization Administrator will decide when they want to start actively using the organization. They can then change the default permissions and enforce more restrictive policies as needed

    Also if you are authenticating using a service account (SA) then the SA needs to have the role