Início rápido: implemente uma função do Cloud Run com a CLI gcloud

Esta página mostra como implementar uma função HTTP do Cloud Run através da CLI gcloud.

Antes de começar

  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. Install the Google Cloud CLI.

  3. Se estiver a usar um fornecedor de identidade (IdP) externo, tem primeiro de iniciar sessão na CLI gcloud com a sua identidade federada.

  4. Para inicializar a CLI gcloud, execute o seguinte comando:

    gcloud init
  5. Create or select 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 the resourcemanager.projects.create permission. Learn how to grant roles.
    • Create a Google Cloud project:

      gcloud projects create PROJECT_ID

      Replace PROJECT_ID with a name for the Google Cloud project you are creating.

    • Select the Google Cloud project that you created:

      gcloud config set project PROJECT_ID

      Replace PROJECT_ID with your Google Cloud project name.

  6. Se estiver a usar um projeto existente para este guia, verifique se tem as autorizações necessárias para concluir este guia. Se criou um novo projeto, já tem as autorizações necessárias.

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

  8. Enable the Artifact Registry, Cloud Build, Cloud Run Admin API, and Cloud Logging APIs:

    Roles required to enable APIs

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

    gcloud services enable artifactregistry.googleapis.com cloudbuild.googleapis.com run.googleapis.com logging.googleapis.com
  9. Install the Google Cloud CLI.

  10. Se estiver a usar um fornecedor de identidade (IdP) externo, tem primeiro de iniciar sessão na CLI gcloud com a sua identidade federada.

  11. Para inicializar a CLI gcloud, execute o seguinte comando:

    gcloud init
  12. Create or select 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 the resourcemanager.projects.create permission. Learn how to grant roles.
    • Create a Google Cloud project:

      gcloud projects create PROJECT_ID

      Replace PROJECT_ID with a name for the Google Cloud project you are creating.

    • Select the Google Cloud project that you created:

      gcloud config set project PROJECT_ID

      Replace PROJECT_ID with your Google Cloud project name.

  13. Se estiver a usar um projeto existente para este guia, verifique se tem as autorizações necessárias para concluir este guia. Se criou um novo projeto, já tem as autorizações necessárias.

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

  15. Enable the Artifact Registry, Cloud Build, Cloud Run Admin API, and Cloud Logging APIs:

    Roles required to enable APIs

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

    gcloud services enable artifactregistry.googleapis.com cloudbuild.googleapis.com run.googleapis.com logging.googleapis.com
  16. Para definir o projeto predefinido para o seu serviço do Cloud Run:
     gcloud config set project PROJECT_ID
    Substitua PROJECT_ID pelo nome do projeto que criou para este início rápido.
  17. Se estiver ao abrigo de uma política da organização de restrição de domínio que restringe as invocações não autenticadas para o seu projeto, tem de aceder ao serviço implementado conforme descrito em Testar serviços privados.

  18. Reveja os preços do Cloud Run ou estime os custos com a calculadora de preços.
  19. Funções necessárias

    Para obter as autorizações de que precisa para concluir este início rápido, peça ao seu administrador que lhe conceda as seguintes funções de IAM:

    Para mais informações sobre a atribuição de funções, consulte o artigo Faça a gestão do acesso a projetos, pastas e organizações.

    Também pode conseguir as autorizações necessárias através de funções personalizadas ou outras funções predefinidas.

    Conceda à conta de serviço do Cloud Build acesso ao seu projeto

    O Cloud Build usa automaticamente a conta de serviço predefinida do Compute Engine como a conta de serviço predefinida do Cloud Build para compilar o seu código-fonte e recurso do Cloud Run, a menos que substitua este comportamento.

    Para que o Cloud Build compile as suas origens, conceda à conta de serviço do Cloud Build a função Cloud Run Builder (roles/run.builder) no seu projeto:

    gcloud projects add-iam-policy-binding PROJECT_ID \
        --member=serviceAccount:SERVICE_ACCOUNT_EMAIL_ADDRESS \
        --role=roles/run.builder

    Substitua PROJECT_ID pelo ID do seu projeto e Google Cloudpelo endereço de email da conta de serviço do Cloud Build.SERVICE_ACCOUNT_EMAIL_ADDRESS Se estiver a usar a conta de serviço predefinida do Compute Engine como conta de serviço do Cloud Build, use o seguinte formato para o endereço de email da conta de serviço:

    PROJECT_NUMBER-compute@developer.gserviceaccount.com

    Substitua PROJECT_NUMBER pelo seu Google Cloud número do projeto.

    Para ver instruções detalhadas sobre como encontrar o ID e o número do projeto, consulte o artigo Criar e gerir projetos.

    A atribuição da função de criador do Cloud Run demora alguns minutos a propagar-se.

    Escreva a função de exemplo

    Para escrever uma candidatura, siga estes passos:

    Node.js

    1. Crie um novo diretório com o nome helloworld e mude para esse diretório:

         mkdir helloworld
         cd helloworld
      

    2. Crie um ficheiro package.json no diretório helloworld para especificar as dependências do Node.js:

      {
        "name": "nodejs-docs-samples-functions-hello-world-get",
        "version": "0.0.1",
        "private": true,
        "license": "Apache-2.0",
        "author": "Google Inc.",
        "repository": {
          "type": "git",
          "url": "https://github.com/GoogleCloudPlatform/nodejs-docs-samples.git"
        },
        "engines": {
          "node": ">=16.0.0"
        },
        "scripts": {
          "test": "c8 mocha -p -j 2 test/*.test.js --timeout=6000 --exit"
        },
        "dependencies": {
          "@google-cloud/functions-framework": "^3.1.0"
        },
        "devDependencies": {
          "c8": "^10.0.0",
          "gaxios": "^6.0.0",
          "mocha": "^10.0.0",
          "wait-port": "^1.0.4"
        }
      }
      
    3. Crie um ficheiro index.js no diretório helloworld com o seguinte exemplo de Node.js:

      const functions = require('@google-cloud/functions-framework');
      
      // Register an HTTP function with the Functions Framework that will be executed
      // when you make an HTTP request to the deployed function's endpoint.
      functions.http('helloGET', (req, res) => {
        res.send('Hello World!');
      });

    Python

    1. Crie um novo diretório com o nome helloworld e mude para esse diretório:

         mkdir helloworld
         cd helloworld
      

    2. Crie um ficheiro requirements.txt no diretório helloworld para especificar as dependências do Python:

      functions-framework==3.9.2
      flask==3.0.3
      google-cloud-error-reporting==1.11.1
      MarkupSafe==2.1.3
      

      Isto adiciona os pacotes necessários para o exemplo.

    3. Crie um ficheiro main.py no diretório helloworld com o seguinte exemplo de Python:

      import functions_framework
      
      @functions_framework.http
      def hello_get(request):
          """HTTP Cloud Function.
          Args:
              request (flask.Request): The request object.
              <https://flask.palletsprojects.com/en/1.1.x/api/#incoming-request-data>
          Returns:
              The response text, or any set of values that can be turned into a
              Response object using `make_response`
              <https://flask.palletsprojects.com/en/1.1.x/api/#flask.make_response>.
          Note:
              For more information on how Flask integrates with Cloud
              Functions, see the `Writing HTTP functions` page.
              <https://cloud.google.com/functions/docs/writing/http#http_frameworks>
          """
          return "Hello World!"
      
      

    Ir

    1. Crie um novo diretório com o nome helloworld e mude para esse diretório:

         mkdir helloworld
         cd helloworld
      

    2. Crie um ficheiro go.mod para declarar o módulo Go:

      module github.com/GoogleCloudPlatform/golang-samples/functions/functionsv2/helloworld
      
      go 1.24.0
      
      require github.com/GoogleCloudPlatform/functions-framework-go v1.8.1
      
      require (
      	github.com/cloudevents/sdk-go/v2 v2.15.2 // indirect
      	github.com/google/go-cmp v0.6.0 // indirect
      	github.com/google/uuid v1.6.0 // indirect
      	github.com/json-iterator/go v1.1.12 // indirect
      	github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
      	github.com/modern-go/reflect2 v1.0.2 // indirect
      	github.com/stretchr/testify v1.10.0 // indirect
      	go.uber.org/multierr v1.11.0 // indirect
      	go.uber.org/zap v1.27.0 // indirect
      	golang.org/x/time v0.9.0 // indirect
      )
      
    3. Crie um ficheiro hello_http.go no diretório helloworld com o seguinte exemplo de código Go:

      
      // Package helloworld provides a set of Cloud Functions samples.
      package helloworld
      
      import (
      	"fmt"
      	"net/http"
      
      	"github.com/GoogleCloudPlatform/functions-framework-go/functions"
      )
      
      func init() {
      	functions.HTTP("HelloGet", helloGet)
      }
      
      // helloGet is an HTTP Cloud Function.
      func helloGet(w http.ResponseWriter, r *http.Request) {
      	fmt.Fprint(w, "Hello, World!")
      }
      

    Java

    1. Crie um novo diretório com o nome helloworld e mude para esse diretório:

         mkdir helloworld
         cd helloworld
      

    2. Crie a seguinte estrutura de projeto para conter o diretório de origem e o ficheiro de origem:

      mkdir -p ~/helloworld/src/main/java/functions
      touch ~/helloworld/src/main/java/functions/HelloWorld.java
      
    3. Atualize o ficheiro HelloWorld.java com o seguinte exemplo de código Java:

      
      package functions;
      
      import com.google.cloud.functions.HttpFunction;
      import com.google.cloud.functions.HttpRequest;
      import com.google.cloud.functions.HttpResponse;
      import java.io.BufferedWriter;
      import java.io.IOException;
      
      public class HelloWorld implements HttpFunction {
        // Simple function to return "Hello World"
        @Override
        public void service(HttpRequest request, HttpResponse response)
            throws IOException {
          BufferedWriter writer = response.getWriter();
          writer.write("Hello World!");
        }
      }
    4. Crie um ficheiro pom.xml no diretório helloworld e adicione as seguintes dependências Java:

      <?xml version="1.0" encoding="UTF-8"?>
      
      <!--
        Copyright 2020 Google LLC
      
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
      
        http://www.apache.org/licenses/LICENSE-2.0
      
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      -->
      
      <project xmlns="http://maven.apache.org/POM/4.0.0"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
      
        <groupId>com.example.functions</groupId>
        <artifactId>functions-hello-world</artifactId>
        <version>1.0.0-SNAPSHOT</version>
      
        <parent>
          <groupId>com.google.cloud.samples</groupId>
          <artifactId>shared-configuration</artifactId>
          <version>1.2.0</version>
        </parent>
      
        <dependencyManagement>
          <dependencies>
            <dependency>
              <artifactId>libraries-bom</artifactId>
              <groupId>com.google.cloud</groupId>
              <scope>import</scope>
              <type>pom</type>
              <version>26.32.0</version>
            </dependency>
          </dependencies>
        </dependencyManagement>
      
        <properties>
          <maven.compiler.target>11</maven.compiler.target>
          <maven.compiler.source>11</maven.compiler.