---
url: /en/build/trigger-rule.md
---
When `Cloud Native Build` receives various events, it automatically retrieves the `.cnb.yml` configuration file from the corresponding branch of the repository, parses the pipeline configuration for the corresponding event under that branch, and assigns a Runner to execute the build task.

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

Public repositories allow others to Fork. For security reasons, **Forked repositories will not execute corresponding 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 the `.cnb.yml` file configuration of each branch itself.
:::

### Matching Patterns

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

#### 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 | Additionally provides environment variable `CNB_NEW_COMMITS_COUNT` (number of new Commits), can be combined with `git log -n` to view new Commits |
| 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 | Pipeline configuration can be attached to branch name or `$`; pipeline uses **default branch** configuration file (because the branch has been 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](../../plugin/#public/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 latter configuration under the same branch name overriding the former. 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

In the following scenarios, mentioning the `NPC` role (such as `@npc`) 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) |

**Mention NPC Role**:

```text
@cnb/feedback(猿芳) Help me answer this issue.
```

Where `@` is followed by the repository path `cnb/feedback` where the NPC belongs, and the role name `猿芳` in parentheses.

**Mention System Role**:

```text
@CodeBuddy Help me answer this issue.
```

::: warning Note
Reopening PR or Issue, as well as editing descriptions or comments will not re-trigger NPC events.
A maximum of 10 NPC events can be triggered at once.
:::

#### NPC Role Configuration

In the `.cnb/settings.yml` file of the `cnb/docs` repository, NPC roles can be defined.

**Example**:

```yaml title=".cnb/settings.yml"
npc:
  roles:
    - name: Yuanfang
      prompt: |
        You refer to yourself as "Yuanfang" and call users "My Lord",
        Your catchphrase is 『There must be something suspicious about this!』,
        Before ending the conversation, politely reply with one line: "There must be a huge secret behind this.\n",
        You will output a meme image on the last line,
        Whether in daily conversation or explaining knowledge, you maintain the above style,
        Use Chinese 『～』 instead of all English 『~』,
        Answer the following questions with a humble tone
```

For detailed NPC configuration, please refer to [UI Customization Configuration File](../repo/settings.md).

#### Execution Flow

CNB will parse the pipeline configuration according to the following steps:

**Mention NPC Role**:

1. Load the `.cnb.yml` file under the default branch (such as `main`) of the repository where the NPC belongs
2. Parse the event configuration corresponding to `role name` from the configuration file (such as `Yuanfang`)
3. If no event configuration is matched under `role name`, parse the default event configuration under `$`
4. If no event pipeline configuration is parsed, use the system default NPC event pipeline configuration

**Mention System Role**:

Directly use the system default NPC event pipeline configuration.

**NPC Configuration Example**:

```yaml title=".cnb.yml"
.npc: &npc
  - stages:
      - name: echo extra env
        script: |
          echo $CNB_NPC_SLUG
          echo $CNB_NPC_NAME
          echo $CNB_NPC_PROMPT
          echo $CNB_NPC_AVATAR

# NPC events can match events under role names
Yuanfang:
  issue.comment@npc: *npc
  pull_request.comment@npc: *npc

# If NPC event is not defined under role name, parse under $
$:
  issue.comment@npc: *npc
  pull_request.comment@npc: *npc
```

After the NPC pipeline configuration loading and parsing is completed, it will be executed under the default branch of the repository where the current Issue or PR belongs, with the triggerer being the current operator.

#### Security Restrictions

For NPC events, the `CNB_TOKEN` in the pipeline environment variables is limited to accessing the current repository only.

#### Environment Variables

When the NPC event pipeline executes, some additional NPC-related [environment variables](./build-in-env.md#npc-variables) will be added.

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