Exécuter un workflow à l'aide des bibliothèques clientes Cloud

Ce guide de démarrage rapide vous explique comment exécuter un workflow et afficher les résultats d'exécution à l'aide des bibliothèques clientes Cloud.

Pour en savoir plus sur l'installation des bibliothèques clientes Cloud et la configuration de votre environnement de développement, consultez la présentation des bibliothèques clientes de Workflows.

Vous pouvez suivre les étapes suivantes à l'aide de la Google Cloud CLI dans votre terminal ou Cloud Shell.

Avant de commencer

Les contraintes de sécurité définies par votre organisation peuvent vous empêcher d'effectuer les étapes suivantes. Pour en savoir plus sur la résolution des problèmes, consultez Développer des applications dans un environnement Google Cloud limité.

  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. To initialize the gcloud CLI, run the following command:

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

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

  6. Enable the Workflows API:

    gcloud services enable workflows.googleapis.com
  7. Set up authentication:

    1. Create the service account:

      gcloud iam service-accounts create SERVICE_ACCOUNT_NAME

      Replace SERVICE_ACCOUNT_NAME with a name for the service account.

    2. Grant the roles/owner IAM role to the service account:

      gcloud projects add-iam-policy-binding PROJECT_ID --member="serviceAccount:SERVICE_ACCOUNT_NAME@PROJECT_ID.iam.gserviceaccount.com" --role=roles/owner

      Replace the following:

      • SERVICE_ACCOUNT_NAME: the name of the service account
      • PROJECT_ID: the project ID where you created the service account
  8. Install the Google Cloud CLI.
  9. To initialize the gcloud CLI, run the following command:

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

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

  12. Enable the Workflows API:

    gcloud services enable workflows.googleapis.com
  13. Set up authentication:

    1. Create the service account:

      gcloud iam service-accounts create SERVICE_ACCOUNT_NAME

      Replace SERVICE_ACCOUNT_NAME with a name for the service account.

    2. Grant the roles/owner IAM role to the service account:

      gcloud projects add-iam-policy-binding PROJECT_ID --member="serviceAccount:SERVICE_ACCOUNT_NAME@PROJECT_ID.iam.gserviceaccount.com" --role=roles/owner

      Replace the following:

      • SERVICE_ACCOUNT_NAME: the name of the service account
      • PROJECT_ID: the project ID where you created the service account
  14. (Facultatif) Pour envoyer des journaux à Cloud Logging, accordez le rôle roles/logging.logWriter au compte de service.

    gcloud projects add-iam-policy-binding PROJECT_ID \
        --member "serviceAccount:SERVICE_ACCOUNT_NAME@PROJECT_ID.iam.gserviceaccount.com" \
        --role "roles/logging.logWriter"

    Pour en savoir plus sur les rôles et les autorisations des comptes de service, consultez la section Accorder une autorisation de workflow pour accéder aux ressourcesGoogle Cloud .

  15. Si nécessaire, téléchargez et installez l'outil de gestion du code source Git.

Déployer un exemple de workflow

Après avoir défini un workflow, vous le déployez pour le rendre disponible en exécution. L'étape de déploiement vérifie également que le fichier source peut être exécuté.

Le workflow suivant envoie une requête à une API publique, puis renvoie la réponse de l'API.

  1. Créez un fichier texte avec le nom de fichier myFirstWorkflow.yaml avec le contenu suivant:

    - getCurrentTime:
        call: http.get
        args:
          url: https://timeapi.io/api/Time/current/zone?timeZone=Europe/Amsterdam
        result: currentTime
    - readWikipedia:
        call: http.get
        args:
          url: https://en.wikipedia.org/w/api.php
          query:
            action: opensearch
            search: ${currentTime.body.dayOfWeek}
        result: wikiResult
    - returnResult:
        return: ${wikiResult.body[1]}
  2. Une fois le workflow créé, vous pouvez le déployer. Toutefois, vous ne devez pas l'exécuter:

    gcloud workflows deploy myFirstWorkflow \
        --source=myFirstWorkflow.yaml \
        --service-account=SERVICE_ACCOUNT_NAME@PROJECT_ID.iam.gserviceaccount.com \
        --location=CLOUD_REGION

    Remplacez CLOUD_REGION par un emplacement compatible pour le workflow. La région par défaut utilisée dans les exemples de code est us-central1.

Obtenir l'exemple de code

Vous pouvez cloner l'exemple de code depuis GitHub.

  1. Clonez le dépôt de l'exemple d'application sur votre machine locale :

    Java

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

    Vous pouvez également télécharger l'exemple en tant que fichier ZIP et l'extraire.

    Node.js

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

    Vous pouvez également télécharger l'exemple en tant que fichier ZIP et l'extraire.

    Python

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

    Vous pouvez également télécharger l'exemple en tant que fichier ZIP et l'extraire.

  2. Accédez au répertoire contenant l'exemple de code Workflows:

    Java

    cd java-docs-samples/workflows/cloud-client/

    Node.js

    cd nodejs-docs-samples/workflows/quickstart/

    Python

    cd python-docs-samples/workflows/cloud-client/

  3. Consultez l'exemple de code. Chaque application exemple effectue les opérations suivantes:

    1. Configure les bibliothèques clientes Cloud pour Workflows.
    2. Exécute un workflow.
    3. Interroge l'exécution du workflow (en utilisant un intervalle exponentiel entre les tentatives) jusqu'à la fin de l'exécution.
    4. Imprime les résultats d'exécution.

    Java

    // Imports the Google Cloud client library
    
    import com.google.cloud.workflows.executions.v1.CreateExecutionRequest;
    import com.google.cloud.workflows.executions.v1.Execution;
    import com.google.cloud.workflows.executions.v1.ExecutionsClient;
    import com.google.cloud.workflows.executions.v1.WorkflowName;
    import java.io.IOException;
    import java.util.concurrent.ExecutionException;
    
    public class WorkflowsQuickstart {
    
      private static final String PROJECT = System.getenv("GOOGLE_CLOUD_PROJECT");
      private static final String LOCATION = System.getenv().getOrDefault("LOCATION", "us-central1");
      private static final String WORKFLOW =
          System.getenv().getOrDefault("WORKFLOW", "myFirstWorkflow");
    
      public static void main(String... args)
          throws IOException, InterruptedException, ExecutionException {
        if (PROJECT == null) {
          throw new IllegalArgumentException(
              "Environment variable 'GOOGLE_CLOUD_PROJECT' is required to run this quickstart.");
        }
        workflowsQuickstart(PROJECT, LOCATION, WORKFLOW);
      }
    
      private static volatile boolean finished;
    
      public static void workflowsQuickstart(String projectId, String location, String workflow)
          throws IOException, InterruptedException, ExecutionException {
        // Initialize client that will be used to send requests. This client only needs
        // to be created once, and can be reused for multiple requests. After completing all of your
        // requests, call the "close" method on the client to safely clean up any remaining background
        // resources.
        try (ExecutionsClient executionsClient = ExecutionsClient.create()) {
          // Construct the fully qualified location path.
          WorkflowName parent = WorkflowName.of(projectId, location, workflow);
    
          // Creates the execution object.
          CreateExecutionRequest request =
              CreateExecutionRequest.newBuilder()
                  .setParent(parent.toString())
                  .setExecution(Execution.newBuilder().build())
                  .build();
          Execution response = executionsClient.createExecution(request);
    
          String executionName = response.getName();
          System.out.printf("Created execution: %s%n", executionName);
    
          long backoffTime = 0;
          long backoffDelay = 1_000; // Start wait with delay of 1,000 ms
          final long backoffTimeout = 10 * 60 * 1_000; // Time out at 10 minutes
          System.out.println("Poll for results...");
    
          // Wait for execution to finish, then print results.
          while (!finished && backoffTime < backoffTimeout) {
            Execution execution = executionsClient.getExecution(executionName);
            finished = execution.getState() != Execution.State.ACTIVE;
    
            // If we haven't seen the results yet, wait.
            if (!finished) {
              System.out.println("- Waiting for results");
              Thread.sleep(backoffDelay);
              backoffTime += backoffDelay;
              backoffDelay *= 2; // Double the delay to provide exponential backoff.
            } else {
              System.out.println("Execution finished with state: " + execution.getState().name());
              System.out.println("Execution results: " + execution.getResult());
            }
          }
        }
      }
    }

    Node.js

    const {ExecutionsClient} = require('@google-cloud/workflows');
    const client = new ExecutionsClient();
    /**
     * TODO(developer): Uncomment these variables before running the sample.
     */
    // const projectId = 'my-project';
    // const location = 'us-central1';
    // const workflow = 'myFirstWorkflow';
    // const searchTerm = '';
    
    /**
     * Executes a Workflow and waits for the results with exponential backoff.
     * @param {string} projectId The Google Cloud Project containing the workflow
     * @param {string} location The workflow location
     * @param {string} workflow The workflow name
     * @param {string} searchTerm Optional search term to pass to the Workflow as a runtime argument
     */
    async function executeWorkflow(projectId, location, workflow, searchTerm) {
      /**
       * Sleeps the process N number of milliseconds.
       * @param {Number} ms The number of milliseconds to sleep.
       */
      function sleep(ms) {
        return new Promise(resolve => {
          setTimeout(resolve, ms);
        });
      }
      const runtimeArgs = searchTerm ? {searchTerm: searchTerm} : {};
      // Execute workflow
      try {
        const createExecutionRes = await client.createExecution({
          parent: client.workflowPath(projectId, location, workflow),
          execution: {
            // Runtime arguments can be passed as a JSON string
            argument: JSON.stringify(runtimeArgs),
          },
        });
        const executionName = createExecutionRes[0].name;
        console.log(`Created execution: ${executionName}`);
    
        // Wait for execution to finish, then print results.
        let executionFinished = false;
        let backoffDelay = 1000; // Start wait with delay of 1,000 ms
        console.log('Poll every second for result...');
        while (!executionFinished) {
          const [execution] = await client.getExecution({
            name: executionName,
          });
          executionFinished = execution.state !== 'ACTIVE';
    
          // If we haven't seen the result yet, wait a second.
          if (!executionFinished) {
            console.log('- Waiting for results...');
            await sleep(backoffDelay);
            backoffDelay *= 2; // Double the delay to provide exponential backoff.
          } else {
            console.log(`Execution finished with state: ${execution.state}`);
            console.log(execution.result);
            return execution.result;
          }
        }
      } catch (e) {
        console.error(`Error executing workflow: ${e}`);
      }
    }
    
    executeWorkflow(projectId, location, workflowName, searchTerm).catch(err => {
      console.error(err.message);
      process.exitCode = 1;
    });
    

    Python

    import os
    import time
    
    from google.cloud import workflows_v1
    from google.cloud.workflows import executions_v1
    from google.cloud.workflows.executions_v1 import Execution
    from google.cloud.workflows.executions_v1.types import executions
    
    PROJECT = os.getenv("GOOGLE_CLOUD_PROJECT")
    LOCATION = os.getenv("LOCATION", "us-central1")
    WORKFLOW_ID = os.getenv("WORKFLOW", "myFirstWorkflow")
    
    
    def execute_workflow(project: str, location: str, workflow: str) -> Execution:
        """Execute a workflow and print the execution results.
    
        A workflow consists of a series of steps described
        using the Workflows syntax, and can be written in either YAML or JSON.
    
        Args:
            project: The Google Cloud project id
                which contains the workflow to execute.
            location: The location for the workflow
            workflow: The ID of the workflow to execute.
    
        Returns:
            The execution response.
        """
        # Set up API clients.
        execution_client = executions_v1.ExecutionsClient()
        workflows_client = workflows_v1.WorkflowsClient()
    
        # Construct the fully qualified location path.
        parent = workflows_client.workflow_path(project, location, workflow)
    
        # Execute the workflow.
        response = execution_client.create_execution(request={"parent": parent})
        print(f"Created execution: {response.name}")
    
        # Wait for execution to finish, then print results.
        execution_finished = False
        backoff_delay = 1  # Start wait with delay of 1 second
        print("Poll for result...")
        while not execution_finished:
            execution = execution_client.get_execution(
                request={"name": response.name}
            )
            execution_finished = execution.state != executions.Execution.State.ACTIVE
    
            # If we haven't seen the result yet, wait a second.
            if not execution_finished:
                print("- Waiting for results...")
                time.sleep(backoff_delay)
                # Double the delay to provide exponential backoff.
                backoff_delay *= 2
            else:
                print(f"Execution finished with state: {execution.state.name}")
                print(f"Execution results: {execution.result}")
                return execution
    
    
    if __name__ == "__main__":
        assert PROJECT, "'GOOGLE_CLOUD_PROJECT' environment variable not set."
        execute_workflow(PROJECT, LOCATION, WORKFLOW_ID)

Exécuter l'exemple de code

Vous pouvez exécuter l'exemple de code et exécuter votre workflow. L'exécution d'un workflow exécute la définition de workflow déployée associée au workflow.

  1. Pour exécuter l'exemple, commencez par installer les dépendances:

    Java

    mvn compile

    Node.js

    npm install -D tsx

    Python

    pip3 install -r requirements.txt

  2. Exécutez le script :

    Java

    GOOGLE_CLOUD_PROJECT=PROJECT_ID LOCATION=CLOUD_REGION WORKFLOW=WORKFLOW_NAME mvn compile exec:java -Dexec.mainClass=com.example.workflows.WorkflowsQuickstart

    Node.js

    npx tsx index.js

    Python

    GOOGLE_CLOUD_PROJECT=PROJECT_ID LOCATION=CLOUD_REGION WORKFLOW=WORKFLOW_NAME python3 main.py

    Remplacez les éléments suivants :

    • PROJECT_ID: nom de votre Google Cloud projet
    • CLOUD_REGION: emplacement de votre workflow (par défaut: us-central1)
    • WORKFLOW_NAME: nom de votre workflow (par défaut: myFirstWorkflow)

    Le résultat ressemble à ce qui suit :

    Execution finished with state: SUCCEEDED
    Execution results: ["Thursday","Thursday Night Football","Thursday (band)","Thursday Island","Thursday (album)","Thursday Next","Thursday at the Square","Thursday's Child (David Bowie song)","Thursday Afternoon","Thursday (film)"]
    

Transmettre des données dans une requête d'exécution

En fonction du langage de la bibliothèque cliente, vous pouvez également transmettre un argument d'environnement d'exécution dans une requête d'exécution. Exemple :

Java

// Creates the execution object.
CreateExecutionRequest request =
    CreateExecutionRequest.newBuilder()
        .setParent(parent.toString())
        .setExecution(Execution.newBuilder().setArgument("{\"searchTerm\":\"Friday\"}").build())
        .build();

Node.js

// Execute workflow
try {
  const createExecutionRes = await client.createExecution({
    parent: client.workflowPath(projectId, location, workflow),
    execution: {
      argument: JSON.stringify({"searchTerm": "Friday"})
    }
});
const executionName = createExecutionRes[0].name;

Pour en savoir plus sur la transmission d'arguments d'environnement d'exécution, consultez la section Transmettre des arguments d'environnement d'exécution dans une requête d'exécution.

Effectuer un nettoyage

Pour éviter que les ressources utilisées sur cette page ne soient facturées sur votre compte Google Cloud , supprimez le projet Google Cloud contenant les ressources.

  1. Supprimez le workflow que vous avez créé :

    gcloud workflows delete myFirstWorkflow
    
  2. Lorsque vous êtes invité à poursuivre l'opération, saisissez y.

Le workflow est supprimé.

Étape suivante