﻿# 如何避免 Pull request 的 Build Validation 同時觸發 Release 部署網站

我們過往設定 CI/CD 的時候，為了要避免 Pull request 的時候也不小心觸發 Release 部署網站，我們都會建立另外一組 Build pipeline 專門給 Pull request 時使用 ( 特定 Branch 的 Build Validation )。不過，這個額外的 Build pipeline 跟原本分支的 Build pipeline 完全一樣，額外維護這份 Pipelines 顯得非常多餘。我今天終於研究出正確的設定方式，所以這篇文章將來說明正確的設定方式。

老實說，這個問題困擾了我好幾年，但是解決方案卻是如此簡單，只要設定 **Build branch filters** 就可以解決此問題！😍

![Release pipelines](https://stwillblogassets.blob.core.windows.net/files/images/external/user-images.githubusercontent.com/17d0a2a767b06a972dfe-169279584-343d0d2a-581b-4b30-af0b-b1f29cc9a9ec.png)

以下是完整的設定步驟：

1.  建立初始專案，並初始化 Git 版控，假設開發用的分支名稱為 `develop`
    
2.  將專案原始碼推送到 Azure Repos
    
3.  到 Azure Pipelines 建立一個 Build pipeline
    
    假設 Pipeline 名稱為 `CI-develop`
    
    取得原始碼請設定 **Default branch** 為 `develop`
    
4.  到 Azure Pipelines 建立一個 Release pipeline
    
    假設 Release 名稱為 `CD-develop`
    
    透過 Add Artifacts 加入 `CI-develop` 最新版建置結果
    
    點擊 ⚡ 設定 **Continuous deployment trigger** 為 **Enabled**
    
    設定 **Build branch filters** 加入 `The build pipeline's default branch`
    
    > 由於 Build pipeline 一定會綁定 Azure Repos 的一個分支，所以就不用在 **Build branch filters** 設定固定的分支名稱！
    
    設定好 Stages 部署設定
    
5.  設定 Azure Repos 專案中 `develop` 分支的 **Branch policies**
    
6.  將 `CI-develop` 加入 **Build Validation**
    

大功告成！ 🔥

由於我們在 **Continuous deployment trigger** 額外設定了一個 **Build branch filters** 條件，所以當我們在發佈 Pull request (PR) 的時候，由於 PR 還沒有真正合併回 `develop` 分支，由於 Artifacts 被限制只有 `The build pipeline's default branch` 才能取得，因此不會真的觸發 Stages 中的發行工作！ 👍

### 針對 Stages 設定部署的條件

有時候一個 Release 會有多個 Stages 需要部署，所以你也可以利用每個 Stage 的 **Pre-deployment conditions** 設定 `Artifact filters` 來設定一個部署條件，只有條件達成才會執行這個 Stage 的 Tasks：

![Release pipelines](https://stwillblogassets.blob.core.windows.net/files/images/external/user-images.githubusercontent.com/54a8b3ddd373d0bae098-169277636-900a16f6-9582-4413-b12e-0f5f25bcce17.png)

### 相關連結

-   [Azure Pipelines 文件](https://learn.microsoft.com/zh-tw/azure/devops/pipelines/?view=azure-devops&WT.mc_id=DT-MVP-4015686)
-   Azure Pipelines | Microsoft Docs
    -   [Release pipelines](https://learn.microsoft.com/en-us/azure/devops/pipelines/release/?view=azure-devops&WT.mc_id=DT-MVP-4015686)
    -   [Deploy from multiple branches](https://learn.microsoft.com/en-us/azure/devops/pipelines/release/deploy-multiple-branches?view=azure-devops&WT.mc_id=DT-MVP-4015686)
    -   [Deploy pull request Artifacts with classic release pipelines](https://learn.microsoft.com/en-us/azure/devops/pipelines/release/deploy-pull-request-builds?view=azure-devops&WT.mc_id=DT-MVP-4015686)
-   [Create a CI/CD pipeline for .NET with the DevOps Starter Project](https://www.azuredevopslabs.com/labs/vstsextend/azuredevopsprojectdotnet/)
