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:

  1. Ative a API Workflows usando o Terraform.
  2. Crie uma conta de serviço para o fluxo de trabalho usando o Terraform.
  3. Definir e implantar um fluxo de trabalho usando o Terraform.
  4. 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.

  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. Install the Google Cloud CLI.
  3. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

  4. To initialize the gcloud CLI, run the following command:

    gcloud init
  5. 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.

  6. Make sure that billing is enabled for your Google Cloud project.

  7. Enable the Cloud Resource Manager and Identity and Access Management (IAM) APIs:

    gcloud services enable cloudresourcemanager.googleapis.com<wbr>&nbsp;iam.googleapis.com
  8. Install the Google Cloud CLI.
  9. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

  10. To initialize the gcloud CLI, run the following command:

    gcloud init
  11. 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.

  12. Make sure that billing is enabled for your Google Cloud project.

  13. Enable the Cloud Resource Manager and Identity and Access Management (IAM) APIs:

    gcloud services enable cloudresourcemanager.googleapis.com<wbr>&nbsp;iam.googleapis.com
  14. 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.
  15. Install the Google Cloud CLI.
  16. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

  17. To initialize the gcloud CLI, run the following command:

    gcloud init
  18. 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.

  19. Make sure that billing is enabled for your Google Cloud project.

  20. Enable the Cloud Resource Manager and Identity and Access Management (IAM) APIs:

    gcloud services enable cloudresourcemanager.googleapis.com<wbr>&nbsp;iam.googleapis.com
  21. Install the Google Cloud CLI.
  22. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

  23. To initialize the gcloud CLI, run the following command:

    gcloud init
  24. 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.

  25. Make sure that billing is enabled for your Google Cloud project.

  26. Enable the Cloud Resource Manager and Identity and Access Management (IAM) APIs:

    gcloud services enable cloudresourcemanager.googleapis.com<wbr>&nbsp;iam.googleapis.com
  27. 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.
  28. Install the Google Cloud CLI.
  29. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

  30. To initialize the gcloud CLI, run the following command:

    gcloud init
  31. 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.

  32. Make sure that billing is enabled for your Google Cloud project.

  33. Enable the Cloud Resource Manager and Identity and Access Management (IAM) APIs:

    gcloud services enable cloudresourcemanager.googleapis.com<wbr>&nbsp;iam.googleapis.com
  34. Install the Google Cloud CLI.
  35. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

  36. To initialize the gcloud CLI, run the following command:

    gcloud init
  37. 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.

  38. Make sure that billing is enabled for your Google Cloud project.

  39. Enable the Cloud Resource Manager and Identity and Access Management (IAM) APIs:

    gcloud services enable cloudresourcemanager.googleapis.com<wbr>&nbsp;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>&nbsp;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>&nbsp;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.

    1. Crie um diretório:

      mkdir terraform
    2. Acesse o diretório terraform:

      cd terraform
    3. Adicione um novo arquivo, main.tf, ao diretório:

      nano main.tf
    4. Adicione os seguintes recursos ao arquivo main.tf:

      1. Atribua o ID do projeto:

        provider "google" {
        project = "PROJECT_ID"
        }

        Substitua PROJECT_ID pelo ID do projeto.

      2. Ative a API Workflows:

        # Enable Workflows API
        resource "google_project_service" "default" {
          service            = "workflows.googleapis.com"
          disable_on_destroy = false
        }

      3. Crie uma conta de serviço para o fluxo de trabalho:

        # Create a dedicated service account
        resource "google_service_account" "default" {
          account_id   = "sample-workflows-sa"
          display_name = "Sample Workflows Service Account"
        }

      4. Defina o fluxo de trabalho usando o recurso google_workflows_workflow:

        # Create a workflow
        resource "google_workflows_workflow" "default" {
          name            = "sample-workflow"
          region          = "us-central1"
          description     = "A sample workflow"
          service_account = google_service_account.default.id
        
          deletion_protection = false # set to "true" in production
        
          labels = {
            env = "test"
          }
          user_env_vars = {
            url = "https://timeapi.io/api/Time/current/zone?timeZone=Europe/Amsterdam"
          }
          source_contents = <<-EOF
          # This is a sample workflow that you can replace with your source code
          #
          # The workflow does the following:
          # - Retrieves the current date from a public API and stores the
          #   response in `currentDate`
          # - Retrieves a list of Wikipedia articles from a public API related
          #   to the day of the week stored in `currentDate`
          # - Returns the list of articles in the workflow output
          #
          # Note that when you define workflows in Terraform, variables must be
          # escaped with two dollar signs ($$) and not a single sign ($)
        
          - getCurrentDate:
              call: http.get
              args:
                  url: $${sys.get_env("url")}
              result: currentDate
          - readWikipedia:
              call: http.get
              args:
                  url: https://en.wikipedia.org/w/api.php
                  query:
                      action: opensearch
                      search: $${currentDate.body.dayOfWeek}
              result: wikiResult
          - returnOutput:
              return: $${wikiResult.body[1]}
        EOF
        
          depends_on = [google_project_service.default]
        }