---
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: # Trigger branch
  push: # Trigger event, corresponding to a build, can contain multiple Pipelines. Can be an array or an object.
    - stages: # Pipeline 1
        - echo "do some job"
    - stages: # Pipeline 2
        - 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:

| Setting Option | Description |
|---------------|-------------|
| 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

```yaml title=".cnb.yml"
.push_pipeline: &push_pipeline
  stages:
    - name: do something
      script: echo "do something"

# Match all branches starting with dev/
"dev/*":
  push:
    - *push_pipeline

# Match main or dev branches
"(main|dev)":
  push:
    - *push_pipeline

# Match all branches except main and dev
"**/!(main|dev)":
  push:
    - *push_pipeline

# Match all branches
"**":
  push:
    - *push_pipeline

# Fallback, match branches not matched by glob
"$":
  push:
    - *push_pipeline
  tag_push:
    - *push_pipeline
```

### 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 all 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 | Triggered when branch push contains new commits | Provides `CNB_NEW_COMMITS_COUNT` (number of new Commits), usable with `git log -n` to view |
| branch.create | Triggered on branch creation | Also triggers `push` event; if there are new commits, also triggers `commit.add` event |
| branch.delete | Triggered on branch deletion | Uses the **default branch** configuration file (since the branch is deleted at runtime) |

**branch.delete Example**:

```yaml title=".cnb.yml"
dev/1:
  branch.delete:
    - stages:
        - name: echo
          # CNB_BRANCH value is the deleted branch
          script: echo $CNB_BRANCH
$:
  branch.delete:
    - stages:
        - name: echo
          # CNB_BRANCH value is the deleted branch
          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, PR title or 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 |

::: 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
  :::

::: 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 | Triggered when Tag is automatically generated | Only supported by clicking the "Auto Generate Tag" button on the repository Tag list page |
| tag\_deploy.\* | Triggered via the "Deploy" button on the repository Tag/Release page | Details refer to [Deploy](./deploy.md) |

**tag\_push Example**:

```yaml title=".cnb.yml"
# Effective for specified tags
v1.0.*:
  tag_push:
    - stages:
        - name: echo tag name
          script: echo  $CNB_BRANCH

# Effective for all tags
$:
  tag_push:
    - stages:
        - name: echo tag name
          script: echo  $CNB_BRANCH
```

#### auto\_tag Auto Generate Tag

**Trigger Method**: Only supported by clicking the "Auto Generate Tag" button on the repository Tag list page.

**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: # Default branch, can be replaced with the actual default branch of the repository
  auto_tag:
    - stages:
        - name: release rules
          # This environment variable is passed in when triggering the build, can view print content to see 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
    - 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 supports triggering `web_trigger` event) |

#### 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) |
| cnb:trigger | Refer to [cnb:trigger](./internal-steps/#cnb-trigger) |
| OPENAPI | Refer to OPENAPI |

::: 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 | When Issue 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 |

***

### 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 when creating | `issue.comment@npc` |
| Issue comment | `issue.comment@npc` |
| PR description when creating | `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, pull\_request.update, pull\_request.approved, pull\_request.changes\_requested, pull\_request.comment | Pre-merged Commit |
| pull\_request.comment@npc | Latest Commit of target branch (for cross-repo fork PRs, uses source repository's source branch when triggered by PR author) |
| 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; [cnb:apply](./internal-steps/#cnb-apply) limited to current build Commit |
| web\_trigger | Read configuration file from corresponding branch, Tag, refer to specific application scenarios |
| Scheduled Task | Latest Commit of specified branch |
| Rebuild | Current build Commit |

## 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.comment`: Issue comment
* `issue.comment@npc`: Triggered when `@npc` appears in Issue descriptions or comments

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

### 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

**Comment Events**:

The trigger is the commenter, who may not be a repository member or administrator:

* Accessing commenter resources leading to data leakage
* Tampering with commenter 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:

| Security Measure | Description |
|-----------------|-------------|
| 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 |
| 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
  :::
