Criar e implantar uma função com o Cloud Code para VS Code
Mantenha tudo organizado com as coleções
Salve e categorize o conteúdo com base nas suas preferências.
Nesta página, mostramos como criar, fazer o download, implantar e invocar uma função HTTP de segunda geração usando o Cloud Functions com o Cloud Code.
Antes de começar
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.
In the Google Cloud console, on the project selector page,
select or create a Google Cloud project.
Fazer o download de uma função que já existe para um novo espaço de trabalho
Para fazer o download de uma função em um novo espaço de trabalho, siga estas etapas:
Clique em Cloud Code e expanda a seção
Cloud Functions.
Abra o snippet do Google Cloud projeto, clique com o botão direito do mouse na função
que você quer baixar e selecione Fazer o download para um novo espaço de trabalho.
Quando solicitado, insira um nome para o novo aplicativo e clique em
Criar novo aplicativo.
Isso faz o download da função para sua máquina local e a abre em um novo
espaço de trabalho no seu ambiente de desenvolvimento integrado.
Implantar uma função
Para implantar uma função, siga estas etapas:
Clique com o botão direito do mouse em uma função e selecione Implantar função.
No menu "Seleção rápida", selecione um projeto Google Cloud para implantar
sua função.
Selecione a região em que a função será implantada.
Selecione um ambiente de execução.
A implantação da função pode levar alguns minutos. Enquanto estiver em andamento, um indicador de progresso progress_activity vai aparecer. Quando ele for concluído, uma marca de seleção check_circle vai aparecer. Se ele falhar, uma marca de erro vai aparecer.
Se a implantação falhar, consulte a mensagem de erro na guia Saída.
Clique no link para acessar os registros do build no console do Google Cloud e
receber mais detalhes sobre o erro.
Opcional: depois que a função é implantada, é possível executar as seguintes
ações:
Para conferir os arquivos somente leitura da função implantada, expanda a função
e depois a pasta Código-fonte. Aqui é possível ver
launch.json em .vscode, o código implantado e package.json.
Para ver a função no console do Google Cloud , clique com o botão direito do mouse na
função e selecione Abrir no console do Cloud. Se solicitado, selecione
Abrir.
Para editar os metadados da função, clique com o botão direito do mouse na função e
selecione Editar metadados no console do Cloud.
Para conferir os registros da função implantada, clique com o botão direito do mouse na função e
selecione Ver registros.
Invocar uma função
Invocar uma função permite que você execute a função implantada no
console doGoogle Cloud a partir do terminal integrado do IDE. Para invocar uma função,
siga estas etapas:
Clique com o botão direito do mouse na função e selecione Invocar função via HTTP.
No menu de seleção rápida Acionar função via HTTP que aparece, selecione uma das
duas opções:
Padrão: um terminal é aberto no ambiente de desenvolvimento integrado e executa um comando para executar
a função em Google Cloud.
Importar argumentos de um arquivo JSON: essa opção pega o conteúdo do
arquivo JSON selecionado, transforma em uma string e transmite com
-d '{. Isso é útil quando você tem uma entrada para suas funções e quer salvá-la, permitindo que você a execute sem precisar digitar repetidamente.
[[["Fácil de entender","easyToUnderstand","thumb-up"],["Meu problema foi resolvido","solvedMyProblem","thumb-up"],["Outro","otherUp","thumb-up"]],[["Difícil de entender","hardToUnderstand","thumb-down"],["Informações incorretas ou exemplo de código","incorrectInformationOrSampleCode","thumb-down"],["Não contém as informações/amostras de que eu preciso","missingTheInformationSamplesINeed","thumb-down"],["Problema na tradução","translationIssue","thumb-down"],["Outro","otherDown","thumb-down"]],["Última atualização 2025-09-04 UTC."],[[["\u003cp\u003eThis page guides users on how to manage 2nd gen HTTP functions using Cloud Functions with Cloud Code, covering creation, downloading, deployment, and invocation.\u003c/p\u003e\n"],["\u003cp\u003eNew functions can be created from templates within Cloud Code, allowing users to define function names and create new applications within specified pathways.\u003c/p\u003e\n"],["\u003cp\u003eExisting functions can be downloaded from Google Cloud to a new workspace on a local machine, allowing users to then edit locally.\u003c/p\u003e\n"],["\u003cp\u003eFunctions are deployed to a user-specified Google Cloud project, region, and runtime, with progress indicators and options to view source code, logs, or edit metadata.\u003c/p\u003e\n"],["\u003cp\u003eDeployed functions can be invoked directly from the IDE via HTTP, either with default settings or by importing arguments from a JSON file.\u003c/p\u003e\n"]]],[],null,["# Create and deploy a function with Cloud Code for VS Code\n\nThis page shows you how to create, download, deploy, and invoke a 2nd gen HTTP\nfunction using [Cloud Functions](https://cloud.google.com/functions/) with\nCloud Code.\n\nBefore you begin\n----------------\n\n- Sign in to your Google Cloud account. If you're new to Google Cloud, [create an account](https://console.cloud.google.com/freetrial) to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.\n- In the Google Cloud console, on the project selector page,\n select or create a Google Cloud project.\n\n | **Note**: If you don't plan to keep the resources that you create in this procedure, create a project instead of selecting an existing project. After you finish these steps, you can delete the project, removing all resources associated with the project.\n\n [Go to project selector](https://console.cloud.google.com/projectselector2/home/dashboard)\n-\n [Verify that billing is enabled for your Google Cloud project](/billing/docs/how-to/verify-billing-enabled#confirm_billing_is_enabled_on_a_project).\n\n-\n\n\n Enable the Cloud Functions, Cloud Build, Artifact Registry, Cloud Run, Logging, and Pub/Sub APIs.\n\n\n [Enable the APIs](https://console.cloud.google.com/flows/enableapi?apiid=cloudfunctions,cloudbuild.googleapis.com,artifactregistry.googleapis.com,run.googleapis.com,logging.googleapis.com,pubsub.googleapis.com&redirect=https://cloud.google.com/functions/docs/create-deploy-nodejs)\n\n- In the Google Cloud console, on the project selector page,\n select or create a Google Cloud project.\n\n | **Note**: If you don't plan to keep the resources that you create in this procedure, create a project instead of selecting an existing project. After you finish these steps, you can delete the project, removing all resources associated with the project.\n\n [Go to project selector](https://console.cloud.google.com/projectselector2/home/dashboard)\n-\n [Verify that billing is enabled for your Google Cloud project](/billing/docs/how-to/verify-billing-enabled#confirm_billing_is_enabled_on_a_project).\n\n-\n\n\n Enable the Cloud Functions, Cloud Build, Artifact Registry, Cloud Run, Logging, and Pub/Sub APIs.\n\n\n [Enable the APIs](https://console.cloud.google.com/flows/enableapi?apiid=cloudfunctions,cloudbuild.googleapis.com,artifactregistry.googleapis.com,run.googleapis.com,logging.googleapis.com,pubsub.googleapis.com&redirect=https://cloud.google.com/functions/docs/create-deploy-nodejs)\n\n1. Install [Git](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git). Git is required for copying samples to your machine.\n2. Install the [Cloud Code plugin](/code/docs/vscode/install#installing) if you haven't already.\n\nCreate a function\n-----------------\n\nIf you've created a function before, you can [download an existing function to a\nnew workspace](#download_an_existing_function_to_a_new_workspace) and edit it\nlocally.\n\nTo create a new function using a sample, follow these steps:\n\n1. Click **Cloud Code** and then expand the\n **Cloud Functions** section.\n\n2. Click add\n **Create function** and select a template.\n\n3. Navigate to the pathway that you'd like to create your new function in, enter\n a name for the function, and select **Create New Application**.\n\n If the folder of your application doesn't appear automatically in the\n **Explorer** , click\n refresh\n **Refresh**.\n\n The `launch.json` file contains the required configurations for your\n function: \n\n {\n \"configurations\": [\n {\n \"name\": \"Deploy Cloud Function\",\n \"type\": \"cloudcode.cloudfunctions\",\n \"request\": \"launch\",\n \"functionName\": \"function-hello-world\",\n \"gen\": \"GEN_2\",\n \"entryPoint\": \"helloHttp\",\n }\n ]\n }\n\nTo learn more about creating multiple functions in a single workspace, see\n[Manage functions in VS Code workspace](/code/docs/vscode/manage-functions-workspace).\n\nDownload an existing function to a new workspace\n------------------------------------------------\n\nTo download a function to a new workspace, follow these steps:\n\n1. Click **Cloud Code** and then expand the\n **Cloud Functions** section.\n\n2. Expand your Google Cloud project snippet, right-click the function\n that you wish to download, and select **Download to new workspace**.\n\n3. When prompted, enter a name for the new application and click\n **Create New Application**.\n\n This downloads the function to your local machine and opens it in a new\n workspace in your IDE.\n\nDeploy a function\n-----------------\n\nTo deploy a function, follow these steps:\n\n1. Right-click a function and select **Deploy function**.\n\n2. In the Quickpick menu, select a Google Cloud project to deploy your\n function to.\n\n3. Select a region that the function will be deployed to.\n\n4. Select a runtime.\n\n The function's deployment may take a few minutes. While in progress,\n a progress_activity\n progress indicator appears. After it is complete, a\n check_circle checkmark\n appears. If it fails, an\n error error mark appears.\n\n If the deployment fails, refer to the **Output** tab for the error message.\n Clicking the link takes you to the build logs in Google Cloud console and\n provides more detail about the error.\n\n5. Optional: Once the function is deployed, you can perform the following\n actions:\n\n - To view read-only files of your deployed function, expand the function\n and then expand the **Source Code** folder. Here you can view\n `launch.json` under `.vscode`, the deployed code, and `package.json`.\n\n - To view the function in Google Cloud console, right-click the\n function and select **Open in Cloud Console** , and if prompted, select\n **Open**.\n\n - To edit the metadata of your function, right-click the function and\n select **Edit metadata in Cloud Console**.\n\n - To view logs of the deployed function, right-click the function and\n select **View logs**.\n\nInvoke a function\n-----------------\n\nInvoking a function allows you to execute the deployed function in\nGoogle Cloud console from the IDE's built-in terminal. To invoke a function,\nfollow these steps:\n\n1. Right-click the function and select **Invoke function via HTTP**.\n\n2. In the **Trigger function via HTTP** Quickpick that appears, select one of\n the two options:\n\n - **Default**: A terminal opens in the IDE and runs a command to execute\n the function in Google Cloud.\n\n - **Import arguments from JSON file** : This option takes the content of\n the selected JSON file, turns it into a string, and passes it with\n `-d '{`. This is useful for when you have an input to your functions and\n want to save it, allowing you to execute it without having to retype it repeatedly.\n\nWhat's next\n-----------\n\n- See the [Work with Cloud Functions](/code/docs/vscode/functions-overview) overview to learn more about [managing your workspace](/code/docs/vscode/manage-functions-workspace) or [setting up a local development environment](/code/docs/vscode/setup-local-functions-dev-environment).\n\nGet Support\n-----------\n\nTo send feedback, report issues on [GitHub](https://github.com/GoogleCloudPlatform/cloud-code-vscode/issues), or ask a question on [Stack Overflow](https://stackoverflow.com/questions/ask?tags=cloud-code-vscode)."]]