0

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.

  • Google Resource Manager API is enabled.
  • Service account has the role=owner permission.
imran shoukat
  • 1,059
  • 2
  • 8
  • 16
  • Is this user part of an organization and you are creating this project in the organization? If NO then you must create the project in the Google Cloud Console. IAM members that are not part of an organization cannot create projects using the CLI or API. – John Hanley Oct 22 '19 at 12:55
  • Yes the user is part of an organization and yes, I am creating the project in the organization. – imran shoukat Oct 23 '19 at 04:00

1 Answers1

1

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

Ernesto U
  • 786
  • 3
  • 14
  • Yes, the user have the Project Owner permission. Also, I have given SA role=owner under the project SA is created. Do I need to give SA role under the organization as well? – imran shoukat Oct 23 '19 at 04:04
  • Granting the resource manage > project creator permission solved the problem. Thanks! – imran shoukat Oct 23 '19 at 09:02