---
url: /en/build/trigger-rule.md
description: >
  Explains how Cloud Native Build determines which pipelines to run in response
  to events, covering all supported trigger types (git operations, manual, API,
  scheduled, issue, NPC events) and branch/event matching rules.
---
When `Cloud Native Build` receives various events,
it automatically retrieves the `.cnb.yml` from the corresponding branch of the repository,
parses the pipeline configuration for that event, and assigns a Runner to execute it.

## Trigger Mechanism Overview

`Cloud Native Build` supports multiple event trigger methods, mainly including:

| Event Type            | Description                                                            |
|-----------------------|------------------------------------------------------------------------|
| Git Operation Events  | Code push, branch creation, PR operations, etc.                        |
| Page Operation Events | Manual trigger, button clicks, AI feature operations, etc.             |
| API Request Events    | Triggered through OPENAPI or built-in tasks                            |
| Scheduled Task Events | Triggered according to predetermined time schedules                    |
| Issue Events          | Issue operations, comments, etc.                                       |
| NPC Events            | Triggered when `@npc` appears in Issue or PR descriptions and comments |

### Trigger Flow Example

Taking the main branch code `push` event as an example, the trigger flow is as follows:

```mermaid
flowchart LR
    push(git push) --> config(read .cnb.yml from main branch) --> event(get push config from main branch) --> checkout(checkout main branch code) --> pipeline(Pipeline execution)
```

Code example:

```yaml title=".cnb.yml"
main:
  push:
    - stages: # multiple stages in one job run serially in order
        - name: job 1
          script: echo "do some job"
        - name: job 2
          script: echo "do some job"
```

### Fork Repository Trigger Restrictions

**Forked repositories will not execute pipelines by default for the following event types**:

* Git Operation Events
* Scheduled Task Events
* Issue Events

#### Enable Fork Repository Auto-Trigger

To allow these events to trigger pipelines,
go to **`Settings` → `Cloud Native Build`** on the repository page and check the following options:

* **Allow Auto Trigger**: When checked, the repository will automatically trigger Cloud Native Build
  according to .cnb.yml configuration
* **Forked Repositories Allow Auto Trigger by Default**: When checked, repositories forked from this
  repository will automatically trigger Cloud Native Build according to .cnb.yml configuration

> **Security Note**: When executing pipelines,
> Forked repositories have their default environment variable `CNB_TOKEN` scoped only to the **current repository** to
> ensure security.

## Trigger Branch {#trigger-branch}

The trigger branch refers to the branch in the code repository where the triggering event occurs,
used to match the corresponding pipeline configuration.

::: warning Important Note
Configuring pipelines for other branches under a specific branch will not cause events from other branches to execute
according to this configuration. Actual execution depends on each branch's own `.cnb.yml` file.
:::

### Matching Patterns

Branch names support `glob` pattern matching ([learn about glob matching](https://globster.xyz/)).

::: tip Glob Matching Rules

* `*` matches any character **except** `/`. For example, `dev/*` matches `dev/feature` but not `dev/team/feature`.
* `**` matches any character **including** `/`. For example, `dev/**` matches both `dev/feature` and `dev/team/feature`.

Use `**` when branch names contain multiple `/` levels.
:::

#### Common Matching Rules

The following four common matching patterns are shown individually. They can be combined in the same `.cnb.yml`:

**Match branches starting with `dev/`:**

```yaml title=".cnb.yml"
"dev/*":
  push:
    - stages:
        - name: do something
          script: echo "dev branch"
```

**Match `main` or `dev` branch:**

```yaml title=".cnb.yml"
"(main|dev)":
  push:
    - stages:
        - name: do something
          script: echo "main or dev"
```

**Exclude `main` and `dev`:**

```yaml title=".cnb.yml"
"**/!(main|dev)":
  push:
    - stages:
        - name: do something
          script: echo "not main or dev"
```

**Match all branches (including fallback `$`):**

```yaml title=".cnb.yml"
"**":
  push:
    - stages:
        - name: do something
          script: echo "all branches"
$:
  push:
    - stages:
        - name: do something
          script: echo "fallback"
```

| Pattern           | Scope                                              |
|-------------------|----------------------------------------------------|
| `dev/*`           | Branches starting with `dev/` (no multi-level `/`) |
| `(main\|dev)`     | `main` or `dev` branch                             |
| `**/!(main\|dev)` | All branches except `main` and `dev`               |
| `**`              | All branches                                       |
| `$`               | Fallback, branches not matched by glob             |

### Matching Strategy

The system performs branch matching in stages according to priority,
only entering the next stage when the previous stage does not match:

| Priority | Matching Stage        | Description                                        |
|----------|-----------------------|----------------------------------------------------|
| 1        | Glob Pattern Matching | Try to match branch names with all glob rules      |
| 2        | Fallback Matching     | Use `$` rule to match branches not matched by glob |

> **Parallel Execution**: If multiple glob rules match simultaneously,
> pipelines for all matching rules will execute **in parallel**.

## Trigger Events {#trigger-event}

### Git Operation Events

#### Branch Events

Events triggered by remote code branch changes.

| Event Name    | Trigger Timing               | Description                                                       |
|---------------|------------------------------|-------------------------------------------------------------------|
| push          | Triggered on branch push     | The most commonly used trigger event                              |
| commit.add    | Push contains new commits    | Provides `CNB_NEW_COMMITS_COUNT`                                  |
| branch.create | Triggered on branch creation | Also triggers `push`; also triggers `commit.add` with new commits |
| branch.delete | Triggered on branch deletion | Uses **default branch** latest code and config                    |

**Additional notes on branch events**:

* **commit.add**: Provides `CNB_NEW_COMMITS_COUNT` (number of new Commits),
  usable with `git log -n` to view new Commits
* **branch.create**: Also triggers `push` event; if the push contains new commits, `commit.add` is also triggered
* **branch.delete**: Uses the **default branch** latest code and configuration file
  (since the branch is deleted at runtime)

**branch.delete and tag\_push share the same matching rules**: both support exact
names, glob patterns, and `$` fallback. The `branch.delete` example is shown below,
and the `tag_push` (Tag event) example can be found in the [Tag Events](#tag-events) section below.

```yaml title=".cnb.yml"
# Exact match
main:
  branch.delete:
    - stages:
        - name: echo
          script: echo $CNB_BRANCH
# Fallback
$:
  branch.delete:
    - stages:
        - name: echo
          script: echo $CNB_BRANCH
```

#### Pull Request Events

Events triggered by Pull Request (hereinafter referred to as PR) related operations.

| Event Name                     | Trigger Timing                                                                       |
|--------------------------------|--------------------------------------------------------------------------------------|
| pull\_request                   | PR creation, reopening, source branch push                                           |
| pull\_request.update            | PR creation, reopening, source branch push, title/description modification           |
| pull\_request.target            | PR creation, reopening, source branch push                                           |
| pull\_request.mergeable         | Triggered when open PR meets specific conditions                                     |
| pull\_request.merged            | Triggered when PR merge is completed                                                 |
| pull\_request.approved          | Triggered when user reviews PR as "Allow Merge"                                      |
| pull\_request.changes\_requested | Triggered when user reviews PR as "Changes Requested"                                |
| pull\_request.comment           | Triggered when PR comment is created                                                 |

**Additional note on pull\_request.update**: In addition to `pull_request` triggers,
PR title or description modifications also trigger this event.

::: tip Difference between pull\_request and pull\_request.update
`pull_request` is a subset of `pull_request.update`:

* PR title, description modification → triggers `pull_request.update` but not `pull_request`
* PR creation, reopening, source branch push → triggers both `pull_request` and `pull_request.update`
  :::

::: tip Difference between pull\_request and pull\_request.target
For detailed differences, please refer to [Code Version Selection](#code-version-selection).
:::

#### pull\_request.mergeable Trigger Conditions

Triggered when an open PR simultaneously meets the following conditions:

1. Target branch is a **protected branch**, with the following rules checked:
   * Requires reviewer approval
   * Requires passing status checks (optional)

2. Mergeable:
   * No code conflicts
   * Status checks passed (if "requires passing status checks" is checked and there are status checks)

3. Review approved

::: warning pull\_request.mergeable Notes

* Configuration file is taken from the target branch, refer to [Code Version Selection](#code-version-selection)
* PR target branch must have this event pipeline configured for the corresponding pipeline to execute when this event
  is triggered
* When CI file parsing fails, if the target branch is a protected branch with status checks enabled,
  a failed status is reported to block merging. Non-protected branches do not report.
  :::

::: warning pull\_request.merged Notes
When branch a is merged into branch b, it will trigger `pull_request.merged` and `push` events under branch b.
:::

::: warning pull\_request.approved Notes
Settings may require multiple reviewers for protected branches;
a user passing review doesn't necessarily mean the PR is in an approved state.
:::

#### Tag Events

Events triggered by remote code and page Tag related operations.

| Event Name   | Trigger Timing             | Description                                    |
|--------------|----------------------------|------------------------------------------------|
| tag\_push     | Triggered on Tag push      | Used for automated processing after Tag push   |
| auto\_tag     | Auto-generated Tag trigger | See "auto\_tag Auto Generate Tag" section below |
| tag\_deploy.\* | Triggered via "Deploy" btn | Details refer to [Deploy](./deploy.md)         |

**tag\_push**: Triggered on Tag push, supporting exact Tag names, glob patterns,
and `$` fallback. Configuration structure is as follows:

```yaml title=".cnb.yml"
# Exact match
v1.0.0:
  tag_push:
    - stages:
        - name: echo
          script: echo $CNB_BRANCH
# glob pattern match
v*:
  tag_push:
    - stages:
        - name: echo
          script: echo $CNB_BRANCH
# Fallback
$:
  tag_push:
    - stages:
        - name: echo
          script: echo $CNB_BRANCH
```

#### auto\_tag Auto Generate Tag {#auto\_tag}

**Trigger Method**: Only supported by clicking the "Auto Generate Tag" button on the repository Tag list page.
The button starts a pipeline on the branch specified by `tag.auto_tag.branch`
(defaults to the repository default branch), which can be configured in `.cnb/settings.yml`
via [Tag Auto-Generation Configuration](../repo/settings-tag.md).

**Implementation Principle**: Starts a pipeline,
defaulting to use the [cnbcool/git-auto-tag](https://cnb.cool/cnb/plugins/cnbcool/git-auto-tag)
plugin to implement automatic Tag generation.

**Tag Format Description**:

* Default format is `3.8.11` type
* If the latest Tag starts with `v`, the automatically generated Tag will also have `v`, such as `v4.1.9`

**Custom Configuration**:

```yaml title=".cnb.yml"
main:
  auto_tag:
    - stages:
        - name: release rules
          script: echo -e "$RELEASE_RULES"
        - name: auto tag
          image: cnbcool/git-auto-tag:latest
          settings:
            tagFormat: 'v\${version}'
            branch: $CNB_BRANCH
            repoUrlHttps: $CNB_REPO_URL_HTTPS
            releaseRules: $RELEASE_RULES
          exports:
            tag: NEW_TAG
        # exports is scoped to the current Pipeline; use it in a later stage of the same Pipeline
        - name: show tag
          script: echo $NEW_TAG
```

::: warning Configuration Override Rules
Default configuration will be merged with .cnb.yml,
with the later configuration under the same branch name overriding the earlier one.
If `auto_tag` configuration in `.cnb.yml` is under `$` rather than the default branch name,
both `auto_tag` configurations will be retained, but the configuration under `$` will be ignored.
Refer to [include Merge Rules](./configuration.md#merge-rules).
:::

***

### Page Operation Events

#### web\_trigger Custom Event {#web\_trigger}

**Event Name Format**: `web_trigger` or starting with `web_trigger_`, such as `web_trigger_test`.

**Trigger Method**: Only supported by triggering events on the page.

**Usage Scenarios**:

| Scenario             | Description                                                   |
|----------------------|---------------------------------------------------------------|
| Deploy Capability    | Used in combination with [Deploy](./deploy.md) capability     |
| Custom Button        | [Custom Buttons](./web-trigger.md) on the page                |
| Manual Build Trigger | Supports inputting environment variables (only `web_trigger`) |

#### Cloud Native Development Event {#vscode}

Event triggered by clicking the "Cloud Native Development" button on the page.
Details refer to [Cloud Native Development](../workspaces/intro.md).

***

### API Request Events

#### api\_trigger Custom Event {#api\_trigger}

**Event Name Format**: `api_trigger` or starting with `api_trigger_`, such as `api_trigger_test`.

**Trigger Methods**:

| Trigger Source | Description                                                 |
|----------------|-------------------------------------------------------------|
| cnb:apply      | Refer to [cnb:apply](./internal-steps/cnb/apply.md)           |
| cnb:trigger    | Refer to [cnb:trigger](./internal-steps/cnb/trigger.md)       |
| OPENAPI        | Refer to [OPENAPI](https://api.cnbprod.alpha.qq.com/#/operations/StartBuild) |

::: tip Tip
Methods 1 and 2 are wrappers for method 3.
:::

***

### Scheduled Task Events

Events triggered by scheduled tasks. Details refer to [Scheduled Tasks](./crontab.md).

***

### Issue Events

Events triggered by Issue related operations.

::: warning Configuration Requirements
Issue event pipeline configurations need to be attached under `$`.
:::

| Event Name                   | Trigger Timing                                       |
|------------------------------|------------------------------------------------------|
| issue.open                   | When Issue is created                                |
| issue.close                  | When Issue is closed                                 |
| issue.reopen                 | When Issue is reopened                               |
| issue.update                 | Name, description, assignee, labels, priority change |
| issue.update.assignee\_change | When Issue assignee changes                          |
| issue.update.priority\_change | When Issue priority changes                          |
| issue.update.label\_change    | When Issue labels change                             |
| issue.comment                | When Issue is commented                              |

The following example attaches `issue.open` and `issue.comment` pipelines under `$`,
so that the tasks run when an Issue is created or commented on:

```yaml title=".cnb.yml"
$:
  issue.open:
    - stages:
        - name: notice issue
          script: echo "$CNB_ISSUE_TITLE" opened
  issue.comment:
    - stages:
        - name: notice issue
          script: echo "$CNB_ISSUE_TITLE" commented
```

Other events (such as `issue.close`, `issue.update`, etc.) follow the same pattern;
simply replace the event name.
For a more complete notification example (such as pushing to a WeCom group when an Issue changes),
see [Issue Notification Example](./showcase/issue-notice-group.md).

:::: warning Comment Count Limit
When the comment count of an Issue or PR exceeds 100,
the corresponding `issue.comment` / `pull_request.comment`
and `@npc` events will no longer trigger any pipeline.
::::

***

### NPC Events {#trigger-npc-scenes}

In the following scenarios, mentioning an `NPC` role (such as `@npc`)
in a description or comment will trigger the `NPC` event:

| Scenario                   | Trigger Event              |
|----------------------------|----------------------------|
| Issue description creation | `issue.comment@npc`        |
| Issue comment              | `issue.comment@npc`        |
| PR description creation    | `pull_request.comment@npc` |
| PR review                  | `pull_request.comment@npc` |
| PR comment                 | `pull_request.comment@npc` |
| PR review comment          | `pull_request.comment@npc` |

For more information, see [NPC Documentation](./npc.md)

## Code Version Selection

When an event is triggered,
the corresponding code version needs to be determined to retrieve and parse the corresponding `.cnb.yml`,
checkout the code, and execute the pipeline.

### Version Selection Strategy

| Event Type                                  | Code Version Selection                      |
|---------------------------------------------|---------------------------------------------|
| push, commit.add, branch.create, vscode     | Latest Commit of current branch             |
| auto\_tag, branch.delete, issue.\*            | Latest Commit of default branch             |
| tag\_push, tag\_deploy.\*                      | Current Tag                                 |
| pull\_request                                | Pre-merged Commit                           |
| pull\_request.update                         | Pre-merged Commit                           |
| pull\_request.approved                       | Pre-merged Commit                           |
| pull\_request.changes\_requested              | Pre-merged Commit                           |
| pull\_request.comment                        | Pre-merged Commit (see note 3)              |
| pull\_request.comment@npc                    | Latest Commit of target branch (see note 4) |
| issue.comment@npc                           | Latest Commit of default branch             |
| pull\_request.merged                         | Merged Commit                               |
| pull\_request.target, pull\_request.mergeable | Latest Commit of target branch before merge |
| api\_trigger                                 | Version can be specified (see note 1)       |
| web\_trigger                                 | Read config from branch/Tag (see note 2)    |
| Scheduled Task                              | Latest Commit of specified branch           |
| Rebuild                                     | Current build Commit                        |

**Additional notes**:

1. **api\_trigger**: Version can be specified; `cnb:apply` is limited to current build Commit
2. **web\_trigger**: Read configuration file from corresponding branch or Tag, refer to specific application scenarios
3. **pull\_request.comment**: When the PR is already merged, uses the merged Commit
   (the source branch may have been deleted; no pre-merge is performed)
4. **pull\_request.comment@npc**:
   * Cross-repo fork PR triggered by the PR author: uses the source repository's source branch code
   * PR already merged: uses the merged Commit (the source branch may have been deleted);
     `git cherry-pick` can sync commits to other branches

## Untrusted Events {#untrusted-events}

Untrusted events refer to event types where the code source or trigger is uncontrollable.

### Event List

The following events are untrusted events:

**Pull Request Related Events**:

* `pull_request`: PR creation or source branch push
* `pull_request.update`: PR content update (including title, description modification)
* `pull_request.approved`: PR approval passed
* `pull_request.changes_requested`: PR approval rejected
* `pull_request.comment`: PR comment
* `pull_request.comment@npc`: Triggered when `@npc` appears in PR descriptions or comments

**Issue Related Events**:

* `issue.open`: Issue created
* `issue.reopen`: Issue reopened
* `issue.close`: Issue closed
* `issue.update`: Issue content update (including title, description modification)
* `issue.update.assignee_change`: Issue assignee changed
* `issue.update.priority_change`: Issue priority changed
* `issue.update.label_change`: Issue label changed
* `issue.comment`: Issue comment
* `issue.comment@npc`: Triggered when `@npc` appears in Issue descriptions or comments

### Risk Scenarios

**PR Events**:

Pipeline configuration originates from the source branch and may be modified by unauthorized users,
with the following risks:

* Malicious code injection or sensitive content leakage
* Build artifacts (such as images, binary files) being tampered with
* Referencing secret repository files leading to key or credential leakage

**Issue and Comment Events**:

Creating, closing, reopening, editing and commenting on an Issue require no write access to the
repository, so the trigger may not be a repository member or administrator:

* Accessing the triggerer's resources leading to data leakage
* Tampering with the triggerer's resources causing damage

**NPC Events**:

The pipeline can be provided by the `NPC`'s repository, and the trigger is the commenter, with stacked risks:

* `NPC` configuration source is uncontrollable and may be maliciously tampered with
* Both commenter resource leakage and tampering risks exist simultaneously

### Security Measures

To reduce the above risks, the system takes the following protective measures for untrusted events:

* **CNB\_TOKEN Permission Restriction**: The [CNB\_TOKEN](./build-in-env.md#cnb_token) built into the pipeline
  environment variables has strictly limited permissions to prevent unauthorized access
* **CNB\_TOKEN Role Cap**: For non-NPC untrusted events, the maximum role of the
  [CNB\_TOKEN](./build-in-env.md#cnb_token) is fixed to `Reporter`, so a triggerer with a higher role
  is also evaluated as a Reporter
* **File Reference Explicit Declaration**: When untrusted event pipelines reference external files, the referenced
  files must explicitly declare through `allow_events` which events are allowed to reference them,
  avoiding sensitive files being accidentally referenced

### Usage Recommendations

::: tip Security Recommendations

* **Choose Trusted NPCs**: When commenting, prioritize NPC roles provided by trusted repositories
* **Isolate Sensitive Tasks**: Tasks involving key operations, sensitive data processing,
  and other important content are recommended to be executed in trusted events such as push, pull\_request.target, tag\_push
  :::
