Cancel execution (v1)

Cancel an ongoing execution of a workflow.

Code sample

Go

Before trying this sample, follow the Go setup instructions in the Workflows quickstart using client libraries. For more information, see the Workflows Go API reference documentation.

To authenticate to Workflows, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.


import (
	"context"
	"fmt"
	"io"

	workflows "cloud.google.com/go/workflows/executions/apiv1"
	executionspb "cloud.google.com/go/workflows/executions/apiv1/executionspb"
)

// cancelExecution cancels an ongoing execution of a workflow.
func cancelExecution(ctx context.Context, w io.Writer, projectID string, locationID string, workflowID string, executionID string) error {
	name := fmt.Sprintf("projects/%s/locations/%s/workflows/%s/executions/%s", projectID, locationID, workflowID, executionID)

	client, err := workflows.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("NewClient failed: %w", err)
	}
	defer client.Close()

	req := &executionspb.CancelExecutionRequest{
		Name: name,
	}

	resp, err := client.CancelExecution(ctx, req)
	if err != nil {
		return fmt.Errorf("client.CancelExecution: %w", err)
	}

	fmt.Fprintf(w, "Canceled execution: %s\nState: %v\n", resp.GetName(), resp.GetState())
	return nil
}

What's next

To search and filter code samples for other Google Cloud products, see the Google Cloud sample browser.