Crear y desplegar una función de Cloud Run HTTP con Ruby (1.ª gen.)

En esta guía se explica cómo escribir una función de Cloud Run con el entorno de ejecución de Ruby. Hay dos tipos de funciones de Cloud Run:

  • Una función HTTP, que se invoca desde solicitudes HTTP estándar.
  • Una función basada en eventos que se usa para gestionar eventos de tu infraestructura de Cloud, como mensajes de un tema de Pub/Sub o cambios en un segmento de Cloud Storage.

En el ejemplo se muestra cómo crear una función HTTP sencilla.

Antes de empezar

  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 (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

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

  4. Enable the Cloud Functions and Cloud Build 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.

    Enable the APIs

  5. 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 (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

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

  7. Enable the Cloud Functions and Cloud Build 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.

    Enable the APIs

  8. Instala e inicializa gcloud CLI.
  9. Actualiza e instala los componentes de gcloud:
    gcloud components update
  10. Prepara tu entorno de desarrollo.

    Ir a la guía de configuración de Ruby

  11. Crear una función

    1. Crea un directorio en tu sistema local para el código de la función:

      Linux o Mac OS X

      mkdir ~/helloworld
      cd ~/helloworld
      

      Windows

      mkdir %HOMEPATH%\helloworld
      cd %HOMEPATH%\helloworld
      
    2. Crea un archivo app.rb en el directorio helloworld con el siguiente contenido:

      require "functions_framework"
      require "cgi"
      require "json"
      
      FunctionsFramework.http "hello_http" do |request|
        # The request parameter is a Rack::Request object.
        # See https://www.rubydoc.info/gems/rack/Rack/Request
        name = request.params["name"] ||
               (request.body.rewind && JSON.parse(request.body.read)["name"] rescue nil) ||
               "World"
        # 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 #{CGI.escape_html name}!"
      end

      Esta función de ejemplo toma un nombre proporcionado en la solicitud HTTP y devuelve un saludo o "Hello World!" si no se proporciona ningún nombre.

      .

    Especificar dependencias

    Las dependencias de Ruby se gestionan con bundler y se expresan en un archivo llamado Gemfile.

    Cuando despliegas tu función, Cloud Run Functions descarga e instala las dependencias declaradas en Gemfile y Gemfile.lock mediante bundler.

    El archivo Gemfile muestra los paquetes que necesita tu función, así como las restricciones de versión opcionales. En el caso de una función de Cloud Run, uno de estos paquetes debe ser la gem functions_framework.

    Para este ejercicio, crea un archivo llamado Gemfile en el mismo directorio que el archivo app.rb que contiene el código de tu función. El archivo Gemfile debe tener el siguiente contenido:

    source "https://rubygems.org"
    
    gem "functions_framework", "~> 0.7"
    

    Ejecuta el siguiente comando para instalar la gema functions_framework y otras dependencias:

    bundle install
    

    Compilar y probar de forma local

    Antes de desplegar la función, puedes compilarla y probarla de forma local. Ejecuta el siguiente comando para usar el archivo ejecutable functions-framework-ruby y iniciar un servidor web local que ejecute tu función hello_http:

    bundle exec functions-framework-ruby --target hello_http
    # ...starts the web server in the foreground
    

    Si la función se compila correctamente, se mostrará la URL que puedes visitar en tu navegador web para ver la función en acción: http://localhost:8080/. Debería aparecer un mensaje Hello World!.

    También puedes enviar solicitudes a esta función mediante curl desde otra ventana de terminal:

    curl localhost:8080
    # Output: Hello World!
    

    Consulta Probar funciones en la documentación del framework de funciones de Ruby.

    Desplegar la función

    Para desplegar la función con un activador HTTP, ejecuta el siguiente comando en el directorio helloworld:

    gcloud functions deploy hello_http --no-gen2 --runtime ruby33 --trigger-http --allow-unauthenticated
    

    La marca --allow-unauthenticated te permite acceder a la función sin autenticación. Para requerir autenticación, omite la marca.

    Probar la función implementada

    1. Cuando la función termine de implementarse, anota la propiedad httpsTrigger.url o búscala con el siguiente comando:

      gcloud functions describe hello_http
      

      Debería tener este aspecto:

      https://GCP_REGION-PROJECT_ID.cloudfunctions.net/hello_http
    2. Visita esta URL en tu navegador. Debería aparecer el mensaje "Hello World!".

      Prueba a enviar un nombre en la solicitud HTTP. Por ejemplo, puedes usar la siguiente URL:

      https://GCP_REGION-PROJECT_ID.cloudfunctions.net/hello_http?name=NAME

      Debería aparecer el mensaje "Hola NAME".

    Ver registros

    Puedes ver los registros de las funciones de Cloud Run en la interfaz de usuario de Cloud Logging o mediante la CLI de Google Cloud.

    Ver registros con la herramienta de línea de comandos

    Para ver los registros de tu función con gcloud CLI, usa el comando logs read, seguido del nombre de la función:

    gcloud functions logs read hello_http

    La salida debería ser similar a la siguiente:

    LEVEL  NAME       EXECUTION_ID  TIME_UTC                 LOG
    D      helloHttp  rvb9j0axfclb  2019-09-18 22:06:25.983  Function execution started
    D      helloHttp  rvb9j0axfclb  2019-09-18 22:06:26.001  Function execution took 19 ms, finished with status code: 200

    Ver registros en el panel de control de Logging

    También puedes ver los registros de las funciones de Cloud Run desde la Google Cloud consola.