Gcloud command line get default project_id
Google Cloud-PlatformGcloudGcloud CliGoogle Cloud-Platform Problem Overview
I'm looking for a one-liner to get the default project id
with gcloud config list core/project
give me
Your active configuration is: [default]
[core]
project = myproject_id
While I want to have only myproject_id. The goal is to use the result in a script.
Google Cloud-Platform Solutions
Solution 1 - Google Cloud-Platform
The easiest way to do this is to use the --format
flag with gcloud
:
gcloud config list --format 'value(core.project)' 2>/dev/null
The --format
flag is available on all commands and gives you full control over what is printed, and how it is formatted.
You can see this help page for full info:
gcloud topic formats
Solution 2 - Google Cloud-Platform
Thanks to comment from Tim Swast above, I was able to use:
export PROJECT_ID=$(gcloud config get-value project)
to get the project ID. Running the get-value
command prints the following:
gcloud config get-value project
#=>
Your active configuration is: [default]
$PROJECT_ID
You can also run:
gcloud config get-value project 2> /dev/null
to just print $PROJECT_ID
and suppress other warnings/errors.
Solution 3 - Google Cloud-Platform
With Google Cloud SDK 266.0.0 you can use following command:
gcloud config get-value project
Solution 4 - Google Cloud-Platform
Not exactly the gcloud command you specified, but will return you the currently configured project:
gcloud info |tr -d '[]' | awk '/project:/ {print $2}'
Works for account, zone and region as well.
Solution 5 - Google Cloud-Platform
From Cloud Shell or any machine where Cloud SDK is installed, we can use:
echo $DEVSHELL_PROJECT_ID
And as shown in the below screenshot.
I got a question about how to set the environment variable $DEVSHELL_PROJECT_ID; here are the steps:
- If the URL has the variable
project
and is set to some project id, then the environment variable $DEVSHELL_PROJECT_ID usually will be set to the project id. - If the variable
project
is not set in the URL, we can choose the project from the Combobox (besides the titleGoogle Cloud Platform
) which will set the variableproject
in the URL. We may need to restart the Cloud Shell or refresh the entire web page to set the environment variable $DEVSHELL_PROJECT_ID. - Otherwise, if the environment variable $DEVSHELL_PROJECT_ID is not set, we can set it by the command shown below where we replace PROJECT_ID with the actual project id.
gcloud config set project PROJECT_ID
- All these are shown in the below figure.
Solution 6 - Google Cloud-Platform
Direct and easy way to get the default $PROJECT_ID
is answered above.
In case you would like to get $PROJECT_ID
from the info
command, here is a way to do it:
gcloud info --format=flattened | awk '/config.project/ {print $2}'
or:
gcloud info --format=json | jq '.config.project' | tr -d '"'
Just run:
gcloud info --format={flattened|json}
to see the output, then use awk
, jq
or similar tools to grab what you need.