Vyacheslav
Vyacheslav

Reputation: 21

How to get google cloud project number programmaticaly?

I want to use Google Secret Manager in my project. To access a saved secret it is necessary to provide a secret name which contains Google project number. It will be convinient to get this number proramatically to form secret name and no to save it in the enviroment variable. I use node.js runtime for my project. I know there is a library google-auth-library which allow to get project id. Is it possible to get project number somehow?

Upvotes: 1

Views: 4092

Answers (4)

Shnatsel
Shnatsel

Reputation: 4209

If you're doing this from outside a Cloud VM, so that the metadata service is not available, you can use the Resource Manager API to convert the project name to project number:

const {ProjectsClient} = require('@google-cloud/resource-manager').v3;
const resourcemanagerClient = new ProjectsClient();

let projectId = 'your-project-id-123'; // TODO: replace with your project ID
const [response] = await resourcemanagerClient.getProject({name: projectId});
let projectNumber = response.name.split('/')[1];

Upvotes: 0

Alex Bubblemaster
Alex Bubblemaster

Reputation: 106

You can send a GET request to the Resource Manager API

https://cloudresourcemanager.googleapis.com/v1/projects/PROJECT_ID?alt=json

Upvotes: 1

al-dann
al-dann

Reputation: 2725

Not sure if the following method can be useful in your case, but I put it here, just in case:

gcloud projects list --filter="$PROJECT_ID" --format="value(PROJECT_NUMBER)"

it should return the project number based on the project identifier (in the PROJECT_ID variable), under assumption, that a user (or a service account) who/which runs that command has relevant permissions.

Upvotes: 0

sethvargo
sethvargo

Reputation: 26997

You can access secrets by project_id or project_number. The following are both valid resource IDs that point to the same secret:

projects/my-project/secrets/my-secret
projects/1234567890/secrets/my-secret

You can get metadata, including project_id and project_number from the metadata service. There are many default values. The ones you're looking for are numeric-project-id and project-id.

Here is an example using curl to access the metadata service. You would run this inside your workload, typically during initial boot:

curl "https://metadata.google.internal/computeMetadata/v1/project/project-id" \
  --header "Metadata-Flavor: Google"

Note: the Metadata-Flavor: Google header is required.

To access these values from Node, you can construct your own http client. Alternatively, you can use the googleapis/gcp-metadata package:

const gcpMetadata = require('gcp-metadata');

async function projectID() {
  const id = await gcpMetadata.project('project-id');
  return id
}

Upvotes: 4

Related Questions