Membuat Cloud Function menggunakan Google Cloud CLI

Halaman ini menampilkan cara membuat dan men-deploy Cloud Function generasi ke-2 menggunakan Google Cloud CLI.

Sebelum memulai

  1. Login ke akun Google Cloud Anda. Jika Anda baru menggunakan Google Cloud, buat akun untuk mengevaluasi performa produk kami dalam skenario dunia nyata. Pelanggan baru juga mendapatkan kredit gratis senilai $300 untuk menjalankan, menguji, dan men-deploy workload.
  2. Di konsol Google Cloud, pada halaman pemilih project, pilih atau buat project Google Cloud.

    Buka pemilih project

  3. Pastikan penagihan telah diaktifkan untuk project Google Cloud Anda.

  4. Enable the Cloud Functions, Cloud Build, Artifact Registry, Cloud Run, and Logging APIs.

    Enable the APIs

  5. Menginstal Google Cloud CLI.
  6. Untuk initialize gcloud CLI, jalankan perintah berikut:

    gcloud init
  7. Di konsol Google Cloud, pada halaman pemilih project, pilih atau buat project Google Cloud.

    Buka pemilih project

  8. Pastikan penagihan telah diaktifkan untuk project Google Cloud Anda.

  9. Enable the Cloud Functions, Cloud Build, Artifact Registry, Cloud Run, and Logging APIs.

    Enable the APIs

  10. Menginstal Google Cloud CLI.
  11. Untuk initialize gcloud CLI, jalankan perintah berikut:

    gcloud init
  12. Perlu command prompt? Anda dapat menggunakan Google Cloud Shell. Google Cloud Shell adalah lingkungan command line yang sudah menyertakan Google Cloud CLI, sehingga Anda tidak perlu menginstalnya. Google Cloud CLI juga sudah terinstal di Virtual Machine Google Compute Engine.

  13. Menyiapkan lingkungan pengembangan.

Mendapatkan kode sampel

  1. Clone repositori contoh ke komputer lokal Anda:

    Node.js

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

    Atau, Anda dapat mendownload contoh sebagai file ZIP dan mengekstraknya.

    Python

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

    Atau, Anda dapat mendownload contoh sebagai file ZIP dan mengekstraknya.

    Go

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

    Atau, Anda dapat mendownload contoh sebagai file ZIP dan mengekstraknya.

    Java

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

    Atau, Anda dapat mendownload contoh sebagai file ZIP dan mengekstraknya.

    C#

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

    Atau, Anda dapat mendownload contoh sebagai file ZIP dan mengekstraknya.

    Ruby

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

    Atau, Anda dapat mendownload contoh sebagai file ZIP dan mengekstraknya.

    PHP

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

    Atau, Anda dapat mendownload contoh sebagai file ZIP dan mengekstraknya.

  2. Ubah ke direktori yang memuat kode contoh Cloud Functions:

    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. Lihat kode contoh:

    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;
    }
    

Men-deploy fungsi

Untuk men-deploy fungsi dengan pemicu HTTP, jalankan perintah berikut di direktori yang berisi kode contoh (atau untuk Java, file pom.xml):

Node.js

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

Gunakan flag --runtime untuk menentukan ID runtime dari versi Node.js yang didukung untuk menjalankan fungsi Anda.

Python

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

Gunakan flag --runtime untuk menentukan ID runtime versi Python yang didukung untuk menjalankan fungsi Anda.

Go

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

Gunakan flag --runtime untuk menentukan ID runtime versi Go yang didukung untuk menjalankan fungsi Anda.

Java

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

Gunakan flag --runtime untuk menentukan ID runtime versi Java yang didukung guna menjalankan fungsi Anda.

C#

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

Gunakan flag --runtime untuk menentukan ID runtime versi .NET yang didukung guna menjalankan fungsi Anda.

Ruby

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

Gunakan flag --runtime untuk menentukan ID runtime versi Ruby yang didukung untuk menjalankan fungsi Anda.

PHP

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

Gunakan tanda --runtime untuk menentukan ID runtime versi PHP yang didukung untuk menjalankan fungsi Anda.

Secara opsional, Anda dapat menggunakan flag --allow-unauthenticated untuk menjangkau fungsi tanpa autentikasi. Hal ini berguna untuk pengujian, tetapi sebaiknya jangan gunakan setelan ini dalam produksi kecuali Anda membuat situs atau API publik. Selain itu, fitur ini mungkin tidak berfungsi untuk Anda, bergantung pada setelan kebijakan perusahaan Anda. Baca bagian Mengautentikasi pemanggilan untuk mengetahui informasi selengkapnya tentang cara memanggil fungsi yang memerlukan autentikasi.

Region

Anda harus menyediakan region saat men-deploy fungsi generasi ke-2. Lihat Lokasi untuk melihat daftar region yang tersedia. Konfigurasi gcloud CLI Anda memiliki region default yang terkait dengannya, tetapi Anda dapat menggunakan region yang didukung yang Anda inginkan dalam perintah deploy.

Untuk melihat region default yang terkait dengan konfigurasi gcloud CLI, jalankan:

gcloud config list

Anda dapat mengubah region default dengan cara berikut:

gcloud config set functions/region REGION

Perhatikan bahwa meskipun men-deploy fungsi ke region default, Anda tetap harus menyertakan region tersebut di command line deploy.

Memicu fungsi

  1. Setelah fungsi selesai di-deploy, catat properti uri atau temukan menggunakan perintah berikut:

    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. Setelah mengedit perintah berikut untuk menggunakan URI Anda sendiri, jalankan untuk menampilkan pesan Hello World!:

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

Menghapus Cloud Function

Untuk menghapus Cloud Function yang Anda buat dalam tutorial ini, jalankan perintah berikut:

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 

Anda juga dapat menghapus Cloud Functions dari Konsol Google Cloud.

Langkah selanjutnya