Crea una función de Cloud Functions mediante Google Cloud CLI

En esta página, se muestra cómo crear y, luego, implementar una función de Cloud Functions de 2ª gen. con Google Cloud CLI.

Antes de comenzar

  1. Accede a tu cuenta de Google Cloud. Si eres nuevo en Google Cloud, crea una cuenta para evaluar el rendimiento de nuestros productos en situaciones reales. Los clientes nuevos también obtienen $300 en créditos gratuitos para ejecutar, probar y, además, implementar cargas de trabajo.
  2. En la página del selector de proyectos de la consola de Google Cloud, selecciona o crea un proyecto de Google Cloud.

    Ir al selector de proyectos

  3. Asegúrate de que la facturación esté habilitada para tu proyecto de Google Cloud.

  4. Habilita las API de Cloud Functions, Cloud Build, Artifact Registry, Cloud Run, and Logging.

    Habilita las API

  5. Instala Google Cloud CLI.
  6. Para inicializar la CLI de gcloud, ejecuta el siguiente comando:

    gcloud init
  7. En la página del selector de proyectos de la consola de Google Cloud, selecciona o crea un proyecto de Google Cloud.

    Ir al selector de proyectos

  8. Asegúrate de que la facturación esté habilitada para tu proyecto de Google Cloud.

  9. Habilita las API de Cloud Functions, Cloud Build, Artifact Registry, Cloud Run, and Logging.

    Habilita las API

  10. Instala Google Cloud CLI.
  11. Para inicializar la CLI de gcloud, ejecuta el siguiente comando:

    gcloud init
  12. ¿Necesitas un símbolo del sistema? Puedes usar Google Cloud Shell. Google Cloud Shell es un entorno de línea de comandos que ya incluye Google Cloud CLI, por lo que no es necesario que lo instales. Google Cloud CLI también viene preinstalado en las máquinas virtuales de Google Compute Engine.

  13. Prepara tu entorno de desarrollo.

Obtenga el código de muestra

  1. Clona el repositorio de muestra en tu máquina local:

    Node.js

    git clone https://github.com/GoogleCloudPlatform/nodejs-docs-samples.git

    De manera opcional, puedes descargar la muestra como un archivo zip y extraerla.

    Python

    git clone https://github.com/GoogleCloudPlatform/python-docs-samples.git

    De manera opcional, puedes descargar la muestra como un archivo zip y extraerla.

    Go

    git clone https://github.com/GoogleCloudPlatform/golang-samples.git

    De manera opcional, puedes descargar la muestra como un archivo ZIP y extraerla.

    Java

    git clone https://github.com/GoogleCloudPlatform/java-docs-samples.git

    De manera opcional, puedes descargar la muestra como un archivo ZIP y extraerla.

    C#

    git clone https://github.com/GoogleCloudPlatform/dotnet-docs-samples.git

    De manera opcional, puedes descargar la muestra como un archivo ZIP y extraerla.

    Ruby

    git clone https://github.com/GoogleCloudPlatform/ruby-docs-samples.git

    De manera opcional, puedes descargar la muestra como un archivo ZIP y extraerla.

    PHP

    git clone https://github.com/GoogleCloudPlatform/php-docs-samples.git

    De manera opcional, puedes descargar la muestra como un archivo ZIP y extraerla.

  2. Ve al directorio que contiene el código de muestra de Cloud Functions, como sigue:

    Node.js

    cd nodejs-docs-samples/functions/helloworld/helloworldGet/

    Python

    cd python-docs-samples/functions/helloworld/

    Go

    cd golang-samples/functions/functionsv2/helloworld/

    Java

    cd java-docs-samples/functions/helloworld/helloworld/

    C#

    cd dotnet-docs-samples/functions/helloworld/HelloWorld/

    Ruby

    cd ruby-docs-samples/functions/helloworld/get/

    PHP

    cd php-docs-samples/functions/helloworld_get/

  3. Ve el código de muestra:

    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

    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!"
    
    

    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

    
    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!");
      }
    }

    C#

    using Google.Cloud.Functions.Framework;
    using Microsoft.AspNetCore.Http;
    using System.Threading.Tasks;
    
    namespace HelloWorld;
    
    public class Function : IHttpFunction
    {
        public async Task HandleAsync(HttpContext context)
        {
            await context.Response.WriteAsync("Hello World!");
        }
    }

    Ruby

    require "functions_framework"
    
    FunctionsFramework.http "hello_get" do |_request|
      # The request parameter is a Rack::Request object.
      # See https://www.rubydoc.info/gems/rack/Rack/Request
    
      # Return the response body as a string.
      # You can also return a Rack::Response object, a Rack response array, or
      # a hash which will be JSON-encoded into a response.
      "Hello World!"
    end

    PHP

    
    use Psr\Http\Message\ServerRequestInterface;
    
    function helloGet(ServerRequestInterface $request): string
    {
        return 'Hello, World!' . PHP_EOL;
    }
    

Implementa la función

Para implementar la función con un activador de HTTP, ejecuta el siguiente comando en el directorio que contiene el código de muestra (o, en el caso de Java, el archivo pom.xml):

Node.js

gcloud functions deploy nodejs-http-function \
--gen2 \
--runtime=nodejs20 \
--region=REGION \
--source=. \
--entry-point=helloGET \
--trigger-http

Usa la marca --runtime para especificar el ID del entorno de ejecución de una versión compatible de Node.js para ejecutar la función.

Python

gcloud functions deploy python-http-function \
--gen2 \
--runtime=python312 \
--region=REGION \
--source=. \
--entry-point=hello_get \
--trigger-http

Usa la marca --runtime para especificar el ID de entorno de ejecución de una versión de Python compatible para ejecutar la función.

Go

gcloud functions deploy go-http-function \
--gen2 \
--runtime=go121 \
--region=REGION \
--source=. \
--entry-point=HelloGet \
--trigger-http

Usa la marca --runtime para especificar el ID de entorno de ejecución de una versión de Go compatible para ejecutar tu función.

Java

gcloud functions deploy java-http-function \
--gen2 \
--runtime=java17 \
--region=REGION \
--source=. \
--entry-point=functions.HelloWorld \
--memory=512MB \
--trigger-http

Usa la marca --runtime para especificar el ID del entorno de ejecución de una versión de Java compatible para ejecutar tu función.

C#

gcloud functions deploy csharp-http-function \
--gen2 \
--runtime=dotnet6 \
--region=REGION \
--source=. \
--entry-point=HelloWorld.Function \
--trigger-http

Usa la marca --runtime para especificar el ID del entorno de ejecución de una versión .NET compatible para ejecutar tu función.

Ruby

gcloud functions deploy ruby-http-function \
--gen2 \
--runtime=ruby32 \
--region=REGION \
--source=. \
--entry-point=hello_get \
--trigger-http

Usa la marca --runtime para especificar el ID de entorno de ejecución de una versión de Ruby compatible para ejecutar tu función.

PHP

gcloud functions deploy php-http-function \
--gen2 \
--runtime=php82 \
--region=REGION \
--source=. \
--entry-point=helloGet \
--trigger-http

Usa la marca --runtime para especificar el ID del entorno de ejecución de una versión de PHP compatible para ejecutar la función.

De forma opcional, puedes usar la marca --allow-unauthenticated para acceder a la función sin autenticación. Esto es útil para realizar pruebas, pero no recomendamos usar esta configuración en producción, a menos que crees una API o un sitio web públicos. Además, es posible que no funcione para ti, según la configuración de la política corporativa. Consulta Autentica para la invocación para obtener detalles sobre cómo invocar una función que requiere autenticación.

Regiones

Debes proporcionar una región cuando implementes una función de 2ª gen.. Consulta Ubicaciones para ver una lista de regiones disponibles. La configuración de gcloud CLI tiene una región predeterminada asociada, pero puedes usar la región compatible que quieras en el comando deploy.

Para ver la región predeterminada asociada a la configuración de tu gcloud CLI, ejecuta lo siguiente:

gcloud config list

Puedes cambiar la región predeterminada de la siguiente manera:

gcloud config set functions/region REGION

Ten en cuenta que, incluso si implementas tu función en tu región predeterminada, debes incluir la región en la línea de comandos de deploy.

Activa la función

  1. Cuando la función se termine de implementar, toma nota de la propiedad uri o búscala con el siguiente comando:

    Node.js

    gcloud functions describe nodejs-http-function --gen2 --region REGION --format="value(serviceConfig.uri)"

    Python

    gcloud functions describe python-http-function --gen2 --region REGION --format="value(serviceConfig.uri)"

    Go

    gcloud functions describe go-http-function --gen2 --region REGION --format="value(serviceConfig.uri)"

    Java

    gcloud functions describe java-http-function --gen2 --region REGION --format="value(serviceConfig.uri)"

    C#

    gcloud functions describe csharp-http-function --gen2 --region REGION --format="value(serviceConfig.uri)"

    Ruby

    gcloud functions describe ruby-http-function --gen2 --region REGION --format="value(serviceConfig.uri)"

    PHP

    gcloud functions describe php-http-function --gen2 --region REGION --format="value(serviceConfig.uri)"

  2. Después de editar el siguiente comando para usar tu propio URI, ejecútalo para ver un mensaje Hello World!:

    curl -m 70 -X POST URI \
        -H "Authorization: Bearer $(gcloud auth print-identity-token)" \
        -H "Content-Type: application/json" \
        -d '{}'
    

Borra la función de Cloud Functions

Para borrar la función de Cloud Functions que creaste en este instructivo, ejecuta el siguiente comando:

Node.js

gcloud functions delete nodejs-http-function --gen2 --region REGION 

Python

gcloud functions delete python-http-function --gen2 --region REGION 

Go

gcloud functions delete go-http-function --gen2 --region REGION 

Java

gcloud functions delete java-http-function --gen2 --region REGION 

C#

gcloud functions delete csharp-http-function --gen2 --region REGION 

Ruby

gcloud functions delete ruby-http-function --gen2 --region REGION 

PHP

gcloud functions delete php-http-function --gen2 --region REGION 

También puedes borrar funciones de Cloud Functions en la consola de Google Cloud.

¿Qué sigue?