gcloud command line inside a Cloud Run service tutorial

In this tutorial, you create an inventory of Cloud Run servicesusing the Google Cloud CLI inside a Cloud Runservice. You can apply what you learn in this tutorial to your existing Cloudoperations scripts or to build a proof-of-concept before usingclient librariesto build a more robust service.

You use the gcloud CLI like any shell script inside a webservice, for example, as shown in theShell quickstart.On Cloud Run, both tools work with Google Cloudservices by automatically authenticating with the Cloud Runservice identity. Any permissions givento the service identity are available to the gcloud CLI.

The gcloud CLI is so broadly capable of information gathering and resourcemanagement across Google Cloud that the challenge of using it within a webservice is minimizing the risk of a caller misusing these capabilities.Without security controls, you could create risk to other services or resourcesrunning in the same project by allowing accidental or intentional maliciousactivity. Examples of these risks include:

  • Enabling the discovery of IP addresses of private virtual machines
  • Enabling access to private data from a database in the same project
  • Enabling deletion of other running services

Several steps in this tutorial show how to impose controls to minimize risks,such as specifying thegcloud command to be run in the code, instead of leavingit open as a user input.

Scripting with the command line tool inside a Cloud Run service issimilar to using the command line locally. The main difference is the additionalrestrictions you should add around the primary script logic.

Objectives

  • Write and build acustom container with aDockerfile
  • Write, build, anddeploy a Cloud Run service
  • Use the gcloud CLI safely in a web service
  • Generate a report of Cloud Run services and save to Cloud Storage

Costs

In this document, you use the following billable components of Google Cloud:

To generate a cost estimate based on your projected usage, use thepricing calculator.

New Google Cloud users might be eligible for afree trial.

Before you begin

  1. Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains theresourcemanager.projects.create permission.Learn how to grant roles.
    Note: If you don't plan to keep the resources that you create in this procedure, create a project instead of selecting an existing project. After you finish these steps, you can delete the project, removing all resources associated with the project.

    Go to project selector

  3. Verify that billing is enabled for your Google Cloud project.

  4. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains theresourcemanager.projects.create permission.Learn how to grant roles.
    Note: If you don't plan to keep the resources that you create in this procedure, create a project instead of selecting an existing project. After you finish these steps, you can delete the project, removing all resources associated with the project.

    Go to project selector

  5. Verify that billing is enabled for your Google Cloud project.

  6. Enable the Artifact Registry, Cloud Build, Cloud Run, and Cloud Storage APIs.

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains theserviceusage.services.enable permission.Learn how to grant roles.

    Enable the APIs

  7. Install and initialize the gcloud CLI.

Required roles

To get the permissions that you need to complete the tutorial, ask your administrator to grant you the following IAM roles on your project:

For more information about granting roles, seeManage access to projects, folders, and organizations.

You might also be able to get the required permissions throughcustom roles or otherpredefined roles.

Note:IAM basic roles might also contain permissions to complete the tutorial. You shouldn't grant basic roles in a production environment, but you can grant them in a development or test environment.

Set up gcloud defaults

To configure gcloud with defaults for your Cloud Run service:

  1. Set your default project:

    gcloudconfigsetprojectPROJECT_ID

    ReplacePROJECT_ID with the name of the project you created forthis tutorial.

  2. Configure gcloud for your chosen region:

    gcloudconfigsetrun/regionREGION

    ReplaceREGION with the supported Cloud Runregionof your choice.

Cloud Run locations

Cloud Run is regional, which means the infrastructure thatruns your Cloud Run services is located in a specific region and ismanaged by Google to be redundantly available acrossall the zones within that region.

Meeting your latency, availability, or durability requirements are primaryfactors for selecting the region where your Cloud Run services are run.You can generally select the region nearest to your users but you should considerthe location of theother Google Cloudproducts that are used by your Cloud Run service.Using Google Cloud products together across multiple locations can affectyour service's latency as well as cost.

Cloud Run is available in the following regions:

Subject toTier 1 pricing

  • asia-east1 (Taiwan)
  • asia-northeast1 (Tokyo)
  • asia-northeast2 (Osaka)
  • asia-south1 (Mumbai, India)
  • asia-southeast3 (Bangkok)
  • europe-north1 (Finland)leaf iconLow CO2
  • europe-north2 (Stockholm)leaf iconLow CO2
  • europe-southwest1 (Madrid)leaf iconLow CO2
  • europe-west1 (Belgium)leaf iconLow CO2
  • europe-west4 (Netherlands)leaf iconLow CO2
  • europe-west8 (Milan)
  • europe-west9 (Paris)leaf iconLow CO2
  • me-west1 (Tel Aviv)
  • northamerica-south1 (Mexico)
  • us-central1 (Iowa)leaf iconLow CO2
  • us-east1 (South Carolina)
  • us-east4 (Northern Virginia)
  • us-east5 (Columbus)
  • us-south1 (Dallas)leaf iconLow CO2
  • us-west1 (Oregon)leaf iconLow CO2

Subject toTier 2 pricing

  • africa-south1 (Johannesburg)
  • asia-east2 (Hong Kong)
  • asia-northeast3 (Seoul, South Korea)
  • asia-southeast1 (Singapore)
  • asia-southeast2 (Jakarta)
  • asia-south2 (Delhi, India)
  • australia-southeast1 (Sydney)
  • australia-southeast2 (Melbourne)
  • europe-central2 (Warsaw, Poland)
  • europe-west10 (Berlin)
  • europe-west12 (Turin)
  • europe-west2 (London, UK)leaf iconLow CO2
  • europe-west3 (Frankfurt, Germany)
  • europe-west6 (Zurich, Switzerland)leaf iconLow CO2
  • me-central1 (Doha)
  • me-central2 (Dammam)
  • northamerica-northeast1 (Montreal)leaf iconLow CO2
  • northamerica-northeast2 (Toronto)leaf iconLow CO2
  • southamerica-east1 (Sao Paulo, Brazil)leaf iconLow CO2
  • southamerica-west1 (Santiago, Chile)leaf iconLow CO2
  • us-west2 (Los Angeles)
  • us-west3 (Salt Lake City)
  • us-west4 (Las Vegas)

If you already created a Cloud Run service, you can view theregion in the Cloud Run dashboard in theGoogle Cloud console.

Retrieving the code sample

To retrieve the code sample for use:

  1. Clone the sample app repository to your local machine:

    gitclonehttps://github.com/GoogleCloudPlatform/cloud-run-samples.git

    Alternatively, you can download the sample as a zip file and extract it.

  2. Change to the directory that contains the Cloud Run samplecode:

    cdcloud-run-samples/gcloud-report/

Review the code

This section includes information about thecode sample you retrieved.

Generate a report and upload it to Cloud Storage

This shell script generates a report of Cloud Run services in thecurrent project and region and uploads the result to Cloud Storage. It listsservices whose name contains the provided stringsearch argument.

The script uses thegcloud run services list command,gcloud advanced format options, andgcloud streaming transfer copy mode.

set-eopipefail# Check for required environment variables.requireEnv(){test"${!1}"||(echo"gcloud-report: '$1' not found">&2 &&exit1)}requireEnvGCLOUD_REPORT_BUCKET# Prepare formatting: Default search term to include all services.search=${1:-'.'}limits='spec.template.spec.containers.resources.limits.flatten("", "", " ")'format='table[box, title="Cloud Run Services"](name,status.url,metadata.annotations.[serving.knative.dev/creator],'${limits}')'# Create a specific object name that will not be overridden in the future.obj="gs://${GCLOUD_REPORT_BUCKET}/report-${search}-$(date+%s).txt"# Write a report containing the service name, service URL, service account or user that# deployed it, and any explicitly configured service "limits" such as CPU or Memory.gcloudrunserviceslist\--format"${format}"\--filter"metadata.name~${search}"|gcloudstoragecp--gzip-in-flight-all-"${obj}"# /dev/stderr is sent to Cloud Logging.echo"gcloud-report: wrote to${obj}">&2echo"Wrote report to${obj}"

This script is safe to run as a service because repeated invocations of itupdate the report without further costly churn. Other scripts using thegcloud CLI can be more costly when invoked repeatedly, such ascreating new Cloud resources or performing expensive tasks. Idempotent scripts,which yield the same result on repeated invocations, are safer to run as aservice.

Invoke the script on HTTP request

This Go code sets up a web service that runs a shell script to generate a report.Since the search query is user input, the code validates it to ensure that itonly contains letters, numbers, or hyphens to prevent malicious commands as input.This set of characters is narrow enough to preventcommand injection attacks.

The web service passes the search parameter as an argument to the shell script.

// Service gcloud-report is a Cloud Run shell-script-as-a-service.packagemainimport("log""net/http""os""os/exec""regexp")funcmain(){http.HandleFunc("/",scriptHandler)// Determine port for HTTP service.port:=os.Getenv("PORT")ifport==""{port="8080"log.Printf("defaulting to port %s",port)}// Start HTTP server.log.Printf("listening on port %s",port)iferr:=http.ListenAndServe(":"+port,nil);err!=nil{log.Fatal(err)}}funcscriptHandler(whttp.ResponseWriter,r*http.Request){search:=r.URL.Query().Get("search")re:=regexp.MustCompile(`^[a-z]+[a-z0-9\-]*$`)if!re.MatchString(search){log.Printf("invalid search criteria %q, using default",search)search="."}cmd:=exec.CommandContext(r.Context(),"/bin/bash","script.sh",search)cmd.Stderr=os.Stderrout,err:=cmd.Output()iferr!=nil{log.Printf("Command.Output: %v",err)http.Error(w,http.StatusText(http.StatusInternalServerError),http.StatusInternalServerError)return}w.Write(out)}
Note: To see how to invoke a command in other languages, review theSystem packages tutorial.The code shown in that tutorial is implemented in Go for fast performanceand short cold starts: the business logic is in the shell script.

Ago.mod file declares the application dependencies in ago module:

modulegithub.com/GoogleCloudPlatform/cloud-run-samples/gcloud-reportgo1.19

Define the container environment

The Dockerfile defines how the environment is put together for the service.It is similar to the Dockerfile from thehelloworld-shell quickstart,except that the final container image is based on thegcloud Google Cloud CLI image. Thisallows your service to usegcloud without custom installation andconfiguration steps for the Google Cloud CLI.

# Use the official golang image to create a binary.# This is based on Debian and sets the GOPATH to /go.# https://hub.docker.com/_/golangFROMgolang:1.20-busterasbuilder# Create and change to the app directory.WORKDIR/app# Retrieve application dependencies.# This allows the container build to reuse cached dependencies.# Expecting to copy go.mod and if present go.sum.COPYgo.*./RUNgomoddownload# Copy local code to the container image.COPYinvoke.go./# Build the binary.RUNgobuild-mod=readonly-v-oserver# Use a gcloud image based on debian:buster-slim for a lean production container.# https://docs.docker.com/develop/develop-images/multistage-build/#use-multi-stage-buildsFROMgcr.io/google.com/cloudsdktool/cloud-sdk:slimWORKDIR/app# Copy the binary to the production image from the builder stage.COPY--from=builder/app/server/app/serverCOPY*.sh/app/RUNchmod+x/app/*.sh# Run the web service on container startup.CMD["/app/server"]

Create an Artifact Registry standard repository

Create an Artifact Registry standard repository to store your container image:

gcloudartifactsrepositoriescreateREPOSITORY\--repository-format=docker\--location=REGION

Replace:

  • REPOSITORY with a unique name for the repository.
  • REGION with the Google Cloud region of the Artifact Registry.

Set up the Cloud Storage bucket

Create a Cloud Storage bucket for uploading reports:

gcloudstoragebucketscreategs://REPORT_ARCHIVE_BUCKET

ReplaceREPORT_ARCHIVE_BUCKET with a globally unique bucket name.

Set up the service identity

In order to limit the privileges that the service has to other infrastructure,you create a service identity and customize the specific IAM permissionsnecessary to do the work.

In this case, the required privileges are permission to read Cloud Runservices and permission to read from and write to the Cloud Storage bucket.

  1. Create a service account:

    gcloudiamservice-accountscreategcloud-report-identity

  2. Grant the service account permission to read Cloud Run services:

    gcloudprojectsadd-iam-policy-bindingPROJECT_ID\--member=serviceAccount:gcloud-report-identity@PROJECT_ID.iam.gserviceaccount.com\--roleroles/run.viewer
  3. Grant the service account permission to read from and write to the Cloud Storage bucket:

    gcloudstoragebucketsadd-iam-policy-bindinggs://REPORT_ARCHIVE_BUCKET\--member=serviceAccount:gcloud-report-identity@PROJECT_ID.iam.gserviceaccount.com\--role=roles/storage.objectUser

The limited access of this customized service identity prevents the service fromaccessing other Google Cloud resources.

Ship the service

Shipping code consists of three steps:

  • Building a container image with Cloud Build
  • Uploading the container image to Artifact Registry
  • Deploying the container image to Cloud Run.

To ship your code:

  1. Build your container and publish on Artifact Registry:

    gcloudbuildssubmit--tagREGION-docker.pkg.dev/PROJECT_ID/REPOSITORY/gcloud-report

    Replace:

    • PROJECT_ID with your Google Cloud project ID
    • REPOSITORY with the name of the Artifact Registry repository.
    • REGION with the Google Cloud region of the Artifact Registry.

    gcloud-report is the name of your service.

    Upon success, a SUCCESS message displays the ID, creation time, and image name.The image is stored in Artifact Registry and can be reused if required.

  2. Run the following command to deploy your service:

    gcloudrundeploygcloud-report\--imageREGION-docker.pkg.dev/PROJECT_ID/REPOSITORY/gcloud-report\--update-env-varsGCLOUD_REPORT_BUCKET=REPORT_ARCHIVE_BUCKET\--service-accountgcloud-report-identity\--no-allow-unauthenticated

    Replace:

    • PROJECT_ID with your Google Cloud project ID.
    • REPOSITORY with the name of the Artifact Registry repository.
    • REGION with the Google Cloud region of the service.

    gcloud-report is part of the container name and the name of the service.The container image is deployed to the service and region(Cloud Run) that you configuredpreviously underSetting up gcloud.

    The--no-allow-unauthenticated flag restricts public access to theservice. By keeping the service private you can rely on Cloud Run'sbuilt-in authentication to block unauthorized requests. For more details aboutauthentication that is based on Identity and Access Management (IAM), seeManaging access using IAM.

    Wait until the deployment is complete. This can take about half a minute.On success, the command line displays the service URL.

  3. If you want to deploy a code update to the service, repeat the previoussteps. Each deployment to a service creates a new revision and automaticallystarts serving traffic when ready.

SeeManaging access using IAM for how to grant Google Cloud users access to invoke this service.Project editors and owners automatically have this access.

Generate a report

To generate a report of Cloud Run services:

  1. Use curl to send an authenticated request:

    curl-H"Authorization: Bearer$(gcloudauthprint-identity-token)"SERVICE_URL

    ReplaceSERVICE_URL with the URL provided by Cloud Run after completing deployment.

    If you created a new project and followed this tutorial, the output will besimilar to:

    Wrotereporttogs://REPORT_ARCHIVE_BUCKET/report-.-DATE.txt

    The. in the filename is the default search argument as mentioned in the source code.

    To use the search feature, add asearch argument to the request:

    curl-H"Authorization: Bearer$(gcloudauthprint-identity-token)"SERVICE_URL?search=gcloud

    This query will return output similar to:

    Wrotereporttogs://REPORT_ARCHIVE_BUCKET/report-gcloud-DATE.txt
  2. Retrieve the file using the gcloud CLI locally:

    gcloudstoragecpgs://REPORT_FILE_NAME.

    The. in the command means the current working directory.

    ReplaceREPORT_FILE_NAME with the Cloud Storage object nameoutput in the previous step.

Open the file to see the report. It should look like this:

Screenshot of the list of Cloud Run services in the project with columns for four service attributes.
The four columns are pulled from the service description. They includeName of the service,URL assigned on first deployment, the initialCreator of the service, and the serviceLimits of maximum CPU and memory.
Success: You created an inventory of Cloud Run servicesusing the Google Cloud CLI inside a Cloud Run service.

Improve robustness for the future

If you intend to further develop this service, consider rewriting in a morerobust programming language and using theCloud Run Admin APIand theCloud Storage client library.

You can examine the API calls being made (and see some authentication details)by adding--log-http to gcloud CLI commands.

Automate this operation

Now that the report of Cloud Run services can be triggered by an HTTPrequest, use automation to generate reports when you need them:

Clean up

To avoid additional charges to your Google Cloud account, delete all the resourcesyou deployed with this tutorial.

Delete the project

If you created a new project for this tutorial, delete the project.If you used an existing project and need to keep it without the changes you addedin this tutorial,delete resources that you created for the tutorial.

The easiest way to eliminate billing is to delete the project that you created for the tutorial.

To delete the project:

    Caution: Deleting a project has the following effects:
    • Everything in the project is deleted. If you used an existing project for the tasks in this document, when you delete it, you also delete any other work you've done in the project.
    • Custom project IDs are lost. When you created this project, you might have created a custom project ID that you want to use in the future. To preserve the URLs that use the project ID, such as anappspot.com URL, delete selected resources inside the project instead of deleting the whole project.

    If you plan to explore multiple architectures, tutorials, or quickstarts, reusing projects can help you avoid exceeding project quota limits.

  1. In the Google Cloud console, go to theManage resources page.

    Go to Manage resources

  2. In the project list, select the project that you want to delete, and then clickDelete.
  3. In the dialog, type the project ID, and then clickShut down to delete the project.

Delete tutorial resources

  1. Delete the Cloud Run service you deployed in this tutorial.Cloud Run services don't incur costs until they receive requests.

    To delete your Cloud Run service, run the following command:

    gcloudrunservicesdeleteSERVICE-NAME

    ReplaceSERVICE-NAME with the name of your service.

    You can also delete Cloud Run services from theGoogle Cloud console.

  2. Remove thegcloud default region configuration you added during tutorialsetup:

    gcloudconfigunsetrun/region
  3. Remove the project configuration:

     gcloud config unset project
  4. Delete other Google Cloud resources created in this tutorial:

What's next

Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2026-02-19 UTC.