Installation

Install as Agent Plugin Recommended
copilot plugin marketplace add samueltauil/skills-hub
copilot plugin install application-integration-authoring@skills-hub

Works with GitHub Copilot CLI and VS Code (enable chat.plugins.enabled). Plugin application-integration-authoring v1.0.0 follows the Agent Plugins spec.

Install with the gh extension
gh skills-hub install application-integration-authoring

Don't have the extension? Run gh extension install samueltauil/skills-hub first.

Download and extract to your repository:

.github/skills/application-integration-authoring/

Extract the ZIP to .github/skills/ in your repo. The folder name must match application-integration-authoring for Copilot to auto-discover it.

Skill Files (7)

SKILL.md 33.7 KB
---
name: application-integration-authoring
metadata:
  version: "1.0.3"
  category: ApplicationDevelopment
description: >-
  Builds, versions, publishes, tests, and executes Google Cloud Application Integration
  workflows through the REST API and Python discovery client, and promotes versions across
  environments. Use when listing integrations, downloading or uploading integration versions
  as JSON, configuring API triggers or config variables, publishing drafts, invoking
  integrations, or automating CI/CD promotion. Do not use for initial region provisioning
  and IAM setup (use application-integration-basics) or diagnosing failed runs and logs (use application-integration-troubleshooting).
---

# Application Integration Authoring

Google Cloud Application Integration workflows are authored, versioned, published, and executed programmatically through the REST API (`https://integrations.googleapis.com/v1/...`) or the discovery-based Google API Python client (`googleapiclient.discovery.build("integrations", "v1")`).

There is no `gcloud integrations` command group, no Google-managed MCP server for Application Integration, and no documented Terraform resource for integrations or versions. Use `gcloud` only for authentication, enabling APIs, and IAM bindings. Use Terraform only for region provisioning (`google_integrations_client`), authentication profiles (`google_integrations_auth_config`), and Integration Connectors (`google_integration_connectors_connection`).

For initial project setup, region provisioning, and IAM role definitions, use the `application-integration-basics` skill. For diagnosing failed or stuck runs, execution logs, and quota errors, use the `application-integration-troubleshooting` skill.

## Attribution

**MUST READ**: Before executing any `gcloud` command, REST API call, or Python
discovery-client call, you MUST read
[Usage Attribution](references/attribution.md). For commands executed directly
in the terminal (never in generated scripts, Terraform, ADK agents, or user
code), prefix `gcloud` with
`CLOUDSDK_METRICS_REQUEST_ATTRIBUTION="agent-skills/1.0 (skill:application-integration-authoring)"`
and add `agent-skills/1.0 (skill:application-integration-authoring)` to the
`User-Agent` header of `curl` requests.

## Safety and Confirmation Rules

- **Read-only operations run freely**: `integrations.list`, `integrations:search`, `versions.list`, `versions.get`, `versions:download`, `authConfigs.list`, and `executions.list`.
- **Confirm before any state change or execution**: Before creating, uploading, patching, publishing, unpublishing, testing, executing, scheduling, or deleting an integration or version, or modifying IAM or auth configs, show the exact command and payload to the user and get explicit confirmation.
- **Host changes require approval.** Before installing packages (`pip install`) or changing global gcloud or credential state (`gcloud config set ...` such as `auth/impersonate_service_account`, `gcloud auth application-default login` / `set-quota-project`), show the exact command and wait for the user's approval.
- **Never store secrets in config variables**: Config variables (`CONFIG_*`) are stored and exported in plain text. Always use authentication profiles (`projects.locations.authConfigs`) or the Secret Manager access task for credentials.

## Prerequisites Checklist

1. **Install Google Cloud CLI**: Follow [Install the Google Cloud CLI](https://docs.cloud.google.com/sdk/docs/install-sdk.md.txt) if `gcloud` is not installed.
2. **Billing and project**: Ensure the Google Cloud project has an active billing account attached (required even when usage stays within the free tier), then set the target project (changes global gcloud state; get the user's approval first):
   ```bash
   gcloud config set project PROJECT_ID
   ```
3. **Enable required APIs**:
   ```bash
   gcloud services enable integrations.googleapis.com connectors.googleapis.com secretmanager.googleapis.com
   ```
4. **Provision the region**: Application Integration is regional: confirm the target region is supported on [Application Integration locations](https://docs.cloud.google.com/application-integration/docs/locations.md.txt) and use `us-central1` as a well-supported default when the user has no preference. The region is the `LOCATION` in every REST path; no `gcloud` default-region setting applies to Application Integration. The target `LOCATION` must be provisioned via the Cloud console or `POST .../clients:provision` before authoring integrations (see `application-integration-basics`).
5. **Authenticate**:
   - For `curl`: run `gcloud auth login` (changes host or credential state; get the user's approval first) and pass `-H "Authorization: Bearer $(gcloud auth print-access-token)"`.
   - For the Python client (install with `pip install "google-api-python-client>=2.100.0,<3" "google-auth>=2.20.0,<3"`): run `gcloud auth application-default login` and `gcloud auth application-default set-quota-project PROJECT_ID` (or set `GOOGLE_APPLICATION_CREDENTIALS` for a service account) (changes host or credential state; get the user's approval first).
   - For service account impersonation: run `gcloud config set auth/impersonate_service_account SA_EMAIL` (requires `roles/iam.serviceAccountTokenCreator`) (changes host or credential state; get the user's approval first).
6. **Verify IAM roles**:
   - Create, upload, or edit drafts: `roles/integrations.integrationEditor` (covers `versions:upload`, which needs `integrations.integrationVersions.create`, and `versions:publish`)
   - Publish or unpublish: `roles/integrations.integrationDeployer` or `roles/integrations.integrationEditor` (`roles/integrations.integrationDeployer` alone can publish an existing version but cannot upload via `versions:upload`), plus `roles/integrations.serviceAgent` granted to the Application Integration service agent (`service-PROJECT_NUMBER@gcp-sa-integrations.iam.gserviceaccount.com`)
   - Invoke integrations: `roles/integrations.integrationInvoker`
   - Act as the run-as service account: integrations created on or after October 15, 2026 with any trigger other than an API or Private trigger (for example Schedule, Cloud Scheduler, Cloud Pub/Sub, Salesforce, or Connector Event; Private triggers are exempt like API triggers, so a sub-integration whose only trigger is Private can be published without `runAsServiceAccount`) cannot be tested or published unless `runAsServiceAccount` is set (and region governance requires it for all integrations); whenever `runAsServiceAccount` is set, the user publishing or testing the version needs `roles/iam.serviceAccountUser` on it (and at runtime, the invoking caller or trigger service account needs `roles/iam.serviceAccountUser` on it).

## Decision Flow

| Goal | Action | Endpoint / Method |
| :--- | :--- | :--- |
| Inspect existing integrations in a region | List integrations, then list versions | `GET .../integrations` then `GET .../versions` |
| Export an integration version to source control | Download version JSON | `GET .../versions/VERSION_ID:download?fileFormat=JSON` |
| Create an integration or add a new `DRAFT` version from JSON | Upload version JSON (creates the integration if it does not exist, or adds a new `DRAFT` version; still needs `:publish`) | `POST .../integrations/INTEGRATION_NAME/versions:upload` |
| Create a brand-new integration and fail on a name clash | Create first `DRAFT` version with `newIntegration=true` (returns `ALREADY_EXISTS` if `INTEGRATION_NAME` already exists) | `POST .../integrations/INTEGRATION_NAME/versions?newIntegration=true` |
| Edit an existing `DRAFT` version | Check `lockHolder`, then patch or upload | `PATCH .../versions/VERSION_ID?updateMask=...` |
| Edit an `ACTIVE` (published) integration | Upload or create a new `DRAFT` version | `POST .../integrations/INTEGRATION_NAME/versions:upload` |
| Externalize environment-specific URLs or IDs | Define `CONFIG_<NAME>` and supply at publish | `integrationConfigParameters` + `versions:publish` |
| Store API keys, OAuth credentials, or certs | Create an authentication profile | `POST .../authConfigs` |
| Test an integration before production | Publish to a non-production project and invoke `:execute` | `POST .../versions/VERSION_ID:publish` then `POST .../integrations/INTEGRATION_NAME:execute` |
| Deploy a `DRAFT` to serve live traffic | Publish version with `configParameters` | `POST .../versions/VERSION_ID:publish` |
| Invoke a published integration synchronously | Call `:execute` with `api_trigger/TRIGGER_NAME` | `POST .../integrations/INTEGRATION_NAME:execute` |
| Invoke a published integration asynchronously | Call `:schedule` with `scheduleTime` | `POST .../integrations/INTEGRATION_NAME:schedule` |
| Promote a version across projects (CI/CD) | Download JSON -> Upload to target -> Publish | `:download` -> `:upload` -> `:publish` |

See [references/rest-api-cheatsheet.md](references/rest-api-cheatsheet.md) for full request parameters, query filters, and IAM permissions for each method.

## Core Authoring Workflow

### 1. List Integrations and Download a Version

List integrations in `LOCATION` and list versions for a specific `INTEGRATION_NAME`:

```bash
TOKEN="$(gcloud auth print-access-token)"

# List integrations in the region
curl -sS -H "Authorization: Bearer ${TOKEN}" \
  "https://integrations.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/integrations?pageSize=50"

# List versions (ordered by most recently modified)
curl -sS -H "Authorization: Bearer ${TOKEN}" \
  "https://integrations.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/integrations/INTEGRATION_NAME/versions?orderBy=last_modified_time%20desc"
```

Download a specific version (`VERSION_ID` is the UUID at the end of the version's `name` field) as portable JSON:

```bash
curl -sS -H "Authorization: Bearer ${TOKEN}" \
  "https://integrations.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/integrations/INTEGRATION_NAME/versions/VERSION_ID:download?fileFormat=JSON" \
  | jq -r '.content' > integration-version.json
```

### 2. Understand the `IntegrationVersion` Structure

An `IntegrationVersion` JSON object contains four primary arrays and version-level settings:

- `triggerConfigs`: Entry points that start the workflow. Each entry requires a unique `triggerNumber`, plus `triggerType` (such as `API` or `PRIVATE_TRIGGER`), optional `triggerId` (auto-generated from `properties` if omitted; for API triggers: `api_trigger/TRIGGER_NAME`), and `startTasks` pointing to the first `taskId`.
- `taskConfigs`: Units of work. Each entry needs `task` (the task type, such as `EmailTask` in the public upload sample, or `FieldMappingTask` in a discovery enum description), a unique `taskId`, `parameters`, `nextTasks`, and optional `failurePolicy` or `errorCatcherId`.
- `integrationParameters`: Input, output, and transient variables (`key`, `dataType` such as `STRING_VALUE` or `JSON_VALUE`, `inputOutputType` of `IN`, `OUT`, `IN_OUT`, or `IN_OUT_TYPE_UNSPECIFIED`, and `defaultValue`).
- `integrationConfigParameters`: Environment-specific config variable definitions (`parameter` with key `` `CONFIG_<NAME>` `` and `parameter.defaultValue`; a top-level `value` in uploaded or created draft JSON is discarded, so per-environment values go in `configParameters` at publish).
- `runAsServiceAccount`: Dedicated user-managed service account email. When set and no authentication profile (`authConfig`) is configured on the task, it is used to generate the auth token for Connector (`Connectors`), REST (`Call REST Endpoint`), and Cloud Function tasks; an authentication profile configured on the task takes precedence over `runAsServiceAccount`.

Always use `triggerConfigs`, `taskConfigs`, and `integrationParameters`. Never use `triggerConfigsInternal`, `taskConfigsInternal`, or `integrationParametersInternal` because they are deprecated. See [references/integration-version-json.md](references/integration-version-json.md) for field schemas, `ValueType` shapes, and a minimal `IntegrationVersion` JSON template.

### 3. Create or Upload a `DRAFT` Version

Each integration allows up to 100 versions and 100 tasks, and `INTEGRATION_NAME` can be at most 64 characters. Calling `versions:upload` creates a new `DRAFT` version—creating the integration automatically if `INTEGRATION_NAME` does not exist yet, or adding the next `DRAFT` version if it already exists (for example, uploading onto version 5 creates version 6). The uploaded version is in `DRAFT` state and still requires `versions:publish` to serve traffic. Use `POST .../versions?newIntegration=true` (passing an `IntegrationVersion` JSON body) only when you explicitly want the call to fail with `ALREADY_EXISTS` if `INTEGRATION_NAME` already exists.

```bash
# Upload integration-version.json as a new DRAFT version
PAYLOAD="$(jq -n --rawfile content integration-version.json '{content: $content, fileFormat: "JSON"}')"

curl -sS --fail-with-body -X POST \
  -H "Authorization: Bearer $(gcloud auth print-access-token)" \
  -H "Content-Type: application/json" \
  -d "${PAYLOAD}" \
  "https://integrations.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/integrations/INTEGRATION_NAME/versions:upload"
```

Capture the new `VERSION_ID` from `.integrationVersion.name` in the response (`projects/PROJECT_ID/locations/LOCATION/integrations/INTEGRATION_NAME/versions/VERSION_ID`).

### 4. Version States and Edit-Lock Rules

| State | Meaning | Editable? | Can Serve Triggers? |
| :--- | :--- | :--- | :--- |
| `DRAFT` | Version actively being edited; its edit lock is held by its author (`lockHolder` email) for 15 minutes from the last update | Yes (only by `lockHolder`) | No |
| `ACTIVE` | Published version serving live traffic | No | Yes |
| `SNAPSHOT` | Prior draft (when another author takes over in the console) or unpublished version (`PREVIOUSLY_PUBLISHED`) | No | No |
| `ARCHIVED` | Soft-deleted via `versions.delete` (no undelete; listed as `DELETED` on the Integration versions documentation page) | No | No |

- **Edit-lock enforcement**: A `DRAFT` version's edit lock is held by its author (`lockHolder`). Calling `versions:publish` or `versions.delete` on a `DRAFT` fails if the caller is not the `lockHolder` (`versions:publish` and `versions.delete` release any existing lock when they succeed).
- **No v1 lock-takeover API**: `takeoverEditLock` does **not** exist on `projects.locations.integrations.versions` in the v1 REST API (it only exists on `versions.testCases`). If a `DRAFT` is locked by another user, wait 15 minutes from `updateTime` for the lock to expire automatically, or click **Take Over** in the Cloud console (which converts the existing draft to `SNAPSHOT` and creates a new `DRAFT`).

### 5. Config Variables vs Authentication Profiles

- **Config variables (`CONFIG_<NAME>`)**: Use for non-secret environment values (backend hostnames, Pub/Sub topics, connection names). Define them in `integrationConfigParameters` on the draft (putting any default in `parameter.defaultValue`, because a top-level `value` on a draft is discarded) and pass their per-environment values in `configParameters` when calling `versions:publish`. **Gotcha**: Keys in `configParameters` at publish must **exactly match** a key in `integrationConfigParameters`, backticks included (for example, `` "`CONFIG_target_url`" ``); unknown keys are **silently ignored**, not rejected (`versions:publish` returns 200 and the default stays). Config variables cannot configure Integration Connectors entity operations or actions.
- **Authentication profiles (`authConfigs`)**: Use for API keys, OAuth 2.0 credentials, JWTs, OIDC tokens, SSL/TLS certificates, and service accounts. Auth profiles are regional resources (`projects/PROJECT_ID/locations/LOCATION/authConfigs/AUTH_CONFIG_ID`) and are **not** included when you download an integration version. Create them in each target project via `POST .../authConfigs` or Terraform `google_integrations_auth_config`.

### 6. Test, Publish, and Unpublish

- **Recommended testing path**: Test integrations by publishing the version in a non-production project (`versions:publish`) and invoking `integrations:execute` there.
  - **Note on `integrations:test`**: The v1 REST API includes `POST .../integrations/INTEGRATION_NAME:test` for testing a `DRAFT`, which requires `TestIntegrationsRequest.clientId` ("Required. This is used to identify the client on whose behalf the event will be executed."), but the public documentation does not specify what value to pass. Do not invent a `clientId` value; publish to a non-production project and call `:execute` instead. (Draft testing also cannot run `Approval`, `Suspend`, or `Timer` tasks, and Call REST Endpoint authentication profile changes only take effect after publishing.)
- **Publish (`versions:publish`)**: Deploys the version as `ACTIVE` and releases any edit lock (fails if the version is already `ACTIVE` or `ARCHIVED`, or if it is a `DRAFT` whose `lockHolder` differs from the caller). Any previously `ACTIVE` version is automatically unpublished, and dependent services switch to the newly published version.
  - **Gotcha**: Publishing a new version automatically cancels all suspended executions of the previous version.
  - **Gotcha**: Due to eventual consistency, the previous version can continue running for up to 10 minutes after a new version is published.
- **Unpublish (`versions:unpublish`)**: Moves the `ACTIVE` version to `SNAPSHOT` (tagged `PREVIOUSLY_PUBLISHED`; fails if the version is not `ACTIVE`) and stops triggers and dependent services.

```bash
# Publish VERSION_ID and supply config variable values (keys must exactly match integrationConfigParameters keys, backticks included; unknown keys are silently ignored)
curl -sS --fail-with-body -X POST \
  -H "Authorization: Bearer $(gcloud auth print-access-token)" \
  -H "Content-Type: application/json" \
  -d '{"configParameters": {"`CONFIG_backend_url`": "https://api.example.com"}}' \
  "https://integrations.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/integrations/INTEGRATION_NAME/versions/VERSION_ID:publish"
```

### 7. Execute (Sync) vs Schedule (Async)

Only an `ACTIVE` (published) version can be invoked via `execute` or `schedule`. For API triggers, `triggerId` is always `api_trigger/TRIGGER_NAME` (where `TRIGGER_NAME` is at most 64 characters). Passing `-` as `INTEGRATION_NAME` in `execute` runs all published integrations in that region that share the `triggerId`.

| Method | Mode | Max Timeout | Max API Input | Key Request Fields | Key Response Fields |
| :--- | :--- | :--- | :--- | :--- | :--- |
| `integrations:execute` | Sync | 2 minutes | 8 MB | `triggerId`, `inputParameters`, `requestId`, `doNotPropagateError` | `executionId`, `outputParameters`, `parameters` |
| `integrations:schedule` | Async | 10 minutes | Not documented | `triggerId`, `scheduleTime` (RFC 3339), `inputParameters`, `requestId`, `userGeneratedExecutionId` | `executionInfoIds[]` |

- **Reading `outputParameters` and `executionId`**: In `ExecuteIntegrationsResponse`, `executionId` identifies the run, and `outputParameters` is a JSON object of output variables (system-generated keys such as `` `ExecutionId` `` are wrapped in backticks).
- **HTTP 200 does not prove every task succeeded**: If `doNotPropagateError` is `true`, or a task uses failure policy `IGNORE` or `NONE` with an alternate path, the HTTP call returns `200 OK` even when a task failed. Always verify the execution record via `executions.list?filter=execution_id="EXECUTION_ID"` (checking `executionDetails.state`, each task's `taskExecutionState`, and `ErrorInfo` in `Execution.responseParameters`; when `doNotPropagateError` is `true`, errors are also returned in event parameters as `PostWithTriggerIdExecutionException`). Do not rely on the legacy/deprecated `executionFailed` field.

See [references/triggers-and-execution.md](references/triggers-and-execution.md) for all trigger types, `ValueType` input formatting, OpenAPI spec generation, and suspension lifting and approval resolution.

## End-to-End Version and API Workflow Examples

In downloaded and uploaded `IntegrationVersion` JSON, an `EmailTask` uses four customer-visible parameter keys inside `taskConfigs[].parameters`: `"To"` (`stringArray` of recipient addresses), `"Subject"` (`stringValue`), `"BodyFormat"` (`stringValue`, such as `"PLAIN_TEXT"`), and `"TextBody"` (`stringValue`). Both runnable examples below also set `"runAsServiceAccount": "RUN_AS_SA"` (replace `RUN_AS_SA` with your dedicated service account email, such as `order-workflow-sa@PROJECT_ID.iam.gserviceaccount.com`; projects with governance require a run-as service account to publish, and the caller needs `roles/iam.serviceAccountUser` on it). Executing an `EmailTask` sends a real email, so always confirm the recipient address (`RECIPIENT_EMAIL`) and each state-changing command (upload, publish, and execute) with the user before running.

### Example 1: Upload, Publish, and Invoke Workflow with `curl`

This example uploads a runnable `IntegrationVersion` JSON (`versions:upload` creates `INTEGRATION_NAME` automatically if it does not exist yet, or adds a new `DRAFT` version if it does), publishes the draft, and invokes `:execute`. The caller must hold `roles/iam.serviceAccountUser` on `RUN_AS_SA` (projects with governance require a run-as service account to publish). Because `EmailTask` sends real email, confirm `RECIPIENT_EMAIL` and get user confirmation before running the upload, publish, and execute calls.

```bash
set -euo pipefail
export PROJECT_ID="my-project"
export LOCATION="us-central1"
export INTEGRATION_NAME="order-webhook"
export TRIGGER_NAME="order_api"
TOKEN="$(gcloud auth print-access-token)"
BASE_URL="https://integrations.googleapis.com/v1/projects/${PROJECT_ID}/locations/${LOCATION}"

# 1. Write an IntegrationVersion JSON file (set RUN_AS_SA and confirm RECIPIENT_EMAIL with user first; caller needs roles/iam.serviceAccountUser on RUN_AS_SA)
cat <<'EOF' > /tmp/version.json
{
  "description": "API-triggered order notification integration",
  "runAsServiceAccount": "RUN_AS_SA",
  "triggerConfigs": [
    {
      "label": "API Trigger",
      "triggerType": "API",
      "triggerNumber": "1",
      "triggerId": "api_trigger/order_api",
      "properties": {"Trigger name": "order_api"},
      "startTasks": [{"taskId": "1"}]
    }
  ],
  "taskConfigs": [
    {
      "task": "EmailTask",
      "taskId": "1",
      "displayName": "Send Email",
      "taskExecutionStrategy": "WHEN_ALL_SUCCEED",
      "parameters": {
        "To": {"key": "To", "value": {"stringArray": {"stringValues": ["RECIPIENT_EMAIL"]}}},
        "Subject": {"key": "Subject", "value": {"stringValue": "Order notification for $orderId$"}},
        "BodyFormat": {"key": "BodyFormat", "value": {"stringValue": "PLAIN_TEXT"}},
        "TextBody": {"key": "TextBody", "value": {"stringValue": "Processing order $orderId$."}}
      }
    }
  ],
  "integrationParameters": [
    {
      "key": "orderId",
      "dataType": "STRING_VALUE",
      "inputOutputType": "IN_OUT",
      "defaultValue": {"stringValue": "ORD-0000"}
    }
  ]
}
EOF

# 2. Upload as a new DRAFT version — creates INTEGRATION_NAME if it does not exist yet (confirm with user first)
UPLOAD_BODY="$(jq -n --rawfile content /tmp/version.json '{content: $content, fileFormat: "JSON"}')"
VERSION_NAME="$(curl -sS --fail-with-body -X POST \
  -H "Authorization: Bearer ${TOKEN}" \
  -H "Content-Type: application/json" \
  -d "${UPLOAD_BODY}" \
  "${BASE_URL}/integrations/${INTEGRATION_NAME}/versions:upload" \
  | jq -r '.integrationVersion.name')"
VERSION_ID="${VERSION_NAME##*/}"
[[ -n "${VERSION_ID}" && "${VERSION_ID}" != "null" ]] || { echo "upload failed: ${VERSION_NAME}" >&2; exit 1; }

# 3. Publish the DRAFT version (confirm with user first)
curl -sS --fail-with-body -X POST \
  -H "Authorization: Bearer ${TOKEN}" \
  -H "Content-Type: application/json" \
  -d '{}' \
  "${BASE_URL}/integrations/${INTEGRATION_NAME}/versions/${VERSION_ID}:publish"

# 4. Invoke the published version synchronously — sends a real email to RECIPIENT_EMAIL (confirm with user first)
curl -sS --fail-with-body -X POST \
  -H "Authorization: Bearer ${TOKEN}" \
  -H "Content-Type: application/json" \
  -H "X-Server-Timeout: 120" \
  -d "{
    \"triggerId\": \"api_trigger/${TRIGGER_NAME}\",
    \"inputParameters\": {
      \"orderId\": {\"stringValue\": \"ORD-1001\"}
    }
  }" \
  "${BASE_URL}/integrations/${INTEGRATION_NAME}:execute" \
  | jq '{executionId, outputParameters}'
```

### Example 2: Python Discovery Client Workflow (Built from the API Reference)

No official Python sample is published on `docs.cloud.google.com`; the following workflow is built from the v1 API discovery document (`google-api-python-client`). The caller must hold `roles/iam.serviceAccountUser` on `RUN_AS_SA` (projects with governance require a run-as service account to publish). Because `EmailTask` sends real email, confirm `RECIPIENT_EMAIL` and each state-changing call (`upload`, `publish`, `execute`) with the user before running. Install dependencies first with `pip install "google-api-python-client>=2.100.0,<3" "google-auth>=2.20.0,<3"` (changes host or credential state; get the user's approval first).

```python
import json
from googleapiclient.discovery import build

PROJECT_ID = "PROJECT_ID"
LOCATION = "LOCATION"
INTEGRATION_NAME = "INTEGRATION_NAME"
TRIGGER_NAME = "TRIGGER_NAME"
RECIPIENT_EMAIL = "RECIPIENT_EMAIL"
parent = f"projects/{PROJECT_ID}/locations/{LOCATION}"
integration_path = f"{parent}/integrations/{INTEGRATION_NAME}"

service = build("integrations", "v1")
integrations_api = service.projects().locations().integrations()
versions_api = integrations_api.versions()

# 1. List existing integrations (read-only)
listed = integrations_api.list(parent=parent, pageSize=20).execute()
for item in listed.get("integrations", []):
    print(item["name"], "active=", item.get("active"))

# 2. Upload a DRAFT version — creates INTEGRATION_NAME if it does not exist yet (set RUN_AS_SA and confirm RECIPIENT_EMAIL and action with user before running; caller needs roles/iam.serviceAccountUser on RUN_AS_SA)
version_dict = {
    "description": "API-triggered order notification integration",
    "runAsServiceAccount": "RUN_AS_SA",
    "triggerConfigs": [{
        "label": "API Trigger",
        "triggerType": "API",
        "triggerNumber": "1",
        "triggerId": f"api_trigger/{TRIGGER_NAME}",
        "properties": {"Trigger name": TRIGGER_NAME},
        "startTasks": [{"taskId": "1"}],
    }],
    "taskConfigs": [{
        "task": "EmailTask",
        "taskId": "1",
        "displayName": "Send Email",
        "taskExecutionStrategy": "WHEN_ALL_SUCCEED",
        "parameters": {
            "To": {"key": "To", "value": {"stringArray": {"stringValues": [RECIPIENT_EMAIL]}}},
            "Subject": {"key": "Subject", "value": {"stringValue": "Order notification for $orderId$"}},
            "BodyFormat": {"key": "BodyFormat", "value": {"stringValue": "PLAIN_TEXT"}},
            "TextBody": {"key": "TextBody", "value": {"stringValue": "Processing order $orderId$."}},
        },
    }],
    "integrationParameters": [{
        "key": "orderId",
        "dataType": "STRING_VALUE",
        "inputOutputType": "IN_OUT",
        "defaultValue": {"stringValue": "ORD-0000"},
    }],
}
upload_resp = versions_api.upload(
    parent=integration_path,
    body={"content": json.dumps(version_dict), "fileFormat": "JSON"},
).execute()
version_name = upload_resp["integrationVersion"]["name"]

# 3. Publish the DRAFT version (confirm with user before running)
versions_api.publish(
    name=version_name,
    body={"configParameters": {}},
).execute()

# 4. Invoke the published version synchronously — sends a real email to RECIPIENT_EMAIL (confirm with user before running)
exec_resp = integrations_api.execute(
    name=integration_path,
    body={
        "triggerId": f"api_trigger/{TRIGGER_NAME}",
        "inputParameters": {"orderId": {"stringValue": "ORD-1001"}},
    },
).execute()
print("executionId:", exec_resp.get("executionId"))
print("outputParameters:", exec_resp.get("outputParameters"))
```

## Common Task Gotchas and Limits

- **Data limits**: Total cumulative integration data (including inputs and outputs) is capped at 30 MB. Above 10 MB, local execution logging is automatically disabled.
- **Data Mapping**: Input and output types must match (cast with `TO_STRING`, `TO_INT`, and so on). Always set a fallback value or null inputs fail the task.
- **Call REST Endpoint**: Reaches the public internet only (cannot reach VPC-internal hosts). Fails on HTTP 4xx and 5xx responses. Request max 20 MB, response max 34 MB, max 100 concurrent calls.
- **JavaScript**: Uses the V8 engine (Rhino was deprecated January 24, 2025). Never remove the `executesScript(event)` entrypoint. Max script request size is 25 MB.
- **Connectors task**: Requires an active Integration Connectors connection (billed separately). Timeout is 3 minutes; Application Integration quotas cap data to and from connections at 8 MB (Integration Connectors quotas list a 10 MB Connectors task payload limit; response max 20 MB).
- **Approval vs Suspend**: Approval tasks can be approved or rejected via `POST .../executions/EXECUTION_ID/suspensions/SUSPENSION_ID:resolve` with body `{"suspension": {"eventExecutionInfoId": "EXECUTION_ID", "integration": "INTEGRATION_NAME", "taskId": "TASK_ID", "state": "LIFTED"}}` (or `"REJECTED"`), which is the same call the Cloud console Approve/Reject buttons make and requires `integrations.suspensions.resolve`. Suspend tasks are resumed via `POST .../integrations/INTEGRATION_NAME/executions/EXECUTION_ID/suspensions/SUSPENSION_ID:lift` (where `-` can replace `INTEGRATION_NAME` and either `EXECUTION_ID` or `SUSPENSION_ID`, provided at least one of `EXECUTION_ID` or `SUSPENSION_ID` is concrete; accepts an optional `suspensionResult` defaulting to `Resolved`), which requires `integrations.suspensions.lift`. Listing suspensions (`suspensions.list`) requires `integrations.suspensions.list`. All three permissions are included in `roles/integrations.suspensionResolver` (and `roles/integrations.integrationAdmin`); resuming also requires `roles/iam.serviceAccountUser` on the integration's run-as service account, requires user confirmation first, and runs the remainder of the execution in async mode.
- **Loops and Sub-integrations**: For Each Loop and While Loop allow up to 8,000 iterations; For Each Parallel allows up to 10,000 iterations (default parallelism 50). For sub-integration calls (`Call Integration`, `For Each Loop`, `For Each Parallel`), child responses/output parameters are returned to the parent only in `SYNC` mode (`ASYNC` calls return no output parameters); avoid `SYNC` mode if the sub-integration exceeds 2 minutes or includes an Approval task.

See [references/tasks-and-gotchas.md](references/tasks-and-gotchas.md) for the full task catalog, limits, variable reference syntax, and retry strategies.

## Promoting Between Environments (CI/CD)

To promote an integration from development to staging or production:

1. Externalize environment-specific values (endpoints, project IDs, connection names) as `CONFIG_<NAME>` config variables.
2. Provision the target region, run-as service account, Integration Connectors connections, and authentication profiles (`authConfigs`) in the target project first (these infrastructure resources are not created by version uploads).
3. Download the tested version JSON (`versions:download?fileFormat=JSON`), commit it to Git alongside per-environment config files, rewrite `.runAsServiceAccount` to the target environment's run-as service account (`jq --arg sa "$RUN_AS_SA" '.runAsServiceAccount = $sa' integration.json > integration.env.json`) before uploading, and run `versions:upload` + `versions:publish` from Cloud Build or your CI runner (`versions:upload` creates the integration automatically in the target project if it does not exist yet, producing a `DRAFT` that `:publish` activates).

See [references/cicd-promotion.md](references/cicd-promotion.md) for the complete promotion checklist and a ready-to-use Cloud Build pipeline.

## Cleanup and Cost Management

- **Pricing**: An active billing account must be attached to the project even when usage stays within the monthly free tier. Application Integration offers a monthly free tier for executions, data processed, and Google service connector nodes, after which executions, data processed, and Integration Connectors nodes incur charges. Review current thresholds and rates on the [Application Integration pricing page](https://cloud.google.com/application-integration/pricing) and estimate costs with the Google Cloud Pricing Calculator.
- **Unpublish to stop triggers**: Run `POST .../versions/VERSION_ID:unpublish` (after user confirmation) to stop scheduled, Pub/Sub, or API triggers from firing.
- **Delete versions or integrations**: `DELETE .../versions/VERSION_ID` archives a single version (deleting all versions deletes the integration). `DELETE .../integrations/INTEGRATION_NAME` permanently deletes the integration and all its versions.
- **Connector nodes**: Unpublishing or deleting an integration does not delete Integration Connectors connections. Delete unused connections at `https://console.cloud.google.com/connectors/connections` to stop hourly node charges.

## Reference Guides

- [Usage Attribution](references/attribution.md): Usage attribution for `gcloud` CLI commands, direct `curl` REST calls, and Python discovery-client snippets run in the terminal.
- [REST API Cheatsheet](references/rest-api-cheatsheet.md): v1 and v2 endpoints, parameters, filters, and IAM permissions.
- [IntegrationVersion JSON Reference](references/integration-version-json.md): Schema for `triggerConfigs`, `taskConfigs`, `integrationParameters`, `ValueType`, and config variables.
- [Triggers and Execution Reference](references/triggers-and-execution.md): Trigger types, `triggerId` formats, `:execute` vs `:schedule`, OpenAPI generation, and lifting or resolving suspensions.
- [Tasks and Gotchas Reference](references/tasks-and-gotchas.md): Task-by-task rules, quotas, variable reference syntax, and error handling strategies.
- [CI/CD Promotion Reference](references/cicd-promotion.md): Cross-project promotion checklist, environment config pattern, and Cloud Build workflow.
references/
attribution.md 5.0 KB
# Usage Attribution

**MUST READ**: Before executing any `gcloud` command, REST API call, or Python
discovery-client call with this skill, follow these usage attribution
instructions. Tag every command you execute directly in the terminal so usage
can be attributed. The tag identifies only the skill and its version; it carries
no user data.

-   **`gcloud` CLI Commands**: Prefix every `gcloud` invocation, whatever the
    subcommand (in this skill, generic tasks such as enabling APIs, IAM, and
    `gcloud logging read`), with the metrics environment variable. Set it inline
    on each command because shell state may not persist between commands:

    ```bash
    CLOUDSDK_METRICS_REQUEST_ATTRIBUTION="agent-skills/1.0 (skill:application-integration-authoring)" \
    gcloud <command> [flags]
    ```

    Do not use `gcloud config set` for this: it would persist beyond the current
    task and mislabel unrelated usage. `gcloud auth print-access-token` never
    needs the prefix, whether it runs on its own (for example to check
    credentials), inline as `$(gcloud auth print-access-token)`, or assigned
    first, as in `TOKEN="$(gcloud auth print-access-token)"`: it only fetches a
    credential, and the `curl` requests that use the token carry the attribution
    `User-Agent` header themselves. Every other `gcloud` command you run needs
    the prefix, including read-only and local ones such as
    `gcloud services list` or `gcloud config list`.

-   **Direct HTTP and REST Requests (`curl`)**: Application Integration has no
    Google-managed MCP server and no `gcloud integrations` command group; calls
    go to `https://integrations.googleapis.com/v1/...` (and
    `https://connectors.googleapis.com/...`). Add the header
    `-H "User-Agent: agent-skills/1.0 (skill:application-integration-authoring)"`
    to every `curl` call you run directly. `curl` sends its own default
    `User-Agent` (`curl/<version>`) only when none is given, so an explicit
    `-H "User-Agent: ..."` replaces it; if a `User-Agent` header is already
    specified, append this string to the end of it rather than overwriting
    existing `User-Agent` data — the collection pipeline parses the
    `agent-skills/<version>` and `skill:<name>` tokens, so any rewording breaks
    attribution:

    ```bash
    curl -sS -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      -H "User-Agent: agent-skills/1.0 (skill:application-integration-authoring)" \
      "https://integrations.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/integrations"
    ```

-   **Python discovery client run directly by you**: When you yourself run a
    one-off Python snippet in the terminal that uses
    `googleapiclient.discovery.build("integrations", "v1")` (or
    `build("connectors", "v1")`), wrap the authorized HTTP object with
    `googleapiclient.http.set_user_agent`, which adds the given string to the
    `User-Agent` header of every request made through that object (the client
    library's own `(gzip)` marker stays after it). Use this pattern
    (`google-auth-httplib2` is installed as a dependency of
    `google-api-python-client`):

    ```python
    import google.auth
    import google_auth_httplib2
    from googleapiclient import discovery
    from googleapiclient.http import set_user_agent

    credentials, _ = google.auth.default(
        scopes=["https://www.googleapis.com/auth/cloud-platform"]
    )
    http = set_user_agent(
        google_auth_httplib2.AuthorizedHttp(credentials),
        "agent-skills/1.0 (skill:application-integration-authoring)",
    )
    service = discovery.build("integrations", "v1", http=http)
    ```

    Do not pass both `http=` and `credentials=` to `build`; because `http=`
    bypasses the scoping `build` normally applies, request the
    `https://www.googleapis.com/auth/cloud-platform` scope in
    `google.auth.default` as shown.

-   **Constraint for Generated Code**: The tracking prefix, `User-Agent` header,
    and `set_user_agent` wrapper are strictly for commands you execute directly
    in the terminal. Do NOT include them in code provided to the user for their
    own repositories, including generated scripts, CI/CD pipelines, Terraform
    configurations, ADK agents (including `ApplicationIntegrationToolset` code),
    Python modules, or integration version JSON.

-   **No host or credential changes**: The attribution is per command only. It
    is not a host change and does not need the approval required by the skill's
    "Host changes require approval" rule, because it never persists anything.
    Never persist it with `gcloud config set metrics/request_attribution`, by
    exporting the variable in a shell profile, or in `~/.curlrc`; those would be
    host changes (needing the user's approval under that rule) and would
    mislabel unrelated usage.

-   **User Opt-Out**: If the user asks to disable or remove tracking or
    attribution tags, omit the `CLOUDSDK_METRICS_REQUEST_ATTRIBUTION` variable,
    custom `User-Agent` suffix, and `set_user_agent` wrapper from all commands.
cicd-promotion.md 11.4 KB
# CI/CD Promotion Reference

This guide explains how to promote Application Integration versions across projects and environments (such as development, staging, and production) using `versions:download`, `versions:upload`, `versions:publish`, and Cloud Build.

- [What Travels in a Downloaded Version vs What Does Not](#what-travels-in-a-downloaded-version-vs-what-does-not): Lines 11-23
- [Environment Parameterization Pattern](#environment-parameterization-pattern): Lines 24-43
- [Step-by-Step Promotion Workflow](#step-by-step-promotion-workflow): Lines 44-103
- [Cloud Build Pipeline Example (`cloudbuild.yaml`)](#cloud-build-pipeline-example-cloudbuildyaml): Lines 104-155
- [Post-Promotion Checks and Rollout Gotchas](#post-promotion-checks-and-rollout-gotchas): Lines 156-161

## What Travels in a Downloaded Version vs What Does Not

Downloading an integration version (`GET .../versions/VERSION_ID:download?fileFormat=JSON`) produces a portable JSON representation, but external dependencies must be created separately in each target project.

| Included in `versions:download` JSON | NOT Included (Must Provision in Target Project) |
| :--- | :--- |
| `triggerConfigs` (trigger types, IDs, properties) | Regional client provisioning (`clients:provision` or `google_integrations_client`) |
| `taskConfigs` (tasks, parameters, edges, retry policies) | Integration Connectors connections (`google_integration_connectors_connection`) |
| `integrationParameters` (inputs, outputs, defaults) | Authentication profiles (`projects.locations.authConfigs` or `google_integrations_auth_config`) |
| `integrationConfigParameters` (config variable definitions) | Run-as service account IAM resources and role bindings (`roles/iam.serviceAccountUser`) |
| `runAsServiceAccount` (**travels in JSON, but must be rewritten** to the target environment's run-as service account email before uploading) | Functional test cases (`versions.testCases` — download/upload separately) |
| `errorCatcherConfigs`, `cloudLoggingDetails`, `description` | - |

## Environment Parameterization Pattern

1. **Use config variables (`CONFIG_<NAME>`) and per-environment `RUN_AS_SA` settings**:
   - Externalize environment-specific backend URLs, project IDs, Pub/Sub topic paths, and Integration Connectors connection names as `CONFIG_<NAME>` in `integrationConfigParameters`.
   - Because `IntegrationVersion.runAsServiceAccount` travels in `versions:download` JSON with the source environment's service account email, store `RUN_AS_SA` alongside `configParameters` in each per-environment config file (for example, `configs/staging.json` and `configs/prod.json`), rewrite `.runAsServiceAccount` before uploading, and pass `{configParameters}` to `versions:publish` (**gotcha**: keys in `configParameters` must **exactly match** a key in `integrationConfigParameters`, backticks included, such as `` "`CONFIG_target_url`" ``; unknown keys are **silently ignored**, not rejected—publish returns 200 and the default stays):
     ```json
     {
       "RUN_AS_SA": "order-workflow-sa@my-staging-project.iam.gserviceaccount.com",
       "configParameters": {
         "`CONFIG_backend_url`": "https://staging-api.example.com",
         "`CONFIG_pubsub_topic`": "projects/my-staging-project/topics/orders"
       }
     }
     ```
2. **Never store secrets in config variables**:
   - Config variables are stored and exported in plain text, and variable masking does not redact downloaded files.
   - Store secrets in regional authentication profiles (`authConfigs`) or fetch them at runtime with the Secret Manager access task.
3. **Know the connector limitation**:
   - Config variables cannot configure Integration Connectors entity operations or actions. Keep connection names and schemas aligned across environments.

## Step-by-Step Promotion Workflow

### Step 1: Export from the Source Environment

Download the verified version from the development project and save the inner `.content` JSON to your repository:

```bash
TOKEN="$(gcloud auth print-access-token)"
curl -sS -H "Authorization: Bearer ${TOKEN}" \
  "https://integrations.googleapis.com/v1/projects/SOURCE_PROJECT_ID/locations/LOCATION/integrations/INTEGRATION_NAME/versions/VERSION_ID:download?fileFormat=JSON" \
  | jq -r '.content' > integrations/INTEGRATION_NAME/integration.json
```

### Step 2: Prepare the Target Environment

Before running the promotion pipeline in `TARGET_PROJECT_ID`:

- Enable `integrations.googleapis.com`, `connectors.googleapis.com`, and `secretmanager.googleapis.com`.
- Provision `LOCATION` in `TARGET_PROJECT_ID` (see the `application-integration-basics` skill).
- Create the required Integration Connectors connections, authentication profiles (`authConfigs`), and the integration's target run-as service account (`RUN_AS_SA`) in `TARGET_PROJECT_ID` (`IntegrationVersion.runAsServiceAccount` travels in `versions:download` JSON and must be rewritten to `RUN_AS_SA` before uploading).
- Grant the CI runner service account (such as the Cloud Build service account):
  - Grant `roles/integrations.integrationEditor` (covers `versions:upload` and `versions:publish`); `roles/integrations.integrationDeployer` alone can publish but cannot upload (it holds `integrations.integrationVersions.list`, `get`, and `deploy`, not `integrations.integrationVersions.create`, which `versions:upload` needs)
  - `roles/iam.serviceAccountUser` on the integration's `runAsServiceAccount` (required for the principal publishing or testing the version whenever `runAsServiceAccount` is set)

### Step 3: Upload and Publish in the Target Environment

Before uploading to `TARGET_PROJECT_ID`, rewrite `.runAsServiceAccount` in the downloaded JSON to the target environment's run-as service account (`RUN_AS_SA`). Calling `versions:upload` creates `INTEGRATION_NAME` automatically in `TARGET_PROJECT_ID` if it does not exist yet (or adds a new `DRAFT` version if it already exists), so no separate "create integration beforehand" step is needed. Because `versions:upload` creates a `DRAFT`, follow it with `versions:publish` to activate the uploaded version with the target environment's `configParameters`. Confirm the exact commands and payloads with the user before running any upload or publish call interactively.

```bash
set -euo pipefail
TOKEN="$(gcloud auth print-access-token)"
BASE_URL="https://integrations.googleapis.com/v1/projects/TARGET_PROJECT_ID/locations/LOCATION/integrations/INTEGRATION_NAME"
RUN_AS_SA="$(jq -r '.RUN_AS_SA' configs/prod.json)"

# 1. Rewrite runAsServiceAccount for the target environment and wrap into UploadIntegrationVersionRequest
jq --arg sa "${RUN_AS_SA}" '.runAsServiceAccount = $sa' \
  integrations/INTEGRATION_NAME/integration.json > /tmp/integration.env.json

UPLOAD_PAYLOAD="$(jq -n --rawfile content /tmp/integration.env.json \
  '{content: $content, fileFormat: "JSON"}')"

# 2. Upload the DRAFT version (creates INTEGRATION_NAME if it does not exist yet) and extract its VERSION_ID (confirm with user before running)
VERSION_NAME="$(curl -sS --fail-with-body -X POST \
  -H "Authorization: Bearer ${TOKEN}" \
  -H "Content-Type: application/json" \
  -d "${UPLOAD_PAYLOAD}" \
  "${BASE_URL}/versions:upload" \
  | jq -r '.integrationVersion.name')"
VERSION_ID="${VERSION_NAME##*/}"
[[ -n "${VERSION_ID}" && "${VERSION_ID}" != "null" ]] || { echo "upload failed: ${VERSION_NAME}" >&2; exit 1; }

# 3. Publish the uploaded version with environment-specific configParameters (keys must exactly match integrationConfigParameters keys, backticks included, or unknown keys are silently ignored; confirm with user before running)
PUBLISH_PAYLOAD="$(jq '{configParameters}' configs/prod.json)"
curl -sS --fail-with-body -X POST \
  -H "Authorization: Bearer ${TOKEN}" \
  -H "Content-Type: application/json" \
  -d "${PUBLISH_PAYLOAD}" \
  "${BASE_URL}/versions/${VERSION_ID}:publish"
```

## Cloud Build Pipeline Example (`cloudbuild.yaml`)

This Cloud Build pipeline rewrites `.runAsServiceAccount` to `_RUN_AS_SA`, uploads `integration.env.json` to `_INTEGRATION_NAME` in `_TARGET_PROJECT_ID` (`versions:upload` creates `_INTEGRATION_NAME` automatically if it does not exist yet, or adds a new `DRAFT` version if it does), and publishes that `DRAFT` using `_CONFIG_FILE`. Trigger it after pull request approval or release tag creation.

```yaml
steps:
  - name: "gcr.io/google.com/cloudsdktool/google-cloud-cli:slim"
    entrypoint: "bash"
    args:
      - "-c"
      - |
        set -euo pipefail
        apt-get update -qq && apt-get install -y -qq jq >/dev/null

        TOKEN="$$(gcloud auth print-access-token)"
        BASE_URL="https://integrations.googleapis.com/v1/projects/${_TARGET_PROJECT_ID}/locations/${_LOCATION}/integrations/${_INTEGRATION_NAME}"

        echo "Rewriting runAsServiceAccount to ${_RUN_AS_SA} and uploading ${_INTEGRATION_NAME} to ${_TARGET_PROJECT_ID} (${_LOCATION})..."
        jq --arg sa "${_RUN_AS_SA}" '.runAsServiceAccount = $$sa' "${_INTEGRATION_FILE}" > /tmp/integration.env.json
        UPLOAD_PAYLOAD="$$(jq -n --rawfile content /tmp/integration.env.json '{content: $$content, fileFormat: "JSON"}')"
        UPLOAD_RESP="$$(curl -sS --fail-with-body -X POST \
          -H "Authorization: Bearer $${TOKEN}" \
          -H "Content-Type: application/json" \
          -d "$${UPLOAD_PAYLOAD}" \
          "$${BASE_URL}/versions:upload")"

        VERSION_NAME="$$(echo "$${UPLOAD_RESP}" | jq -r '.integrationVersion.name')"
        VERSION_ID="$${VERSION_NAME##*/}"
        [[ -n "$${VERSION_ID}" && "$${VERSION_ID}" != "null" ]] || { echo "upload failed: $${VERSION_NAME}" >&2; exit 1; }
        echo "Created draft version: $${VERSION_ID}"

        echo "Publishing version $${VERSION_ID} with ${_CONFIG_FILE}..."
        PUBLISH_PAYLOAD="$$(jq '{configParameters}' "${_CONFIG_FILE}")"
        curl -sS --fail-with-body -X POST \
          -H "Authorization: Bearer $${TOKEN}" \
          -H "Content-Type: application/json" \
          -d "$${PUBLISH_PAYLOAD}" \
          "$${BASE_URL}/versions/$${VERSION_ID}:publish"
        echo "Published version $${VERSION_ID} successfully."

substitutions:
  _TARGET_PROJECT_ID: "PROJECT_ID"
  _LOCATION: "us-central1"
  _INTEGRATION_NAME: "INTEGRATION_NAME"
  _INTEGRATION_FILE: "integrations/INTEGRATION_NAME/integration.json"
  _CONFIG_FILE: "configs/staging.json"
  _RUN_AS_SA: "order-workflow-sa@PROJECT_ID.iam.gserviceaccount.com"

options:
  logging: CLOUD_LOGGING_ONLY
```

## Post-Promotion Checks and Rollout Gotchas

- **Eventual consistency (up to 10 minutes)**: After `versions:publish` succeeds, the previous `ACTIVE` version can continue handling traffic for up to 10 minutes while the new version propagates across the region.
- **Suspended executions are canceled**: Publishing a new version automatically cancels all suspended executions (`Suspend` or `Approval` tasks) waiting on the previous version. Check `executions.list?filter=state%3DSUSPENDED` before promoting to production if long-running pauses are active.
- **Version cap (100 versions max)**: Each integration supports at most 100 versions. In high-frequency CI pipelines, archive old unused snapshots with `DELETE .../versions/OLD_VERSION_ID` (confirm with the user before deleting any version interactively) so uploads do not fail at the 100-version limit.
- **Smoke testing**: After promotion, run an API trigger smoke check via `integrations:execute` (reading `outputParameters` and verifying `executionDetails.state` and per-task states via `executions.list?filter=execution_id%3D%22EXECUTION_ID%22`) or upload and run functional test cases via `versions.testCases:execute`.
integration-version-json.md 14.4 KB
# IntegrationVersion JSON Reference

This guide details the `IntegrationVersion` JSON schema used by `versions.create`, `versions.patch`, `versions:upload`, and `versions:download` in the v1 REST API.

- [Top-Level `IntegrationVersion` Fields](#top-level-integrationversion-fields): Lines 12-37
- [Trigger Configuration (`TriggerConfig`)](#trigger-configuration-triggerconfig): Lines 38-55
- [Task Configuration (`TaskConfig`)](#task-configuration-taskconfig): Lines 56-74
- [Variables and `ValueType` (`IntegrationParameter`)](#variables-and-valuetype-integrationparameter): Lines 75-108
- [Config Variables (`IntegrationConfigParameter`)](#config-variables-integrationconfigparameter): Lines 109-118
- [Minimal `IntegrationVersion` JSON Template](#minimal-integrationversion-json-template): Lines 119-196

## Top-Level `IntegrationVersion` Fields

| Field | Mode | Description |
| :--- | :--- | :--- |
| `name` | Output only | Resource path: `projects/PROJECT_ID/locations/LOCATION/integrations/INTEGRATION_NAME/versions/VERSION_ID`. |
| `description` | Optional | Human-readable version description. |
| `userLabel` | Optional | User-assigned version label. |
| `state` | Output only | `INTEGRATION_STATE_UNSPECIFIED`, `DRAFT`, `ACTIVE`, `ARCHIVED`, or `SNAPSHOT`. |
| `snapshotNumber` | Output only | Monotonically increasing version snapshot number. |
| `lockHolder` | Optional | Email of the author currently holding the 15-minute `DRAFT` edit lock (`versions:publish` and `versions.delete` fail on a `DRAFT` if the caller is not `lockHolder`). |
| `lastModifierEmail` | Optional | Email of the last user who modified this version. |
| `createTime` / `updateTime` | Output only | RFC 3339 creation and last-modified timestamps. |
| `runAsServiceAccount` | Optional | Dedicated service account email. When set and no authentication profile (`authConfig`) is configured on the task, it is used to generate the auth token for Connector (`Connectors`), REST (`Call REST Endpoint`), and Cloud Function tasks; an authentication profile configured on the task takes precedence over `runAsServiceAccount`. Integrations created on or after October 15, 2026 with any trigger other than an API or Private trigger (for example Schedule, Cloud Scheduler, Cloud Pub/Sub, Salesforce, or Connector Event) cannot be tested or published unless `runAsServiceAccount` is set (Private triggers are exempt like API triggers, so a sub-integration whose only trigger is Private can be published without `runAsServiceAccount`); whenever `runAsServiceAccount` is set, the user publishing or testing the version needs `roles/iam.serviceAccountUser` on it. |
| `triggerConfigs` | Repeated | Trigger definitions (`TriggerConfig[]`) that start the workflow. |
| `taskConfigs` | Repeated | Task definitions (`TaskConfig[]`) that execute work. |
| `integrationParameters` | Repeated | Input, output, and transient workflow variables (`IntegrationParameter[]`). |
| `integrationConfigParameters` | Repeated | Environment-specific config variables (`IntegrationConfigParameter[]`). |
| `errorCatcherConfigs` | Repeated | Error catcher flows triggered when tasks or triggers fail. |
| `cloudLoggingDetails` | Optional | Controls Cloud Logging (`enableCloudLogging` boolean, `cloudLoggingSeverity` of `INFO`, `ERROR`, or `WARNING`). |
| `databasePersistencePolicy` | Optional | Controls database persistence (local logging) for execution data: `DATABASE_PERSISTENCE_POLICY_UNSPECIFIED` = `Enable (sync)` (the API default—a version built over REST without `databasePersistencePolicy` persists synchronously), `DATABASE_PERSISTENCE_ASYNC` = `Enable (async)` (the console default), or `DATABASE_PERSISTENCE_DISABLED` = `Disable`. |
| `enableVariableMasking` | Optional | Masks variable values in logs (Preview). Does **not** redact downloaded version files. |
| `cloudKmsKey` | Optional | CMEK key reference when regional CMEK is enabled. |
| `teardown` | Optional (deprecated) | Teardown configuration for the integration (marked deprecated in the v1 discovery document). |

- **Deprecated fields**: Never populate `taskConfigsInternal`, `triggerConfigsInternal`, or `integrationParametersInternal`. They are deprecated in favor of `taskConfigs`, `triggerConfigs`, and `integrationParameters`.

## Trigger Configuration (`TriggerConfig`)

Each trigger in `triggerConfigs[]` defines an entry point and the initial `startTasks` to invoke.

| Field | Required | Description |
| :--- | :--- | :--- |
| `triggerNumber` | Yes | Unique string identifier for this trigger within the version (for example, `"1"`). |
| `triggerType` | No | `API`, `CRON`, `CLOUD_PUBSUB_EXTERNAL`, `CLOUD_SCHEDULER`, `SFDC_CHANNEL`, `SFDC_CDC_CHANNEL`, `INTEGRATION_CONNECTOR_TRIGGER`, `PRIVATE_TRIGGER`, or `EVENTARC_TRIGGER`. |
| `triggerId` | No | Auto-generated invocation identifier (optional in payload; derived from `properties`). For API triggers: `api_trigger/TRIGGER_NAME`. For private triggers: `private_trigger/TRIGGER_NAME`. |
| `label` | No | Display label in the editor (for example, `"API Trigger"`). |
| `properties` | No | Trigger-specific key-value properties (for example, `{"Trigger name": "TRIGGER_NAME"}` for API triggers). |
| `startTasks` | No | Array of `{ "taskId": "1" }` objects naming the first task(s) to run. |
| `nextTasksExecutionPolicy` | No | Controls how multiple `startTasks` are evaluated (`RUN_ALL_MATCH` or `RUN_FIRST_MATCH`). |
| `errorCatcherId` | No | Attaches an error catcher flow to this trigger (at most one per trigger). |
| `inputVariables` / `outputVariables` | No | Trigger-scoped input and output variable names. |
| `cloudSchedulerConfig` | No | Configuration block when `triggerType` is `CLOUD_SCHEDULER`. |
| `alertConfig` | No | Alert thresholds attached to the trigger. |

## Task Configuration (`TaskConfig`)

Each task in `taskConfigs[]` represents one step in the DAG. An integration can contain at most 100 tasks.

| Field | Required | Description |
| :--- | :--- | :--- |
| `taskId` | Yes | Unique string identifier within the integration (for example, `"1"`, `"2"`). |
| `task` | No | Task type identifier (for example, `EmailTask` in the public upload guide, or `FieldMappingTask` in the API discovery document). |
| `displayName` | No | Human-readable label shown in the editor and execution logs. |
| `parameters` | No | Map of parameter key to `EventParameter` (`{"key": "...", "value": {ValueType}}`). |
| `nextTasks` | No | Outgoing edges: array of `{"taskId": "2", "condition": "$amount$ > 0"}`. |
| `nextTasksExecutionPolicy` | No | `RUN_ALL_MATCH` (runs all downstream tasks whose edge condition matches) or `RUN_FIRST_MATCH`. |
| `taskExecutionStrategy` | No | Join behavior when multiple upstream tasks point here: `WHEN_ALL_SUCCEED`, `WHEN_ANY_SUCCEED`, or `WHEN_ALL_TASKS_AND_CONDITIONS_SUCCEED`. |
| `failurePolicy` | No | Retry strategy on temporary errors: `retryStrategy` (`FATAL`, `IGNORE`, `NONE`, `RESTART_INTEGRATION_WITH_BACKOFF`, `EXPONENTIAL_BACKOFF`, `FIXED_INTERVAL`, `LINEAR_BACKOFF`), `maxRetries`, `intervalTime`, `condition`. |
| `synchronousCallFailurePolicy` | No | Retry policy used specifically during synchronous execution. |
| `conditionalFailurePolicies` | No | Conditional retry configuration (`failurePolicies[]` evaluated in order, plus `defaultFailurePolicy` when none match). |
| `errorCatcherId` | No | ID of the error catcher flow to run after retry policies are exhausted (at most one per task). |
| `jsonValidationOption` | No | Controls JSON schema validation for task inputs/outputs. |

## Variables and `ValueType` (`IntegrationParameter`)

Variables in `integrationParameters[]` define the integration's typed inputs, outputs, and working state.

### `IntegrationParameter` Fields

| Field | Description |
| :--- | :--- |
| `key` | Variable name (for example, `orderId`). Referenced in expressions as `$orderId$`. |
| `dataType` | `STRING_VALUE`, `INT_VALUE`, `DOUBLE_VALUE`, `BOOLEAN_VALUE`, `STRING_ARRAY`, `INT_ARRAY`, `DOUBLE_ARRAY`, `BOOLEAN_ARRAY`, or `JSON_VALUE`. |
| `inputOutputType` | `IN` (input only), `OUT` (output only), `IN_OUT` (both), or `IN_OUT_TYPE_UNSPECIFIED` (default, for internal variables). |
| `defaultValue` | `ValueType` object used when the trigger does not supply a dynamic value. A dynamic trigger input always overrides `defaultValue`. |
| `isTransient` | Boolean; indicates whether this parameter is a transient parameter. |
| `masked` | Boolean; masks the variable value in execution logs. |
| `searchable` | Boolean; indexes the variable for execution log filtering. |
| `containsLargeData` | Boolean hint for large payloads. |
| `jsonSchema` | Optional JSON Schema string when `dataType` is `JSON_VALUE`. |

### `ValueType` Oneof Encoding

Every `ValueType` object (used in `defaultValue` on `IntegrationParameter` and `integrationConfigParameters[].parameter.defaultValue`, and in `inputParameters` on `:execute`/`:schedule`) contains **exactly one** of these fields:

| `dataType` | `ValueType` Field | JSON Encoding Note |
| :--- | :--- | :--- |
| `STRING_VALUE` | `{"stringValue": "hello"}` | UTF-8 string (max 20 MB in Data Mapping). |
| `INT_VALUE` | `{"intValue": "42"}` | **String-encoded** 64-bit integer (not a raw JSON number). |
| `DOUBLE_VALUE` | `{"doubleValue": 3.14}` | JSON number. |
| `BOOLEAN_VALUE` | `{"booleanValue": true}` | JSON boolean. |
| `JSON_VALUE` | `{"jsonValue": "{\"id\":1}"}` | **String-encoded** JSON document (not an inline JSON object). |
| `STRING_ARRAY` | `{"stringArray": {"stringValues": ["a", "b"]}}` | Object wrapping `stringValues[]`. |
| `INT_ARRAY` | `{"intArray": {"intValues": ["1", "2"]}}` | Object wrapping string-encoded `intValues[]`. |
| `DOUBLE_ARRAY` | `{"doubleArray": {"doubleValues": [1.5, 2.5]}}` | Object wrapping `doubleValues[]`. |
| `BOOLEAN_ARRAY` | `{"booleanArray": {"booleanValues": [true, false]}}` | Object wrapping `booleanValues[]`. |

## Config Variables (`IntegrationConfigParameter`)

Config variables (Preview) separate environment-specific configuration from workflow logic so the same version JSON can be promoted across projects without editing tasks.

- **Naming rule**: In the REST API, config variable keys must use the `CONFIG_` prefix wrapped in backticks: `` `CONFIG_<NAME>` `` (the Cloud console adds `CONFIG_` automatically). Reference them in expressions as `` $`CONFIG_<NAME>`$ ``.
- **Schema in `integrationConfigParameters[]`**: Config variable defaults belong in `parameter.defaultValue` inside `integrationConfigParameters[]`—for example, `{"parameter": {"key": "`CONFIG_backend_url`", "dataType": "STRING_VALUE", "displayName": "Backend URL", "defaultValue": {"stringValue": "https://api.example.com"}}}`. A top-level `value` in uploaded or created draft JSON is discarded, so per-environment values go in `configParameters` at publish.
- **Supplying values at publish**: Pass `{"configParameters": {"`CONFIG_<NAME>`": "target-value"}}` in the `POST .../versions/VERSION_ID:publish` body (`configParameters` is a `google.protobuf.Struct`, so values are plain JSON primitives/objects rather than `ValueType` wrappers). **Gotcha**: Keys in `configParameters` must **exactly match** a key in `integrationConfigParameters`, backticks included (for example, `` "`CONFIG_target_url`" ``); unknown keys are **silently ignored**, not rejected (`versions:publish` returns 200 and the default stays).
- **Security limitation**: Config variables are **not** a secret store. Their values are stored and exported in plain text when downloading a version (`versions:download`) or sharing a template, even if variable masking is enabled. Never store API keys, passwords, or tokens in config variables; use `projects.locations.authConfigs` or the Secret Manager access task.
- **Connector limitation**: Config variables cannot be used to parameterize Integration Connectors entity operations or actions.

## Minimal `IntegrationVersion` JSON Template

Save this runnable template to a file (for example, `version.json`). Pass it to `versions:upload` wrapped in `{"content": "<escaped-json>", "fileFormat": "JSON"}`—`versions:upload` creates the integration automatically if it does not exist yet, or adds a new `DRAFT` version if it does (the uploaded `DRAFT` still requires `versions:publish`). Alternatively, pass the JSON directly to `POST .../versions?newIntegration=true` only when you want the call to fail with `ALREADY_EXISTS` if `INTEGRATION_NAME` already exists. The template sets `runAsServiceAccount` (`RUN_AS_SA`, such as `order-workflow-sa@PROJECT_ID.iam.gserviceaccount.com`) because projects with governance require a run-as service account to publish, and the caller needs `roles/iam.serviceAccountUser` on it. The `EmailTask` uses the customer-visible parameter keys `"To"` (`stringArray`), `"Subject"` (`stringValue`), `"BodyFormat"` (`stringValue`, such as `"PLAIN_TEXT"`), and `"TextBody"` (`stringValue`). Running this workflow sends a real email, so always confirm `RECIPIENT_EMAIL` and each state-changing call (upload/create, publish, and execute) with the user first.

```json
{
  "description": "API-triggered order notification integration",
  "runAsServiceAccount": "order-workflow-sa@PROJECT_ID.iam.gserviceaccount.com",
  "cloudLoggingDetails": {
    "enableCloudLogging": true,
    "cloudLoggingSeverity": "INFO"
  },
  "triggerConfigs": [
    {
      "label": "API Trigger",
      "triggerType": "API",
      "triggerNumber": "1",
      "triggerId": "api_trigger/TRIGGER_NAME",
      "properties": {
        "Trigger name": "TRIGGER_NAME"
      },
      "startTasks": [
        {
          "taskId": "1"
        }
      ]
    }
  ],
  "taskConfigs": [
    {
      "task": "EmailTask",
      "taskId": "1",
      "displayName": "Send Email",
      "taskExecutionStrategy": "WHEN_ALL_SUCCEED",
      "parameters": {
        "To": {
          "key": "To",
          "value": {
            "stringArray": {
              "stringValues": [
                "RECIPIENT_EMAIL"
              ]
            }
          }
        },
        "Subject": {
          "key": "Subject",
          "value": {
            "stringValue": "Order notification for $orderId$"
          }
        },
        "BodyFormat": {
          "key": "BodyFormat",
          "value": {
            "stringValue": "PLAIN_TEXT"
          }
        },
        "TextBody": {
          "key": "TextBody",
          "value": {
            "stringValue": "Processing order $orderId$."
          }
        }
      }
    }
  ],
  "integrationParameters": [
    {
      "key": "orderId",
      "dataType": "STRING_VALUE",
      "inputOutputType": "IN_OUT",
      "defaultValue": {
        "stringValue": "ORD-0000"
      }
    }
  ]
}
```
rest-api-cheatsheet.md 19.3 KB
# Application Integration REST API Cheatsheet

This reference covers the v1 and v2 REST endpoints for authoring, versioning, testing, publishing, and running Google Cloud Application Integration workflows.

- [Endpoint and Authentication Rules](#endpoint-and-authentication-rules): Lines 13-25
- [Integrations Resource (`projects.locations.integrations`)](#integrations-resource-projectslocationsintegrations): Lines 26-43
- [Versions Resource (`projects.locations.integrations.versions`)](#versions-resource-projectslocationsintegrationsversions): Lines 44-63
- [Authentication Profiles (`projects.locations.authConfigs`)](#authentication-profiles-projectslocationsauthconfigs): Lines 64-79
- [Test Cases (`versions.testCases`, Preview)](#test-cases-versionstestcases-preview): Lines 80-93
- [Templates (`projects.locations.templates`, Preview)](#templates-projectslocationstemplates-preview): Lines 94-106
- [Executions, Suspensions, and v2 Surface](#executions-suspensions-and-v2-surface): Lines 107-122

## Endpoint and Authentication Rules

- **Global base URL**: `https://integrations.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION`
- **Regional base URL**: Some documentation pages use `https://LOCATION-integrations.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION` for `:execute` and `:lift`. If you use the regional host, the host prefix and `locations/LOCATION` must match (the public API trigger guide contains a known typo pairing `us-east1` with `locations/us-central1`). Prefer the global host `https://integrations.googleapis.com` consistently.
- **Required OAuth scope**: `https://www.googleapis.com/auth/cloud-platform`
- **REST header**: `-H "Authorization: Bearer $(gcloud auth print-access-token)"`
- **Client libraries**: For the Python discovery client (`pip install "google-api-python-client>=2.100.0,<3" "google-auth>=2.20.0,<3"`), run `gcloud auth application-default login` and `gcloud auth application-default set-quota-project PROJECT_ID` to configure Application Default Credentials (changes host or credential state; get the user's approval first).
- **Service account impersonation**: Run `gcloud config set auth/impersonate_service_account SA_EMAIL` (caller needs `roles/iam.serviceAccountTokenCreator` on `SA_EMAIL`) (changes host or credential state; get the user's approval first).

| Header | Applies To | Default | Notes |
| :--- | :--- | :--- | :--- |
| `X-Server-Timeout` | `:execute` | `120` (seconds) | Sets the HTTP request wait timeout in seconds (synchronous execution max is 120 seconds). |

## Integrations Resource (`projects.locations.integrations`)

All paths below are relative to `https://integrations.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION`.

| Method | HTTP & Path | Key Parameters / Body | IAM Permission | Notes |
| :--- | :--- | :--- | :--- | :--- |
| `list` | `GET /integrations` | Query: `pageSize`, `pageToken`, `orderBy`, `filter` | `integrations.integrations.list` | Returns `integrations[]` (`name`, `description`, `active`, `createTime`, `updateTime`, `creatorEmail`, `lastModifierEmail`). |
| `search` | `GET /integrations:search` | Query search parameters | `integrations.integrations.list` | Searches integrations in the region. |
| `delete` | `DELETE /integrations/INTEGRATION_NAME` | None | `integrations.integrations.delete` | Permanently deletes the integration and **all** its versions. Cannot be undone. |
| `execute` | `POST /integrations/INTEGRATION_NAME:execute` | Body: `triggerId`, `inputParameters`, `requestId`, `doNotPropagateError` | `integrations.integrations.invoke` | Synchronous run; integration must be `ACTIVE`. Use `-` as `INTEGRATION_NAME` to run all integrations matching `triggerId`. |
| `schedule` | `POST /integrations/INTEGRATION_NAME:schedule` | Body: `triggerId`, `scheduleTime`, `inputParameters`, `requestId`, `userGeneratedExecutionId` | `integrations.integrations.invoke` | Asynchronous run; returns `executionInfoIds[]`. If `scheduleTime` <= now, runs immediately. |

### `integrations.list` Filtering and Ordering

- **Supported `orderBy` fields**: `last_modified_time`, `created_time`, `snapshot_number` (descending; the public `integrations.list` reference page writes these in camelCase as `lastModifiedTime`, `createdTime`, `snapshotNumber`), or `name` (ascending).
- **Supported `filter` operators**: `:`, `=`, `>`, `<`, `>=`, `<=`, `!=`, combined with `NOT`, `AND`, `OR`.
- **Limitation**: You cannot filter on repeated fields such as `taskConfig`.

## Versions Resource (`projects.locations.integrations.versions`)

All paths below are relative to `https://integrations.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/integrations/INTEGRATION_NAME`.

| Method | HTTP & Path | Key Parameters / Body | IAM Permission | Notes |
| :--- | :--- | :--- | :--- | :--- |
| `create` | `POST /versions` | Query: `newIntegration` (bool, in discovery), `createSampleIntegrations` (bool); Body: `IntegrationVersion` | `integrations.integrationVersions.create` | Creates a `DRAFT` version (creates a new integration if none exists; pass `newIntegration=true` only when you want `ALREADY_EXISTS` if `INTEGRATION_NAME` already exists). |
| `get` | `GET /versions/VERSION_ID` | None | `integrations.integrationVersions.get` | Returns the full `IntegrationVersion` resource. |
| `list` | `GET /versions` | Query: `pageSize` (default 50, max 1000), `pageToken`, `orderBy`, `filter`, `fieldMask` | `integrations.integrationVersions.list` | `orderBy` supports `last_modified_time`, `created_time`, `snapshot_number` (desc), `name` (asc). |
| `patch` | `PATCH /versions/VERSION_ID` | Query: `updateMask` (FieldMask); Body: `IntegrationVersion` | `integrations.integrationVersions.update` | Updates an editable `DRAFT` version. |
| `delete` | `DELETE /versions/VERSION_ID` | None | `integrations.integrationVersions.delete` | Soft-deletes version to `ARCHIVED` (no undelete) and releases any edit lock. Fails if `DRAFT` and the caller is not `lockHolder`. Deleting all versions deletes the integration. |
| `download` | `GET /versions/VERSION_ID:download` | Query: `fileFormat` (`JSON` or `YAML`), `files[]` (`INTEGRATION`, `INTEGRATION_CONFIG_VARIABLES`) | `integrations.integrationVersions.get` | Returns `DownloadIntegrationVersionResponse` with `content` string and `files[]`. |
| `downloadJsonPackage` | `GET /versions/VERSION_ID:downloadJsonPackage` | Query: `files[]` (`INTEGRATION`, `INTEGRATION_CONFIG_VARIABLES`) | `integrations.integrationVersions.get` | Returns `files[]` with `type`, `integrationVersion`, and `integrationConfig` as JSON. |
| `upload` | `POST /versions:upload` | Body: `content` (string), `fileFormat` (`JSON` or `YAML`) | `integrations.integrationVersions.create` (in `roles/integrations.integrationEditor` and `roles/integrations.integrationAdmin`—not in `roles/integrations.integrationDeployer`, which can publish but cannot upload) | Creates a new `DRAFT` version from a downloaded payload (creates the integration if it does not exist yet; still requires `:publish`). Returns `UploadIntegrationVersionResponse.integrationVersion`. |
| `publish` | `POST /versions/VERSION_ID:publish` | Body: `configParameters` (Struct; keys must **exactly match** a key in `integrationConfigParameters`, backticks included, such as `` "`CONFIG_target_url`" ``, because unknown keys are silently ignored—publish returns 200 and the default stays) | `integrations.integrationVersions.deploy` (in `roles/integrations.integrationDeployer`, `roles/integrations.integrationEditor`, and `roles/integrations.integrationAdmin`, plus `roles/iam.serviceAccountUser` on `runAsServiceAccount` for the user publishing the version whenever `runAsServiceAccount` is set) | Makes version `ACTIVE`, auto-unpublishes prior `ACTIVE` version (dependents switch to the newly published version), and releases any edit lock. Fails if already `ACTIVE`/`ARCHIVED` or if `DRAFT` and the caller is not `lockHolder`. |
| `unpublish` | `POST /versions/VERSION_ID:unpublish` | Empty body | `integrations.integrationVersions.deploy` | Moves `ACTIVE` version to `SNAPSHOT` (tag `PREVIOUSLY_PUBLISHED`) and stops dependent services. Fails if not `ACTIVE`. |

- **Lock takeover**: `takeoverEditLock` does **not** exist on `projects.locations.integrations.versions` in v1. Wait 15 minutes for the lock to expire or use **Take Over** in the Cloud console.
- **Testing before production**: Test a draft version by publishing it to a non-production project (`versions:publish`) and invoking `integrations:execute` there.

## Authentication Profiles (`projects.locations.authConfigs`)

Authentication profiles store external credentials so secrets never enter `IntegrationVersion` JSON or config variables.

| Method | HTTP & Path | Key Parameters / Body | Notes |
| :--- | :--- | :--- | :--- |
| `create` | `POST /authConfigs` | Body: `AuthConfig` (`displayName` and `credentialType` required, `decryptedCredential`, `visibility`) | Requires `roles/integrations.integrationEditor` (or Admin). |
| `get` | `GET /authConfigs/AUTH_CONFIG_ID` | None | Returns `AuthConfig` (`state`: `VALID`, `INVALID`, `SOFT_DELETED`, `EXPIRED`, `UNAUTHORIZED`, `UNSUPPORTED`). |
| `list` | `GET /authConfigs` | Query: `pageSize`, `pageToken`, `filter`, `readMask` | Lists regional auth profiles. |
| `patch` | `PATCH /authConfigs/AUTH_CONFIG_ID` | Query: `updateMask`; Body: `AuthConfig` | Updates credentials or metadata. |
| `delete` | `DELETE /authConfigs/AUTH_CONFIG_ID` | None | Requires `roles/integrations.integrationAdmin`. |

- **Supported `credentialType` values**: `USERNAME_AND_PASSWORD`, `API_KEY`, `OAUTH2_AUTHORIZATION_CODE`, `OAUTH2_IMPLICIT`, `OAUTH2_CLIENT_CREDENTIALS`, `OAUTH2_RESOURCE_OWNER_CREDENTIALS`, `JWT`, `AUTH_TOKEN`, `SERVICE_ACCOUNT`, `CLIENT_CERTIFICATE_ONLY`, `OIDC_TOKEN`.
- **OAuth 2.0 redirect URI**: `https://console.cloud.google.com/integrations/callback/locations/AUTH_PROFILE_REGION`.
- **Portability**: Auth profiles are **not** included in downloaded integration files. Provision them separately in each project via REST or Terraform (`google_integrations_auth_config`).

## Test Cases (`versions.testCases`, Preview)

Test cases attach functional assertions and task mocks to a `DRAFT` version. They are not included when downloading an integration version and must be downloaded/uploaded separately.

| Method | HTTP & Path (under `.../versions/VERSION_ID`) | Notes |
| :--- | :--- | :--- |
| `create` | `POST /testCases?testCaseId=TEST_CASE_ID` | Cannot create test cases on an `ACTIVE` version (create a `DRAFT` first). |
| `get` / `list` | `GET /testCases/TEST_CASE_ID` / `GET /testCases` | Reads test case definitions (`triggerId`, `testInputParameters`, `testTaskConfigs`). |
| `patch` / `delete` | `PATCH /testCases/TEST_CASE_ID?updateMask=...` / `DELETE /testCases/TEST_CASE_ID` | Updates or removes a test case on a `DRAFT`. |
| `download` / `upload` | `GET /testCases/TEST_CASE_ID:download` / `POST /testCases:upload` | Exports or imports a test case (`fileFormat`: `JSON` or `YAML`). |
| `executeTest` | `POST /testCases/TEST_CASE_ID:executeTest` | Runs one test case (body `inputParameters`). Returns `executionId`, `testExecutionState`, `assertionResults[]`, `outputParameters`. Needs `integrations.testCases.invoke` (included in `roles/integrations.integrationInvoker`, `roles/integrations.integrationEditor`, and `roles/integrations.integrationAdmin`). |
| `execute` | `POST /testCases:execute` | Runs all test cases on a version. Returns `executeTestCaseResponses[]` (each containing `executionId`, `testExecutionState`, `assertionResults[]`, `outputParameters`). Needs `integrations.testCases.invoke` (included in `roles/integrations.integrationInvoker`, `roles/integrations.integrationEditor`, and `roles/integrations.integrationAdmin`). |
| `takeoverEditLock` | `POST /testCases/TEST_CASE_ID:takeoverEditLock` | Exists on `testCases` only (not on parent `versions`). |

## Templates (`projects.locations.templates`, Preview)

Templates package reusable integration patterns (Global read-only, Shared, or Project visibility).

| Method | HTTP & Path (under `.../locations/LOCATION`) | Notes |
| :--- | :--- | :--- |
| `create` / `patch` / `delete` | `POST /templates` / `PATCH /templates/TEMPLATE_ID?updateMask=...` / `DELETE /templates/TEMPLATE_ID` | Manages project or shared templates. |
| `get` / `list` / `search` | `GET /templates/TEMPLATE_ID` / `GET /templates` / `GET /templates:search` | Inspects available templates (`visibility`: `PRIVATE`, `SHARED`, `PUBLIC`). |
| `download` / `upload` | `GET /templates/TEMPLATE_ID:download?fileFormat=JSON` / `POST /templates:upload` | Exports (`fileFormat` required) or imports template content (body requires `content` and `fileFormat`). |
| `use` | `POST /templates/TEMPLATE_ID:use` | Creates a new integration from a template (body requires `integrationDetails` and `integrationRegion`; `subIntegrations` is optional). |
| `import` | `POST /templates/TEMPLATE_ID:import` | Imports a template into an existing integration (body requires `integration`; `subIntegrations` is optional). |
| `share` / `unshare` | `POST /templates/TEMPLATE_ID:share` / `POST /templates/TEMPLATE_ID:unshare` | Shares or revokes access across `resourceNames`. |

## Executions, Suspensions, and v2 Surface

| Method | HTTP & Path | Notes |
| :--- | :--- | :--- |
| `executions.list` | `GET /v1/.../integrations/INTEGRATION_NAME/executions` | Query with `filter`, `snapshotMetadataWithoutParams=true`, and `readMask` (do **not** use deprecated `truncateParams` [UI-only] or `filterParams.*` [internal-only]). Supported filter keys to use are `execution_id`, `state` (supports `=` and `!=` with unquoted `ExecutionDetails.state` values such as `filter=state=FAILED`, `filter=state!=SUCCEEDED`, `filter=state=CANCELLED`, or `filter=state=FAILED OR state=CANCELLED`, URL-encoded as needed; use `state`, not `eventExecutionState` [as shown on the REST reference page] or `event_execution_state` in the API reference's filter description), `update_time`, `workflow_name`, `trigger_id`, `CreateTimestamp`, and `parameter_type`; camelCase variants such as `executionId` are not supported even though some docs examples show them. Use `-` as `INTEGRATION_NAME` to query across integrations. |
| `executions:cancel` | `POST /v1/.../executions/EXECUTION_ID:cancel` | Body requires `cancelReason`. Only cancels `PENDING` (console "On hold"), `RETRY_ON_HOLD`, or `SUSPENDED` runs (cannot cancel `PROCESSING` [console "In process"], completed runs [`SUCCEEDED`, `FAILED`, `CANCELLED`], or Schedule-trigger runs). Requires `integrations.executions.cancel` (included in `roles/integrations.integrationInvoker`, `roles/integrations.integrationEditor`, and `roles/integrations.integrationAdmin`—**not** in `roles/integrations.suspensionResolver` or `roles/integrations.integrationViewer`). |
| `executions:replay` | `POST /v1/.../executions/EXECUTION_ID:replay` | Preview; published integrations only. Body requires `replayReason`, optional `replayMode` (`REPLAY_MODE_FROM_BEGINNING` or `REPLAY_MODE_POINT_OF_FAILURE`), and optional `modifiedParameters` + `updateMask` (list every overridden key in `updateMask`; without `updateMask`, all original inputs are discarded and only `modifiedParameters` are used, and a key in `updateMask` missing from `modifiedParameters` is an error). Not for Schedule triggers. Preconditions returning `FAILED_PRECONDITION`: (a) test-case runs cannot be replayed in any mode (`"Test runs cannot be replayed."`); (b) `REPLAY_MODE_POINT_OF_FAILURE` is refused for executions that ran with database persistence (local logging / `databasePersistencePolicy: DATABASE_PERSISTENCE_DISABLED`) disabled because it needs execution snapshots—use `REPLAY_MODE_FROM_BEGINNING` in that case. Requires `integrations.executions.replay` (included in `roles/integrations.integrationInvoker`, `roles/integrations.integrationEditor`, and `roles/integrations.integrationAdmin`—**not** in `roles/integrations.suspensionResolver` or `roles/integrations.integrationViewer`). |
| `suspensions.list` | `GET /v1/.../executions/EXECUTION_ID/suspensions` | Requires `integrations.suspensions.list` (included in `roles/integrations.suspensionResolver` and `roles/integrations.integrationAdmin`; `roles/integrations.suspensionResolver` alone cannot read execution records, so also grant `roles/integrations.integrationViewer` to inspect `taskExecutionDetails` or run `:troubleshoot`, or use the approval email link, which carries the execution and task IDs); visible only to principals with permission to resolve the relevant suspensions. |
| `suspensions:lift` | `POST /v1/.../integrations/INTEGRATION_NAME/executions/EXECUTION_ID/suspensions/SUSPENSION_ID:lift` | `Suspend`-task variant (confirm with user first). Body accepts optional `suspensionResult` (defaults to `Resolved`). `-` can replace `INTEGRATION_NAME` and either `EXECUTION_ID` or `SUSPENSION_ID` (at least one of `EXECUTION_ID` or `SUSPENSION_ID` must be concrete; omitting both returns an error). Requires `integrations.suspensions.lift` (included in `roles/integrations.suspensionResolver` and `roles/integrations.integrationAdmin`) plus `roles/iam.serviceAccountUser` on `runAsServiceAccount`. |
| `suspensions:resolve` | `POST /v1/.../executions/EXECUTION_ID/suspensions/SUSPENSION_ID:resolve` | Approves or rejects an `Approval` task (same call the console Approve/Reject buttons make; confirm with user first). Body: `{"suspension": {"eventExecutionInfoId": "EXECUTION_ID", "integration": "INTEGRATION_NAME", "taskId": "TASK_ID", "state": "LIFTED"}}` (or `"REJECTED"`). Requires `integrations.suspensions.resolve` (included in `roles/integrations.suspensionResolver` and `roles/integrations.integrationAdmin`) plus `roles/iam.serviceAccountUser` on `runAsServiceAccount`. |
| `generateOpenApiSpec` | `POST /v1/projects/PROJECT_ID/locations/LOCATION:generateOpenApiSpec` | Body requires `apiTriggerResources[]` (`integrationResource` + `triggerId[]`) and `fileFormat` (`JSON` or `YAML`). Generates an OpenAPI 3.0.1 spec for published API-trigger integrations in a single region. Requires `integrations.integrations.generateOpenApiSpec` (included in `roles/integrations.integrationViewer`, `roles/integrations.integrationEditor`, and `roles/integrations.integrationAdmin`, but **not** in `roles/integrations.integrationInvoker`). Used by ADK `ApplicationIntegrationToolset` in **integration mode** (`roles/integrations.integrationInvoker` + `roles/integrations.integrationViewer`); ADK **connection mode** does not call `:generateOpenApiSpec` and instead needs `roles/integrations.integrationInvoker` + `roles/connectors.viewer` (or a custom role with `connectors.connections.get` and `connectors.connections.getConnectionSchemaMetadata`, which `roles/connectors.invoker` does not have, and `roles/integrations.integrationEditor` holds no `connectors.*` permissions). `roles/secretmanager.secretAccessor` is not needed for the toolset itself (the ADK client does not read Secret Manager). |
| `v2` `integrations:execute` / `:schedule` | `POST /v2/projects/PROJECT_ID/locations/LOCATION/integrations/INTEGRATION_NAME:execute` (or `:schedule`) | v2 execution endpoints. |
| `v2` `executions:troubleshoot` | `GET /v2/.../executions/EXECUTION_ID:troubleshoot` | Uses Gemini to return `executionId`, `displayMessage`, `errorMessage`, `rootCause`, and `detailedExplanation` for a failed execution (requires AI features enabled in the region and `integrations.executions.get`). |
| `v2` `taskExecutions.get` | `GET /v2/.../executions/EXECUTION_ID/taskExecutions/TASK_EXECUTION_ID` | Reads individual task execution details in v2. |

For detailed log queries, failure states, and troubleshooting workflows, use the `application-integration-troubleshooting` skill.
tasks-and-gotchas.md 13.0 KB
# Tasks, Variables, and Gotchas Reference

This reference lists the limits, configuration rules, and runtime pitfalls for common Application Integration tasks, variable expressions, and retry policies.

- [Core Data and Integration Tasks](#core-data-and-integration-tasks): Lines 12-24
- [Pause and Wait Tasks (`Approval`, `Suspend`, `Timer`)](#pause-and-wait-tasks-approval-suspend-timer): Lines 25-40
- [Loop and Sub-Integration Tasks](#loop-and-sub-integration-tasks): Lines 41-51
- [Variable Reference Syntax and System Variables](#variable-reference-syntax-and-system-variables): Lines 52-73
- [Error Handling and Retry Strategies](#error-handling-and-retry-strategies): Lines 74-101
- [Project and Integration Quotas](#project-and-integration-quotas): Lines 102-114

## Core Data and Integration Tasks

| Task | Key Limits | Documented Rules and Gotchas |
| :--- | :--- | :--- |
| **Data Mapping** | Array <= 100,000 elements; JSON or String variable <= 20 MB | Input and output types must match exactly; cast explicitly with transformation functions such as `TO_STRING` or `TO_INT`. Always configure a fallback value, or `null` inputs cause the task to fail. |
| **Data Transformer Script** (Preview) | 300 MB evaluation memory | Supports Diagram mode and Jsonnet Script mode. Jsonnet identifiers cannot contain hyphens (`-`). |
| **JavaScript** | Script request size <= 25 MB | Uses the V8 JavaScript engine (the legacy Rhino engine was deprecated on January 24, 2025). Do not delete or rename the `executesScript(event)` entrypoint function. |
| **Call REST Endpoint** | Request <= 20 MB; Response <= 34 MB; <= 100 concurrent calls | Reaches the **public internet only** (cannot connect to private VPC-only hosts). Fails on HTTP `4xx` and `5xx` responses. Outputs task variables such as `` `Task_1_responseBody` `` (for `taskId` `"1"`). An authentication profile (`authConfig`) configured on the task takes precedence over the integration's `runAsServiceAccount` (which generates the auth token when no auth config is set on the task). If you change its authentication profile, publish the version so the updated profile takes effect. |
| **Connectors** | Timeout 3 minutes; data to/from connection <= 8 MB (Application Integration quota; Integration Connectors quota lists 10 MB max Connectors task payload); response <= 20 MB; default page size 25 (max 50,000 pages); custom query <= 180 seconds and <= 50,000 rows | Requires a provisioned Integration Connectors connection (billed per active node) and `roles/connectors.admin` to create connections. Uses the integration's `runAsServiceAccount` to generate the auth token when no auth config is configured on the task. Outputs `connectorOutputPayload`. HTTP 429 indicates connection node throttling (increase min/max nodes or add a retry strategy). |
| **Cloud Function** | Standard HTTP limits | Supports Cloud Functions 1st gen and v2 (`.run.app`). Function source must follow the required template (`main.py`, `task.py`, `requirements.txt`). Stops working if VPC Service Controls is enabled for Application Integration. An attached OIDC authentication profile (`authConfig`) takes precedence over the integration's `runAsServiceAccount` (which generates the auth token when no auth config is set on the task). |
| **Send Email** | Max 30 recipients | Supports `$variableName$` substitution inside both the email subject and body. |
| **Other Built-in Tasks** | Service-specific | Also available: Return, Apps Script, and Google Cloud service tasks (Cloud KMS, Dataflow, Drive, Document AI, Firestore, Natural Language, Secret Manager, Sheets, Translate, Vertex AI, and Workflows). |

## Pause and Wait Tasks (`Approval`, `Suspend`, `Timer`)

Integrations containing any of these three tasks cannot be tested in draft state and must be published before testing or execution (for example, by publishing to a non-production project and calling `integrations:execute`).

| Feature | Approval Task | Suspend Task | Timer Task |
| :--- | :--- | :--- | :--- |
| **Purpose** | Emails recipients to approve or reject | Pauses for an external event or timeout | Pauses for a fixed delay |
| **Resume via REST API?** | **Yes** (`POST .../executions/EXECUTION_ID/suspensions/SUSPENSION_ID:resolve` with `state` `"LIFTED"` or `"REJECTED"`, the same call the console Approve/Reject buttons make; confirm with user first) | **Yes** (`POST .../integrations/INTEGRATION_NAME/executions/EXECUTION_ID/suspensions/SUSPENSION_ID:lift` with optional `suspensionResult`; `-` can replace `INTEGRATION_NAME` and either `EXECUTION_ID` or `SUSPENSION_ID` if at least one ID is concrete; confirm with user first) | **No** (resumes automatically when timer expires) |
| **Max / Default Duration** | Configurable hours (max total run lifetime 31 days) | Max and default 44,640 minutes (31 days) | Default 120 seconds, max 44,640 minutes (31 days) |
| **Expiration Behavior** | Defaults to `REJECTED` (can be set to lift) | Resumes with `suspensionResult` = `Expired` | Resumes automatically |
| **Required Approver IAM** | `integrations.suspensions.resolve` (`roles/integrations.suspensionResolver` or `roles/integrations.integrationAdmin`) + `roles/iam.serviceAccountUser` on `runAsServiceAccount` (`suspensions.list` needs `integrations.suspensions.list`) | `integrations.suspensions.lift` (`roles/integrations.suspensionResolver` or `roles/integrations.integrationAdmin`) + `roles/iam.serviceAccountUser` on `runAsServiceAccount` (`suspensions.list` needs `integrations.suspensions.list`) | None |
| **Execution Mode After Resume** | Always ASYNC | Always ASYNC | `< 60 s` behaves like SYNC; `>= 60 s` runs ASYNC |
| **Key Output / Branching** | Boolean `isApproved` (for example, `taskId` `"2"` -> `` $`Task_2_isApproved`$ = TRUE ``) | `suspensionResult` string (defaults to `Resolved` if lifted without a value) | None |

- **Publish side effect**: Publishing a new version of an integration automatically cancels all currently suspended executions of the previous version.

## Loop and Sub-Integration Tasks

All loop and sub-integration tasks invoke another published integration (the sub-integration) by its API trigger (`api_trigger/TRIGGER_NAME`) or Private trigger (`private_trigger/TRIGGER_NAME`). For sub-integration calls (`Call Integration`, `For Each Loop`, `For Each Parallel`), child responses/output parameters are returned to the parent only in `SYNC` mode; `ASYNC` calls return no output parameters.

| Task | Max Iterations / Scale | Key Rules and Gotchas |
| :--- | :--- | :--- |
| **For Each Loop** | 8,000 iterations; <= 50 MB total collected output | Calls a sub-integration sequentially per array item. Child responses/output parameters are returned to the parent only in SYNC mode (ASYNC calls return no output parameters). Prefer underscore loop-metadata keys (such as `current_iteration_count`). |
| **For Each Parallel** | 10,000 iterations; default parallelism 50 | Calls sub-integrations concurrently. Child responses/output parameters are returned to the parent only in SYNC mode (ASYNC calls return no output parameters); avoid SYNC mode if the sub-integration runs longer than 2 minutes or contains an Approval task. Selecting "run all integrations with this trigger ID" makes sub-integration responses unavailable to the parent. |
| **While Loop** | 8,000 iterations | Repeats a sub-integration while a condition holds. |
| **Call Integration** | Up to 10,000 sub-integrations | Callee must have an API trigger or a Private trigger (Private triggers are invokable only from other integrations). Supports SYNC or ASYNC mode (child responses/output parameters are returned to the parent only in SYNC mode; ASYNC calls return no output parameters). The caller's service account (or default Application Integration service agent `service-PROJECT_NUMBER@gcp-sa-integrations.iam.gserviceaccount.com` if none is attached) needs `roles/integrations.integrationInvoker`. |

## Variable Reference Syntax and System Variables

### Four Variable Categories

1. **Integration variables**: Defined in `integrationParameters` (`inputOutputType` of `IN`, `OUT`, `IN_OUT`, or `IN_OUT_TYPE_UNSPECIFIED` for internal variables). Referenced as `$variableName$`.
2. **Task variables**: Auto-generated outputs from tasks, named `` `Task_<taskId>_<variableName>` `` where `taskId` is the bare task number in `taskConfigs[].taskId`. Referenced with backticks inside dollar signs (for example, `taskId` `"5"` -> `` $`Task_5_responseBody`$ ``).
3. **Config variables**: Environment values defined in `integrationConfigParameters` with prefix `CONFIG_`. Referenced as `` $`CONFIG_endpoint_url`$ ``.
4. **System variables**: keys are backtick-wrapped; reference them as `` $`ExecutionId`$ `` (a bare `$ExecutionId$` names a nonexistent integration variable and fails).

### Built-in System Variables

| System Variable | Type | Contents |
| :--- | :--- | :--- |
| `` `ExecutionId` `` | String | Unique UUID for the current execution. |
| `` `ExecutionMode` `` | String | `SYNC` or `ASYNC`. |
| `` `ErrorInfo` `` | JSON (`message`, `code`) | Populated when a task or trigger fails (for example, `` $`ErrorInfo.code`$ ``). |
| `` `IntegrationName` `` | String | Name of the running integration. |
| `` `Region` `` | String | Region (`LOCATION`) where the integration runs. |
| `` `ProjectId` `` | String | Google Cloud project ID. |

- **Override precedence**: A value supplied dynamically by a trigger at runtime always overrides a static `defaultValue` defined on the integration variable.

## Error Handling and Retry Strategies

Error handling strategies apply to temporary (server-side) errors. Combine a task retry strategy with an Error Catcher trigger so the catcher runs after all retries are exhausted.

### Task `FailurePolicy.retryStrategy` Options

| UI Strategy Name | API Enum (`retryStrategy`) | Behavior |
| :--- | :--- | :--- |
| Fatal | `FATAL` | Fails the entire integration execution immediately. |
| Ignore | `IGNORE` | Ignores the task failure and continues downstream tasks as if this task succeeded. |
| None | `NONE` | Downstream tasks dependent on this task do not run, though parallel branches can still complete. |
| Restart integration with backoff | `RESTART_INTEGRATION_WITH_BACKOFF` | Restarts the entire integration from the first task using your configured `intervalTime` (retry interval in seconds) and `maxRetries` (maximum retry count). |
| Retry task (exponential / fixed / linear) | `EXPONENTIAL_BACKOFF` / `FIXED_INTERVAL` / `LINEAR_BACKOFF` | Retries only the failed task using `maxRetries` and `intervalTime` (adds a random 1–5 second jitter). |

### Conditional Failure Policies and Edge Conditions

- **Operators**: `=`, `!=`, `<`, `<=`, `>`, `>=`, `:`, `AND`, `OR`, `NOT`.
- **Functions**: `exists()`, `does_not_exist()`, `is_empty()`, `is_not_empty()`.
- **Condition example**: `` $`ErrorInfo.code`$ = 404 OR $`ErrorInfo.code`$ = 503 ``.
- **Evaluation order**: Conditional policies in `conditionalFailurePolicies.failurePolicies` are checked in list order; if none match, `defaultFailurePolicy` applies.

### Error Catcher Constraints

- Started by an Error Catcher trigger (`errorCatcherConfigs`) and linked via `errorCatcherId` on a task or trigger.
- Event-level catchers handle integration, edge-condition, task, and retry failures when no task-level catcher is attached.
- Only one error catcher can be attached per task or trigger.
- Error catchers cannot be nested, and no edges may connect error catcher tasks back into the main workflow flow.

## Project and Integration Quotas

| Resource or Limit | Value | Notes |
| :--- | :--- | :--- |
| Max cumulative integration data | 30 MB | Applies per integration and per sub-integration. **Above 10 MB, local logging is disabled** (no full logs, no retry strategy, no dashboard metrics). |
| Max API trigger input size | 8 MB | Exceeding 8 MB prevents the integration from starting and returns an error. |
| Max integrations per project | 1,000 | Integration name max 64 characters. |
| Max tasks per integration | 100 | Maximum number of tasks allowed in an integration. |
| Max versions per integration | 100 | Delete (`ARCHIVE`) old unused versions before hitting 100. |
| Default concurrent executions | 50 per project per region; 10 per integration | Both caps are adjustable. A burst on a single integration hits the 10-per-integration cap, not 50. Per the error-handling documentation ("Backoff retries"): "The default concurrency limit is set to 50 executions for each project and region. Failed executions are queued and retried using an exponential backoff algorithm" (10, 20, 40 minutes, and so on), up to 10 times. |
| Execution request rate | Shown on Cloud Quotas page | The execution request rate quota is shown on the Cloud Quotas page for the project and can be adjusted there. Execution-log reads cap at 18,000 per minute. |
| Eventual consistency after publish | Up to 10 minutes | An older published version can continue serving for up to 10 minutes after a new version is published. |
| Integration Connectors limits | 50 connections / region | Max 100 nodes per connection; max 20 unique regions; max 10 MB Connectors task payload (Integration Connectors quota; Application Integration quota caps data to/from connections at 8 MB). |
triggers-and-execution.md 15.4 KB
# Triggers and Execution Reference

This reference covers trigger types, `triggerId` formats, synchronous versus asynchronous execution, `:execute` and `:schedule` request and response schemas, OpenAPI spec generation, and resuming suspended runs.

- [Trigger Types and `triggerId` Formats](#trigger-types-and-triggerid-formats): Lines 12-30
- [Execution Modes (SYNC vs ASYNC)](#execution-modes-sync-vs-async): Lines 31-39
- [Comparing `:execute` and `:schedule`](#comparing-execute-and-schedule): Lines 40-70
- [Reading Execution Responses and Verifying Success](#reading-execution-responses-and-verifying-success): Lines 71-101
- [Generating OpenAPI Specifications](#generating-openapi-specifications): Lines 102-121
- [Resuming Suspended Executions (`suspensions:lift` and `suspensions:resolve`)](#resuming-suspended-executions-suspensionslift-and-suspensionsresolve): Lines 122-151

## Trigger Types and `triggerId` Formats

An integration can have multiple triggers. Each trigger starts from its own `startTasks` list, and simultaneous trigger events run separate copies of the integration.

| Trigger Type | `triggerType` Enum | Documented `triggerId` Format | Rules and Gotchas |
| :--- | :--- | :--- | :--- |
| API Trigger | `API` | `api_trigger/TRIGGER_NAME` | `TRIGGER_NAME` max 64 characters. Multiple API triggers allowed per integration (each unique). Max 8 MB total input variables. |
| Private Trigger | `PRIVATE_TRIGGER` | `private_trigger/TRIGGER_NAME` | Callable only from other integrations (not public REST APIs). Exempt like API triggers from the October 15, 2026 `runAsServiceAccount` rule, so a sub-integration whose only trigger is Private can be published without `runAsServiceAccount` (unless region governance is enabled). Cannot test while published (unpublish first). Shares the 30 MB data limit with the parent integration. |
| Cloud Pub/Sub | `CLOUD_PUBSUB_EXTERNAL` | Configured via topic | Topic format `projects/PROJECT_ID/topics/TOPIC_ID`. Auto-creates a Pub/Sub subscription on publish (billed at Pub/Sub rates). New or modified Pub/Sub triggers require a trigger service account (the identity that invokes the integration at runtime); integrations created on or after October 15, 2026 with any trigger other than an API or Private trigger (for example Schedule, Cloud Scheduler, Cloud Pub/Sub, Salesforce, or Connector Event) cannot be tested or published unless `runAsServiceAccount` is set (whenever `runAsServiceAccount` is set, the user publishing or testing the version needs `roles/iam.serviceAccountUser` on it, and at runtime the trigger service account needs `roles/iam.serviceAccountUser` on it). Outputs `CloudPubSubMessage` (JSON). |
| Schedule | `CRON` | Configured via cron | 5-field cron expression. Runs cannot be canceled or replayed. Google recommends the Cloud Scheduler trigger for higher reliability. |
| Cloud Scheduler | `CLOUD_SCHEDULER` | Configured via scheduler | Requires Cloud Scheduler API (`cloudscheduler.googleapis.com`, billed separately). Supports cross-region scheduling. Editing it in Application Integration overwrites the cron job in a new integration version. Requires `runAsServiceAccount`. |
| Salesforce | `SFDC_CHANNEL` / `SFDC_CDC_CHANNEL` | Configured via channel | Event-driven Salesforce channel or Change Data Capture trigger. Runs asynchronously. |
| Webhook (Preview) | `INTEGRATION_CONNECTOR_TRIGGER` | Connector subscription | Needs an Integration Connectors Webhook connection with an event subscription. Accepts JSON payloads only. Outputs `ConnectorEventPayload`. |
| Connector Event | `INTEGRATION_CONNECTOR_TRIGGER` | Connector subscription | Supported for Apache Kafka, Azure AD, HubSpot, IBM MQ, Jira Cloud, Jira Server Data Center, HL7, RabbitMQ, SAP ERP, SAP Gateway, ServiceNow, Solace, TIBCO EMS, Webhook, and Zendesk. |
| Error Catcher | Error catcher config | Referenced by `errorCatcherId` | One catcher per `errorCatcherId`. Cannot attach multiple catchers to one task or trigger. Cannot nest catchers. No edges can connect catcher tasks back to the main flow. |

- **Public REST invocation**: Only `api_trigger/TRIGGER_NAME` is used with public `integrations:execute` and `integrations:schedule`. Trigger ID formats for Pub/Sub, Schedule, Cloud Scheduler, and Salesforce triggers are not documented for direct public REST calls.
- **Run-as service account requirement (October 15, 2026+)**: Integrations created on or after October 15, 2026 with any trigger other than an API or Private trigger (for example Schedule, Cloud Scheduler, Cloud Pub/Sub, Salesforce, or Connector Event) cannot be tested or published unless `runAsServiceAccount` is set. Private triggers are exempt like API triggers, so a sub-integration whose only trigger is Private can be published without `runAsServiceAccount` (unless region governance is enabled). Whenever `runAsServiceAccount` is set, the user publishing or testing the version needs `roles/iam.serviceAccountUser` on it (and at runtime, the invoking caller or trigger service account needs `roles/iam.serviceAccountUser` on it).

## Execution Modes (SYNC vs ASYNC)

| Mode | How It Is Started | Execution Timeout | Max Lifetime |
| :--- | :--- | :--- | :--- |
| **SYNC** | `integrations:execute`, Call Integration task in SYNC mode, Timer task < 60 seconds | **2 minutes** (status becomes `CANCELLED` on timeout) | 2 minutes |
| **ASYNC** | `integrations:schedule`, Schedule trigger, Cloud Scheduler trigger, Cloud Pub/Sub trigger, Salesforce trigger, Call Integration task in ASYNC mode, Timer task >= 60 seconds, and **any execution resumed from a suspension or approval** | **10 minutes** | **31 days** (including pause time in Suspend or Approval tasks) |

- **Resumed runs always switch to ASYNC**: Even if an integration started synchronously via `integrations:execute`, once it pauses at a `Suspend` or `Approval` task and resumes, the remainder of the run executes in asynchronous mode.

## Comparing `:execute` and `:schedule`

### 1. Synchronous Execution (`integrations:execute`)

- **Endpoint**: `POST https://integrations.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/integrations/INTEGRATION_NAME:execute`
- **State requirement**: The integration must have an `ACTIVE` (published) version. To test an integration before production, publish the version in a non-production project (`versions:publish`) and invoke `integrations:execute` there.
- **Wildcard `-`**: Passing `-` as `INTEGRATION_NAME` (`/integrations/-:execute`) runs **every** published integration in that region that has the matching `triggerId`.
- **Timeout header**: Set `X-Server-Timeout: SECONDS` (default `120`; max synchronous runtime is 2 minutes).

| Request Body Field | Type | Required | Description |
| :--- | :--- | :--- | :--- |
| `triggerId` | string | Yes | `api_trigger/TRIGGER_NAME`. |
| `inputParameters` | map (`string` -> `ValueType`) | No | Input variables (max 8 MB cumulative for API triggers). |
| `requestId` | string | No | Deduplication token. Sending a duplicate `requestId` returns the previous execution's response without re-running. |
| `doNotPropagateError` | boolean | No | Default `false`. When `true`, returns HTTP 200 with an `ExecuteIntegrationsResponse` containing `executionId` and error details instead of throwing an HTTP error. |

### 2. Asynchronous Execution (`integrations:schedule`)

- **Endpoint**: `POST https://integrations.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/integrations/INTEGRATION_NAME:schedule`
- **State requirement**: The integration must have an `ACTIVE` (published) version.

| Request Body Field | Type | Required | Description |
| :--- | :--- | :--- | :--- |
| `triggerId` | string | Yes | `api_trigger/TRIGGER_NAME`. |
| `scheduleTime` | string (RFC 3339 Timestamp) | No | When to run (for example, `"2026-10-17T20:00:00Z"`). If omitted or <= current time, runs immediately in async mode. |
| `inputParameters` | map (`string` -> `ValueType`) | No | Input variables mapped to `ValueType`. |
| `requestId` | string | No | Deduplication token. |
| `userGeneratedExecutionId` | string | No | Custom UUID string (at most 36 characters, alphanumerics and hyphens only) used as the `executionId`. |

- **Response (`ScheduleIntegrationsResponse`)**: Returns `{"executionInfoIds": ["EXECUTION_ID"]}`. Poll or inspect completion via `executions.list`.

## Reading Execution Responses and Verifying Success

`ExecuteIntegrationsResponse` returns `executionId`, `outputParameters`, and `parameters`:

```json
{
  "executionId": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
  "outputParameters": {
    "`ExecutionId`": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
    "orderStatus": "PROCESSED"
  },
  "parameters": {
    "orderStatus": {
      "stringValue": "PROCESSED"
    }
  }
}
```

### Verification Checklist After `:execute`

1. **Verify the execution record (`executions.list`)**: Do not rely on HTTP 200 alone (or the legacy, deprecated `executionFailed` field, which is not a supported public signal). Query the execution record by `executionId`:
   ```bash
   curl -sS -H "Authorization: Bearer $(gcloud auth print-access-token)" \
     "https://integrations.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/integrations/-/executions?filter=execution_id%3D%22EXECUTION_ID%22"
   ```
   Check `executionDetails.state` (`PENDING`, `PROCESSING`, `SUCCEEDED`, `FAILED`, `CANCELLED`, `RETRY_ON_HOLD`, `SUSPENDED`) and each task's `taskExecutionState` (`SUCCEED`, `FAILED`, `FATAL`, `SKIPPED`, `SUSPENDED`, and so on).
2. **Do not trust HTTP 200 or `SUCCEEDED` without checking task states**: If a task has `failurePolicy.retryStrategy` set to `IGNORE` ("assumes this task succeeded") or `NONE` with an alternate branch, the integration can still return HTTP 200 and state `SUCCEEDED` even though a task failed.
3. **Check system keys in `outputParameters`**: System-generated variable names inside `outputParameters` are wrapped in backticks (for example, `` `ExecutionId` ``, `` `ErrorInfo` ``). User-defined output variables use their plain `key` name.
4. **Check `ErrorInfo` on errors**: Without `doNotPropagateError: true`, a failed `:execute` call throws an HTTP error rather than returning response parameters. Per the API reference, when `doNotPropagateError` is `true` on `:execute`, errors are returned in event parameters (`PostWithTriggerIdExecutionException`), while the `ErrorInfo` shape (`{"ErrorInfo": {"message": "...", "code": 400}}`) is documented on the execution record (`Execution.responseParameters`).

## Generating OpenAPI Specifications

You can generate an OpenAPI 3.0.1 specification for published integrations that use API triggers in a single region (`fileFormat` accepts `"JSON"` or `"YAML"`):

```bash
curl -sS -X POST \
  -H "Authorization: Bearer $(gcloud auth print-access-token)" \
  -H "Content-Type: application/json" \
  -d '{
    "apiTriggerResources": [{
      "integrationResource": "INTEGRATION_NAME",
      "triggerId": ["api_trigger/TRIGGER_NAME"]
    }],
    "fileFormat": "JSON"
  }' \
  "https://integrations.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION:generateOpenApiSpec"
```

ADK (`ApplicationIntegrationToolset`) roles depend on mode. In **integration mode**, `ApplicationIntegrationToolset` calls `POST .../locations/LOCATION:generateOpenApiSpec` automatically when turning published API-triggered integrations into agent tools; calling `:generateOpenApiSpec` requires `integrations.integrations.generateOpenApiSpec` (included in `roles/integrations.integrationViewer` and `roles/integrations.integrationEditor`, but **not** in `roles/integrations.integrationInvoker`), so grant `roles/integrations.integrationInvoker` + `roles/integrations.integrationViewer` as the least-privilege combination for integration mode (use `roles/integrations.integrationEditor` only as the broad option—it also grants version create, update, delete, and publish permissions, and holds no `connectors.*` permissions). In **connection mode**, the toolset does **not** call `:generateOpenApiSpec` (so `roles/integrations.integrationViewer` is only needed in integration mode); instead, when constructed using the agent's own credentials, it calls `GET .../connections/CONNECTION?view=BASIC`, `connectionSchemaMetadata:getEntityType`, and `connectionSchemaMetadata:getAction`, which require `connectors.connections.get` and `connectors.connections.getConnectionSchemaMetadata` (`roles/connectors.viewer` has both; `roles/connectors.invoker` does **not**). Grant `roles/integrations.integrationInvoker` (to `:execute` the `ExecuteConnection` integration) + `roles/connectors.viewer` (or a custom role with `connectors.connections.get` and `connectors.connections.getConnectionSchemaMetadata`) for connection mode. `roles/secretmanager.secretAccessor` is not needed for the toolset itself (the ADK client does not read Secret Manager).

## Resuming Suspended Executions (`suspensions:lift` and `suspensions:resolve`)

An execution paused at a **Suspend** or **Approval** task waits until its expiration timer elapses (up to 44,640 minutes / 31 days) or until resolved via the Suspensions REST API (or the Cloud console UI). Once resumed, the remainder of the execution runs asynchronously. Always confirm with the user before lifting or resolving a suspension.

- **Required IAM**: `integrations.suspensions.resolve` for `suspensions:resolve` (Approval), `integrations.suspensions.lift` for `suspensions:lift` (Suspend), and `integrations.suspensions.list` for `suspensions.list` (all three are included in `roles/integrations.suspensionResolver` and `roles/integrations.integrationAdmin`, and none are in `roles/integrations.integrationEditor`; `roles/integrations.suspensionResolver` alone cannot read execution records, so also grant `roles/integrations.integrationViewer` to inspect `taskExecutionDetails` or run `:troubleshoot`, or use the approval email link, which carries the execution and task IDs) **plus** `roles/iam.serviceAccountUser` on the integration's `runAsServiceAccount`.
- **Approve or reject an Approval task (`suspensions:resolve`)** — this is the same call the Cloud console Approve/Reject buttons make (confirm with user before running):
  ```bash
  curl -sS --fail-with-body -X POST \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json" \
    -d '{
      "suspension": {
        "eventExecutionInfoId": "EXECUTION_ID",
        "integration": "INTEGRATION_NAME",
        "taskId": "TASK_ID",
        "state": "LIFTED"
      }
    }' \
    "https://integrations.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/integrations/INTEGRATION_NAME/executions/EXECUTION_ID/suspensions/SUSPENSION_ID:resolve"
  ```
  Pass `"state": "LIFTED"` to approve or `"state": "REJECTED"` to reject (`Suspension.state` enum values: `PENDING`, `REJECTED`, `LIFTED`).
- **Lift a Suspend task (`suspensions:lift`)** — the Suspend-task variant, which accepts an optional `suspensionResult` (defaults to `Resolved`, or `Expired` on timeout; `-` can replace `INTEGRATION_NAME` and either `EXECUTION_ID` or `SUSPENSION_ID`, provided at least one of `EXECUTION_ID` or `SUSPENSION_ID` is concrete—omitting both returns an error; confirm with user before running):
  ```bash
  # Both IDs known (or replace INTEGRATION_NAME with "-" and either EXECUTION_ID or SUSPENSION_ID with "-")
  curl -sS --fail-with-body -X POST \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json" \
    -d '{"suspensionResult": "Approved"}' \
    "https://integrations.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/integrations/INTEGRATION_NAME/executions/EXECUTION_ID/suspensions/SUSPENSION_ID:lift"
  ```

License (Apache-2.0)

View full license text
Licensed under the Apache License, Version 2.0. See https://github.com/google/skills/blob/main/LICENSE