教學課程:使用 Jenkins 和 Azure CLI 來部署到 Azure App ServiceTutorial: Deploy to Azure App Service with Jenkins and the Azure CLI

若要將 Java Web 應用程式部署到 Azure,您可以在 Jenkins 管線中使用 Azure CLI。To deploy a Java web app to Azure, you can use Azure CLI in a Jenkins Pipeline. 在此教學課程中,您會執行下列工作:In this tutorial, you do the following tasks:

  • 建立 Jenkins VMCreate a Jenkins VM
  • 設定 JenkinsConfigure Jenkins
  • 在 Azure 中建立 Web 應用程式Create a web app in Azure
  • 準備 GitHub 存放庫Prepare a GitHub repository
  • 建立 Jenkins 管線Create Jenkins pipeline
  • 執行管線並確認 Web 應用程式Run the pipeline and verify the web app

建立及設定 Jenkins 執行個體Create and configure Jenkins instance

如果您還沒有 Jenkins 主要伺服器,請在 Linux VM 上安裝 JenkinsIf you do not already have a Jenkins master, install Jenkins on a Linux VM.

「Azure 認證」外掛程式可讓您將 Microsoft Azure 服務主體認證儲存在 Jenkins 中。The Azure Credential plug-in allows you to store Microsoft Azure service principal credentials in Jenkins. 在 1.2 版中,我們已新增支援,因此 Jenkins 管線可以取得 Azure 認證。In version 1.2, we added the support so that Jenkins Pipeline can get the Azure credentials.

請確定您擁有的版本是 1.2 或更新版本:Ensure you have version 1.2 or later:

  • 在 Jenkins 儀表板中,按一下 [Manage Jenkins] (管理 Jenkins) -> [Plugin Manager] (外掛程式管理員)****,然後搜尋 [Azure Credential] (Azure 認證)****。Within the Jenkins dashboard, click Manage Jenkins -> Plugin Manager -> and search for Azure Credential.
  • 如果版本比 1.2 版舊,請更新外掛程式。Update the plug-in if the version is earlier than 1.2.

Jenkins Master 中也必須有 Java JDK 和 Maven。Java JDK and Maven are also required in the Jenkins master. 若要安裝,請使用 SSH 登入 Jenkins Master,然後執行下列命令:To install, sign in to Jenkins master using SSH and run the following commands:

sudo apt-get install -y openjdk-7-jdk
sudo apt-get install -y maven

將 Azure 服務主體新增到 Jenkins 認證Add Azure service principal to a Jenkins credential

必須要有 Azure 認證,才能執行 Azure CLI。An Azure credential is needed to execute Azure CLI.

  • 在 Jenkins 儀表板中,按一下 [Credentials] (認證) -> [System] (系統) -> ****。Within the Jenkins dashboard, click Credentials -> System ->. 按一下 [Global credentials(unrestricted)] (全域認證 (不受限))****。Click Global credentials(unrestricted).
  • 按一下 [Add Credentials] (新增認證) 來填寫 [Subscription ID] (訂用帳戶 ID)、[Client ID] (用戶端識別碼)、[Client Secret] (用戶端祕密) 及 [OAuth 2.0 Token Endpoint] (OAuth 2.0 權杖端點),以新增 Microsoft Azure 服務主體Click Add Credentials to add a Microsoft Azure service principal by filling out the Subscription ID, Client ID, Client Secret, and OAuth 2.0 Token Endpoint. 請提供一個要在後續步驟中使用的識別碼。Provide an ID for use in subsequent step.

新增認證

建立 Azure App Service 來部署 Java Web 應用程式Create an Azure App Service for deploying the Java web app

使用 az appservice plan create CLI 命令,建立搭配免費定價層的 Azure App Service 方案。Create an Azure App Service plan with the FREE pricing tier using the az appservice plan create CLI command. Appservice 方案會定義用來託管應用程式的實體資源。The appservice plan defines the physical resources used to host your apps. 所有指派給 Appservice 方案的應用程式都會共用這些資源,從而讓您節省託管多個應用程式的成本。All applications assigned to an appservice plan share these resources, allowing you to save cost when hosting multiple apps.

az appservice plan create \
    --name myAppServicePlan \ 
    --resource-group myResourceGroup \
    --sku FREE

方案準備妥當時,Azure CLI 會顯示類似下列範例的輸出:When the plan is ready, the Azure CLI shows similar output to the following example:

{ 
  "adminSiteName": null,
  "appServicePlanName": "myAppServicePlan",
  "geoRegion": "North Europe",
  "hostingEnvironmentProfile": null,
  "id": "/subscriptions/0000-0000/resourceGroups/myResourceGroup/providers/Microsoft.Web/serverfarms/myAppServicePlan",
  "kind": "app",
  "location": "North Europe",
  "maximumNumberOfWorkers": 1,
  "name": "myAppServicePlan",
  ...
  < Output has been truncated for readability >
} 

建立 Azure Web 應用程式Create an Azure web app

使用 az webapp create CLI 命令,在 myAppServicePlan App Service 方案中建立 Web 應用程式定義。Use the az webapp create CLI command to create a web app definition in the myAppServicePlan App Service plan. Web 應用程式定義會提供一個 URL 以存取您的應用程式,並設定數個選項將您的程式碼部署至 Azure。The web app definition provides a URL to access your application with and configures several options to deploy your code to Azure.

az webapp create \
    --name <app_name> \ 
    --resource-group myResourceGroup \
    --plan myAppServicePlan

使用您自己的唯一應用程式名稱來取代 <app_name> 預留位置。Substitute the <app_name> placeholder with your own unique app name. 這個唯一名稱會是 Web 應用程式預設網域名稱的一部分,因此,這個名稱在 Azure 的所有應用程式中必須是唯一的。This unique name is part of the default domain name for the web app, so the name needs to be unique across all apps in Azure. 您可以先將自訂的網域名稱項目對應至 Web 應用程式,再將它公開給使用者。You can map a custom domain name entry to the web app before you expose it to your users.

Web 應用程式定義備妥之後,Azure CLI 會顯示類似下列範例的資訊:When the web app definition is ready, the Azure CLI shows information similar to the following example:

{
  "availabilityState": "Normal",
  "clientAffinityEnabled": true,
  "clientCertEnabled": false,
  "cloningInfo": null,
  "containerSize": 0,
  "dailyMemoryTimeQuota": 0,
  "defaultHostName": "<app_name>.azurewebsites.net",
  "enabled": true,
   ...
  < Output has been truncated for readability >
}

設定 JavaConfigure Java

使用 az appservice web config update 命令來設定您的應用程式需要的 Java 執行階段組態。Set up the Java runtime configuration that your app needs with the az appservice web config update command.

下列命令會將 Web 應用程式設定為在最新的 Java 8 JDK 和 Apache Tomcat 8.0 上執行。The following command configures the web app to run on a recent Java 8 JDK and Apache Tomcat 8.0.

az webapp config set \ 
    --name <app_name> \
    --resource-group myResourceGroup \ 
    --java-version 1.8 \ 
    --java-container Tomcat \
    --java-container-version 8.0

準備 GitHub 存放庫Prepare a GitHub repository

  1. 開啟適用於 Azure 的簡單 Java Web 應用程式存放庫。Open the Simple Java Web App for Azure repo. 為了將存放庫分支至您自己的 GitHub 帳戶,按一下右上角的 [分支]**** 按鈕。To fork the repo to your own GitHub account, click the Fork button in the top right-hand corner.

  2. 在 GitHub Web UI 中,開啟 Jenkinsfile 檔案。In GitHub web UI, open Jenkinsfile file. 按一下鉛筆圖示來編輯此檔案,更新您 Web 應用程式的資源群組和名稱 (分別位於第 20 行和第 21 行)。Click the pencil icon to edit this file to update the resource group and name of your web app on line 20 and 21 respectively.

    def resourceGroup = '<myResourceGroup>'
    def webAppName = '<app_name>'
    
  3. 變更第 23 行以更新您 Jenkins 執行個體中的認證識別碼Change line 23 to update credential ID in your Jenkins instance

    withCredentials([azureServicePrincipal('<mySrvPrincipal>')]) {
    

建立 Jenkins 管線Create Jenkins pipeline

在網頁瀏覽器中開啟 Jenkins,按一下 [New Item] (新增項目)****。Open Jenkins in a web browser, click New Item.

  1. 輸入作業的名稱。Enter a name for the job.
  2. 選取 [管線]。Select Pipeline.
  3. 選取 [確定]。Select OK.
  4. 選取 [管線]。Select Pipeline.
  5. 針對 [Definition] (定義) ,選取 [Pipeline script from SCM] (來自 SCM 的管線指令碼) 。For Definition, select Pipeline script from SCM.
  6. 針對 [SCM] ,選取 [Git] 。For SCM, select Git.
  7. 輸入您分支存放庫的 GitHub URL:https:\<your forked repo\>.gitEnter the GitHub URL for your forked repo: https:\<your forked repo\>.git
  8. 選取 [儲存]。Select Save

測試您的管線Test your pipeline

  1. 移至您建立的管線Go to the pipeline you created
  2. 按一下 [立即建置]。Click Build Now
  3. 建置完成後,請選取 [主控台輸出] 以查看組建詳細資料。After the build completes, select Console Output to see build details.

確認您的 Web 應用程式Verify your web app

請執行下列作業,確認 WAR 檔案是否已順利部署到您的 Web 應用程式。Do the following to verify the WAR file is deployed successfully to your web app.

  1. 請開啟網頁瀏覽器:Open a web browser:

  2. 瀏覽至 http://&lt;app_name>.azurewebsites.net/api/calculator/pingBrowse to http://&lt;app_name>.azurewebsites.net/api/calculator/ping

  3. 您應該會看到類似以下的輸出:You should see text similar to the following:

    Welcome to Java Web App!!! This is updated!
    Today's date
    
  4. 移至 http://<app_name>.azurewebsites.net/api/calculator/add?x=<x>&y=<y> (以任何數字取代 <x> 和 <y>) 以取得 x 和 y 的總和Go to http://<app_name>.azurewebsites.net/api/calculator/add?x=<x>&y=<y> (substitute <x> and <y> with any numbers) to get the sum of x and y

    計算機:加法

部署到 Linux 上的 Azure Web 應用程式Deploy to Azure Web App on Linux

在 Jenkins 管線中使用 Azure CLI 後,請修改指令碼以部署至 Linux 上的 Azure Web 應用程式。Once you use Azure CLI in your Jenkins pipeline, modify the script to deploy to an Azure Web App on Linux. Linux 上的 Web 應用程式可支援 Docker。Web Apps on Linux supports Docker. 因此,您可提供一個 Dockerfile,此檔案會將您的 Web 應用程式與服務執行階段封裝成 Docker 映像。As such, you provide a Dockerfile that packages your web app with service runtime into a Docker image. 外掛程式會建置該映像,將其推送到 Docker 登錄,然後將該映像部署到您的 Web 應用程式。The plug-in builds the image, pushes it to a Docker registry, and deploys the image to your web app.

  1. 建立在 Linux 上執行的 Azure Web 應用程式Create an Azure Web App running on Linux.

  2. 在您的 Jenkins 上安裝 DockerInstall Docker on your Jenkins.

  3. 在 Azure 入口網站中建立容器登錄Create a Container Registry in the Azure portal.

  4. 在您所分支的相同適用於 Azure 的簡單 Java Web 應用程式存放庫中,編輯 Jenkinsfile2 檔案,如下所是:In the same Simple Java Web App for Azure repo you forked, edit the Jenkinsfile2 file as follows:

    1. 更新您的資源群組、Web 應用程式和 ACR 的名稱 (以您的值取代預留位置)。Update to the names of your resource group, web app, and ACR (replacing the placeholders with your values).

      def webAppResourceGroup = '<myResourceGroup>'
      def webAppName = '<app_name>'
      def acrName = '<myRegistry>'
      
    2. <azsrvprincipal\> 更新為您的認證識別碼Update <azsrvprincipal\> to your credential ID

      withCredentials([azureServicePrincipal('<mySrvPrincipal>')]) {
      
  5. 就像您部署到 Windows 中的 Azure Web 應用程式時一樣,使用 Jenkinsfile2 建立新的 Jenkins 管線。Create a new Jenkins pipeline as you did when deploying to Azure web app in Windows using Jenkinsfile2.

  6. 執行您的新作業。Run your new job.

  7. 若要確認,請在 Azure CLI 中執行下列命令:To verify, in Azure CLI, run the following command:

    az acr repository list -n <myRegistry> -o json
    

    您應該會看到如下的結果:You should see results similar to the following:

    [
    "calculator"
    ]
    
  8. 瀏覽至 http://<app_name>.azurewebsites.net/api/calculator/ping (取代預留位置)。Browse to http://<app_name>.azurewebsites.net/api/calculator/ping (replacing the placeholder). 您應該會看見如下所示的結果:You should see similar results to the following:

    Welcome to Java Web App!!! This is updated!
    Today's date
    
  9. 瀏覽至 http://<app_name>.azurewebsites.net/api/calculator/add?x=<x>&y=<y> (取代預留位置)。Browse to http://<app_name>.azurewebsites.net/api/calculator/add?x=<x>&y=<y> (replacing the placeholders). 您為 xy 指定的值會加總並顯示。The values you specify for x and y are summed and displayed.

後續步驟Next steps