Google Cloud CLI를 사용하여 Cloud 함수 만들기

이 페이지에서는 Google Cloud CLI를 사용하여 2세대 Cloud 함수를 만들고 배포하는 방법을 보여줍니다.

시작하기 전에

  1. Google Cloud 계정에 로그인합니다. Google Cloud를 처음 사용하는 경우 계정을 만들고 Google 제품의 실제 성능을 평가해 보세요. 신규 고객에게는 워크로드를 실행, 테스트, 배포하는 데 사용할 수 있는 $300의 무료 크레딧이 제공됩니다.
  2. Google Cloud Console의 프로젝트 선택기 페이지에서 Google Cloud 프로젝트를 선택하거나 만듭니다.

    프로젝트 선택기로 이동

  3. Google Cloud 프로젝트에 결제가 사용 설정되어 있는지 확인합니다.

  4. API Cloud Functions, Cloud Build, Artifact Registry, Cloud Run, and Logging 사용 설정

    API 사용 설정

  5. Google Cloud CLI를 설치합니다.
  6. gcloud CLI를 초기화하려면 다음 명령어를 실행합니다.

    gcloud init
  7. Google Cloud Console의 프로젝트 선택기 페이지에서 Google Cloud 프로젝트를 선택하거나 만듭니다.

    프로젝트 선택기로 이동

  8. Google Cloud 프로젝트에 결제가 사용 설정되어 있는지 확인합니다.

  9. API Cloud Functions, Cloud Build, Artifact Registry, Cloud Run, and Logging 사용 설정

    API 사용 설정

  10. Google Cloud CLI를 설치합니다.
  11. gcloud CLI를 초기화하려면 다음 명령어를 실행합니다.

    gcloud init
  12. 명령 프롬프트가 필요하신가요? Google Cloud Shell을 사용해보세요. Google Cloud Shell 명령줄 환경에는 Google Cloud CLI가 이미 포함되어 있으므로 별도로 설치할 필요가 없습니다. Google Cloud CLI는 Google Compute Engine 가상 머신에도 사전 설치되어 있습니다.

  13. 개발 환경을 준비합니다.

샘플 코드 가져오기

  1. 샘플 저장소를 로컬 머신에 클론합니다.

    Node.js

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

    또는 zip 파일로 샘플을 다운로드하고 압축을 풀 수 있습니다.

    Python

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

    또는 zip 파일로 샘플을 다운로드하고 압축을 풀 수 있습니다.

    Go

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

    또는 zip 파일로 샘플을 다운로드하고 압축을 풀 수 있습니다.

    Java

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

    또는 zip 파일로 샘플을 다운로드하고 압축을 풀 수 있습니다.

    C#

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

    또는 zip 파일로 샘플을 다운로드하고 압축을 풀 수 있습니다.

    Ruby

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

    또는 zip 파일로 샘플을 다운로드하고 압축을 풀 수 있습니다.

    PHP

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

    또는 zip 파일로 샘플을 다운로드하고 압축을 풀 수 있습니다.

  2. 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. 다음 샘플 코드를 살펴봅니다.

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

함수 배포

HTTP 트리거를 사용하여 함수를 배포하려면 샘플 코드가 포함된 디렉터리(또는 Java의 경우 pom.xml 파일)에서 다음 명령어를 실행합니다.

Node.js

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

--runtime 플래그를 사용하여 함수를 실행할 지원되는 Node.js 버전의 런타임 ID를 지정합니다.

Python

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

--runtime 플래그를 사용하여 함수를 실행할 지원되는 Python 버전의 런타임 ID를 지정합니다.

Go

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

--runtime 플래그를 사용하여 함수를 실행할 지원되는 Go 버전의 런타임 ID를 지정합니다.

Java

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

--runtime 플래그를 사용하여 함수를 실행할 지원되는 Java 버전의 런타임 ID를 지정합니다.

C#

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

--runtime 플래그를 사용하여 함수를 실행할 지원되는 .NET 버전의 런타임 ID를 지정합니다.

Ruby

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

--runtime 플래그를 사용하여 함수를 실행할 지원되는 Ruby 버전의 런타임 ID를 지정합니다.

PHP

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

--runtime 플래그를 사용하여 함수를 실행할 지원되는 PHP 버전의 런타임 ID를 지정합니다.

선택적으로 --allow-unauthenticated 플래그를 사용하여 인증 없이 함수에 도달할 수 있습니다. 이 방법은 테스트에 유용하지만, 공개 API 또는 웹사이트를 만들지 않는 한 프로덕션에서 이 설정을 사용하지 않는 것이 좋습니다. 또한 기업 정책 설정에 따라 작동하지 않을 수 있습니다. 인증이 필요한 함수를 호출하는 방법에 대한 자세한 내용은 호출 인증을 참조하세요.

리전

2세대 함수를 배포할 때 리전을 제공해야 합니다. 사용 가능한 리전 목록은 위치를 참조하세요. gcloud CLI 구성에 연결된 기본 리전이 있지만 deploy 명령어에 지원되는 모든 리전을 사용할 수 있습니다.

gcloud CLI 구성과 연결된 기본 리전을 보려면 다음을 실행합니다.

gcloud config list

기본 리전을 다음과 같이 변경할 수 있습니다.

gcloud config set functions/region REGION

함수를 기본 리전에 배포하더라도 deploy 명령줄에 리전을 포함해야 합니다.

함수 트리거

  1. 함수 배포가 완료되면 uri 속성을 기록하거나 다음 명령어를 사용하여 찾을 수 있습니다.

    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. 자체 URI를 사용하도록 다음 명령어를 수정한 후 실행하여 Hello World! 메시지를 확인합니다.

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

Cloud 함수 삭제

이 튜토리얼에서 만든 Cloud 함수를 삭제하려면 다음 명령어를 실행합니다.

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 

Google Cloud 콘솔에서 Cloud Functions를 삭제할 수도 있습니다.

다음 단계