1. Overview

In the following examples, we’re going to take a look at working with the Cloud Run Admin API Client Library for Java.

You must have created or have access to a project on Cloud Run to be able to follow these steps.

2. Add the dependency to your project

Get the latest version of the library from Maven Central here.

3. Getting Authenticated

With Service Account credentials

Create a Service Account from the Google Cloud Console by clicking on the sidebar and navigating to IAM & AdminService Account. Then click on Create Service Account and fill in the requested details. Your service account should have suitable permissions to be able to manage services on Cloud Run.

After creating the service, click on the three dots next to it, then select Manage KeysAdd KeyCreate new key. Select JSON and save the provided file.

String credentialsFilePath = "/path/to/your/json/credentials/file";
GoogleCredentials credentials = GoogleCredentials.fromStream(new FileInputStream(credentialsFilePath));
CloudRun cloudRun = new CloudRun.Builder(new NetHttpTransport(), new GsonFactory(), new HttpCredentialsAdapter(credentials))

4. Creating a new Service

String projectId = "your-project-id";
Map<String, String> annotations = Map.of("autoscaling.knative.dev/minScale", "0", // Autoscaling: Minimum instances
        "autoscaling.knative.dev/maxScale", "100", // Autoscaling: Maximum instances
        "run.googleapis.com/cpu-throttling", "false");
ObjectMeta meta = new ObjectMeta()
ResourceRequirements resources = new ResourceRequirements().setLimits(Map.of("memory", "2Gi", "cpu", "2")); // 2 GigaBytes of RAM and 2 vCPUs
ContainerPort port = new ContainerPort().setContainerPort(80); // Container port you want to expose
Container container = new Container()
                        .setImage("gcr.io/example/example") // URI of your Docker image on Cloud Registry
ServiceSpec spec = new ServiceSpec();
spec.setTemplate(new RevisionTemplate()
        .setSpec(new RevisionSpec()
                .setTimeoutSeconds((int) config.getInstanceTimeoutDuration().toSeconds())
                .setContainerConcurrency(80) // Maximum concurrent requests per container
Service service = new Service();
Service deployedService = cloudRun.namespaces().services()
        .create("namespaces/" + projectId, service)

5. Deleting an Existing Service

Status status = cloudRun.namespaces().services().delete("namespaces/your-project-id/services/name-of-your-service").execute();

6. Getting a Service

Service service = cloudRun.namespaces().services().get(serviceName).execute();

7. Getting All Available Services

List<Service> services = cloudRun.namespaces().services()

Look at the official documentation to know what more you can do with the Cloud Run Admin API.