Criar um fluxo de trabalho usando o Terraform
Neste guia de início rápido, mostramos como criar, implantar e executar seu primeiro fluxo de trabalho usando o Terraform. O Terraform é uma ferramenta de infraestrutura como código que permite criar, mudar e melhorar de maneira previsível sua infraestrutura em nuvem usando código. Aprenda a usar o Terraform para provisionar infraestruturas no Google Cloud.
Neste guia de início rápido, o fluxo de trabalho de exemplo envia uma solicitação para uma API pública e retorna a resposta da API.
Você vai concluir o seguinte:
- Ative a API Workflows usando o Terraform.
- Crie uma conta de serviço para o fluxo de trabalho usando o Terraform.
- Definir e implantar um fluxo de trabalho usando o Terraform.
- Execute o fluxo de trabalho usando a Google Cloud CLI.
Antes de começar
As restrições de segurança definidas pela sua organização podem impedir que você conclua as etapas a seguir. Para informações sobre solução de problemas, consulte Desenvolver aplicativos em um ambiente restrito de Google Cloud .
O Cloud Shell já tem o Terraform integrado. Se você precisar instalar o Terraform, consulte a documentação do Terraform da HashiCorp.
- 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.
- Install the Google Cloud CLI.
-
If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
-
To initialize the gcloud CLI, run the following command:
gcloud init
-
Create or select a Google Cloud project.
-
Create a Google Cloud project:
gcloud projects create PROJECT_ID
Replace
PROJECT_ID
with a name for the Google Cloud project you are creating. -
Select the Google Cloud project that you created:
gcloud config set project PROJECT_ID
Replace
PROJECT_ID
with your Google Cloud project name.
-
-
Make sure that billing is enabled for your Google Cloud project.
-
Enable the Cloud Resource Manager and Identity and Access Management (IAM) APIs:
gcloud services enable cloudresourcemanager.googleapis.com<wbr> iam.googleapis.com
- Install the Google Cloud CLI.
-
If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
-
To initialize the gcloud CLI, run the following command:
gcloud init
-
Create or select a Google Cloud project.
-
Create a Google Cloud project:
gcloud projects create PROJECT_ID
Replace
PROJECT_ID
with a name for the Google Cloud project you are creating. -
Select the Google Cloud project that you created:
gcloud config set project PROJECT_ID
Replace
PROJECT_ID
with your Google Cloud project name.
-
-
Make sure that billing is enabled for your Google Cloud project.
-
Enable the Cloud Resource Manager and Identity and Access Management (IAM) APIs:
gcloud services enable cloudresourcemanager.googleapis.com<wbr> iam.googleapis.com
- 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.
- Install the Google Cloud CLI.
-
If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
-
To initialize the gcloud CLI, run the following command:
gcloud init
-
Create or select a Google Cloud project.
-
Create a Google Cloud project:
gcloud projects create PROJECT_ID
Replace
PROJECT_ID
with a name for the Google Cloud project you are creating. -
Select the Google Cloud project that you created:
gcloud config set project PROJECT_ID
Replace
PROJECT_ID
with your Google Cloud project name.
-
-
Make sure that billing is enabled for your Google Cloud project.
-
Enable the Cloud Resource Manager and Identity and Access Management (IAM) APIs:
gcloud services enable cloudresourcemanager.googleapis.com<wbr> iam.googleapis.com
- Install the Google Cloud CLI.
-
If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
-
To initialize the gcloud CLI, run the following command:
gcloud init
-
Create or select a Google Cloud project.
-
Create a Google Cloud project:
gcloud projects create PROJECT_ID
Replace
PROJECT_ID
with a name for the Google Cloud project you are creating. -
Select the Google Cloud project that you created:
gcloud config set project PROJECT_ID
Replace
PROJECT_ID
with your Google Cloud project name.
-
-
Make sure that billing is enabled for your Google Cloud project.
-
Enable the Cloud Resource Manager and Identity and Access Management (IAM) APIs:
gcloud services enable cloudresourcemanager.googleapis.com<wbr> iam.googleapis.com
- 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.
- Install the Google Cloud CLI.
-
If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
-
To initialize the gcloud CLI, run the following command:
gcloud init
-
Create or select a Google Cloud project.
-
Create a Google Cloud project:
gcloud projects create PROJECT_ID
Replace
PROJECT_ID
with a name for the Google Cloud project you are creating. -
Select the Google Cloud project that you created:
gcloud config set project PROJECT_ID
Replace
PROJECT_ID
with your Google Cloud project name.
-
-
Make sure that billing is enabled for your Google Cloud project.
-
Enable the Cloud Resource Manager and Identity and Access Management (IAM) APIs:
gcloud services enable cloudresourcemanager.googleapis.com<wbr> iam.googleapis.com
- Install the Google Cloud CLI.
-
If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
-
To initialize the gcloud CLI, run the following command:
gcloud init
-
Create or select a Google Cloud project.
-
Create a Google Cloud project:
gcloud projects create PROJECT_ID
Replace
PROJECT_ID
with a name for the Google Cloud project you are creating. -
Select the Google Cloud project that you created:
gcloud config set project PROJECT_ID
Replace
PROJECT_ID
with your Google Cloud project name.
-
-
Make sure that billing is enabled for your Google Cloud project.
-
Enable the Cloud Resource Manager and Identity and Access Management (IAM) APIs:
gcloud services enable cloudresourcemanager.googleapis.com<wbr> iam.googleapis.com
If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
To initialize the gcloud CLI, run the following command:
gcloud init
Create or select a Google Cloud project.
-
Create a Google Cloud project:
gcloud projects create PROJECT_ID
Replace
PROJECT_ID
with a name for the Google Cloud project you are creating. -
Select the Google Cloud project that you created:
gcloud config set project PROJECT_ID
Replace
PROJECT_ID
with your Google Cloud project name.
Make sure that billing is enabled for your Google Cloud project.
Enable the Cloud Resource Manager and Identity and Access Management (IAM) APIs:
gcloud services enable cloudresourcemanager.googleapis.com<wbr> iam.googleapis.com
If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
To initialize the gcloud CLI, run the following command:
gcloud init
Create or select a Google Cloud project.
-
Create a Google Cloud project:
gcloud projects create PROJECT_ID
Replace
PROJECT_ID
with a name for the Google Cloud project you are creating. -
Select the Google Cloud project that you created:
gcloud config set project PROJECT_ID
Replace
PROJECT_ID
with your Google Cloud project name.
Make sure that billing is enabled for your Google Cloud project.
Enable the Cloud Resource Manager and Identity and Access Management (IAM) APIs:
gcloud services enable cloudresourcemanager.googleapis.com<wbr> iam.googleapis.com
Criar um arquivo de configuração do Terraform
Crie um arquivo de configuração do Terraform chamado main.tf
e inclua os recursos do provedor do Google para o Terraform usados neste guia de início rápido.
É possível usar interpolação para substituições, como variáveis de referência, atributos de recursos e funções de chamada.
Crie um diretório:
mkdir terraform
Acesse o diretório
terraform
:cd terraform
Adicione um novo arquivo,
main.tf
, ao diretório:nano main.tf
Adicione os seguintes recursos ao arquivo
main.tf
:Atribua o ID do projeto:
provider "google" { project = "PROJECT_ID" }
Substitua
PROJECT_ID
pelo ID do projeto.Ative a API Workflows:
Crie uma conta de serviço para o fluxo de trabalho:
Defina o fluxo de trabalho usando o recurso
google_workflows_workflow
:Os seguintes argumentos são usados no fluxo de trabalho de exemplo:
name
: o nome do fluxo de trabalho.region
: o local do fluxo de trabalho.description
: uma descrição do fluxo de trabalho.service_account
: o endereço de e-mail ou ID exclusivo da conta de serviço associada à versão mais recente do fluxo de trabalho. Essa conta de serviço representa a identidade do fluxo de trabalho e determina quais permissões ele tem. Se você não especificar uma conta de serviço durante a criação do fluxo de trabalho, ele vai usar a conta de serviço padrão do Compute Engine como identidade. Para mais informações, consulte Conceder permissão a um fluxo de trabalho para acessar recursos Google Cloud .labels
: uma lista de pares de rótulos de chave-valor para atribuir a este fluxo de trabalho que ajuda a organizar as instâncias Google Cloud . Para mais informações, consulte O que são rótulos?user_env_vars
: variáveis de ambiente definidas pelo usuário associadas a esta revisão do fluxo de trabalho. Para mais informações, consulte Usar variáveis de ambiente.source_contents
: o código Workflows a serem executados. Para saber mais sobre o limite de tamanho de arquivo, consulte Limites de recurso.
Outros argumentos opcionais incluem:
crypto_key_name
: o ID do recurso de uma chave do Cloud Key Management Service no formato a seguir:projects/PROJECT_NAME/locations/LOCATION/keyRings/KEY_RING/cryptoKeys/KEY_NAME
Para mais informações, consulte Usar chaves de criptografia gerenciadas pelo cliente.
call_log_level
: o nível de registro a ser aplicado a chamadas e respostas de chamadas durante as execuções desse fluxo de trabalho. Os valores possíveis são:CALL_LOG_LEVEL_UNSPECIFIED
LOG_ALL_CALLS
LOG_ERRORS_ONLY
LOG_NONE
Para mais informações, consulte Registro de chamadas.
project
: o ID do projeto ao qual o recurso pertence. Se ele não for informado, o projeto do provedor será usado.name_prefix
: cria um nome exclusivo que começa com o prefixo especificado. Se esse ename
não forem especificados, um valor aleatório será escolhido para o nome.
Criar e executar o fluxo de trabalho
Implante seus recursos do Terraform para criar e executar o fluxo de trabalho.
Inicialize o Terraform no diretório:
terraform init
Verifique se as alterações propostas pelo Terraform correspondem ao plano esperado:
terraform plan
Ignore a observação sobre o uso da opção
-out
.Crie o fluxo de trabalho:
terraform apply
No prompt Digite um valor, digite
yes
para continuar criando recursos.Confirme se um fluxo de trabalho foi criado:
gcloud workflows list --location us-central1
A saída será semelhante a:
NAME STATE REVISION_ID UPDATE_TIME projects/project-name/locations/us-central1/workflows/sample-workflow ACTIVE 000001-f9a 2024-02-24T13:38:58.353765906Z
Também é possível executar o fluxo de trabalho:
gcloud workflows execute sample-workflow
Limpar
Para evitar cobranças na sua conta do Google Cloud pelos recursos usados nesta página, exclua o projeto Google Cloud com esses recursos.
- Exclua todos os recursos que você criou com o Terraform:
terraform destroy
- Exclua o fluxo de trabalho que você criou:
Quando perguntar se você quer continuar, digitegcloud workflows delete sample-workflow
y
. - Se preferir, exclua o projeto Google Cloud para evitar cobranças. A exclusão do projeto Google Cloud interrompe o faturamento de todos os recursos usados nele.
Delete a Google Cloud project:
gcloud projects delete PROJECT_ID
A seguir
Exceto em caso de indicação contrária, o conteúdo desta página é licenciado de acordo com a Licença de atribuição 4.0 do Creative Commons, e as amostras de código são licenciadas de acordo com a Licença Apache 2.0. Para mais detalhes, consulte as políticas do site do Google Developers. Java é uma marca registrada da Oracle e/ou afiliadas.
Última atualização 2025-05-14 UTC.