教學課程:於認可原始程式碼時在雲端自動執行容器映像建置Tutorial: Automate container image builds in the cloud when you commit source code

除了快速工作之外,ACR 工作還能在您將原始程式碼認可至 Git 存放庫時,自動化雲端中的 Docker 容器映像建置。In addition to a quick task, ACR Tasks supports automated Docker container image builds in the cloud when you commit source code to a Git repository.

在本教學課程中,當您將原始程式碼認可至 Git 存放庫時,ACR 工作會建置並推送在 Dockerfile 中指定的單一容器映像。In this tutorial, your ACR task builds and pushes a single container image specified in a Dockerfile when you commit source code to a Git repo. 若要建立多步驟工作,以在認可程式碼時,使用 YAML 檔案來定義建置、推送及選擇性測試多個容器的步驟,請參閱教學課程:於認可原始程式碼時在雲端執行多步驟容器工作流程To create a multi-step task that uses a YAML file to define steps to build, push, and optionally test multiple containers on code commit, see Tutorial: Run a multi-step container workflow in the cloud when you commit source code. 如需 ACR 工作的概觀,請參閱使用 ACR 工作自動化作業系統和架構修補For an overview of ACR Tasks, see Automate OS and framework patching with ACR Tasks

本教學課程內容:In this tutorial:

  • 建立工作Create a task
  • 測試工作Test the task
  • 檢視工作狀態View task status
  • 透過程式碼認可觸發工作Trigger the task with a code commit

本教學課程假設您已完成上一個教學課程中的步驟。This tutorial assumes you've already completed the steps in the previous tutorial. 如果您尚未完成上一個教學課程的必要條件一節中的步驟,請先加以完成,再繼續操作。If you haven't already done so, complete the steps in the Prerequisites section of the previous tutorial before proceeding.

使用 Azure Cloud ShellUse Azure Cloud Shell

Azure Cloud Shell 是裝載於 Azure 中的互動式殼層環境,可在瀏覽器中使用。Azure hosts Azure Cloud Shell, an interactive shell environment that you can use through your browser. Cloud Shell 可讓您使用 bashPowerShell 以與 Azure 服務搭配使用。Cloud Shell lets you use either bash or PowerShell to work with Azure services. Azure Cloud Shell 已預先安裝一些命令,可讓您執行本文提到的程式碼,而不必在本機環境上安裝任何工具。You can use the Cloud Shell pre-installed commands to run the code in this article without having to install anything on your local environment.

若要啟動 Azure Cloud Shell:To launch Azure Cloud Shell:

選項Option 範例/連結Example/Link
選取程式碼區塊右上角的 [試試看] 。Select Try It in the upper-right corner of a code block. 選取 [試用] 並不會自動將程式碼複製到 Cloud Shell 中。Selecting Try It doesn't automatically copy the code to Cloud Shell. Azure Cloud Shell 的試試看範例
請前往 https://shell.azure.com 或選取 [啟動 Cloud Shell] 按鈕,在瀏覽器中開啟 Cloud Shell。Go to https://shell.azure.com or select the Launch Cloud Shell button to open Cloud Shell in your browser. 在新視窗中啟動 Cloud ShellLaunch Cloud Shell in a new window
選取 Azure 入口網站右上角功能表列中的 [Cloud Shell] 按鈕。Select the Cloud Shell button on the top-right menu bar in the Azure portal. Azure 入口網站中的 [Cloud Shell] 按鈕

若要在 Azure Cloud Shell 中執行本文中的程式碼:To run the code in this article in Azure Cloud Shell:

  1. 開啟 Cloud Shell。Open Cloud Shell.
  2. 選取程式碼區塊上的 [複製] 按鈕,複製程式碼。Select the Copy button on a code block to copy the code.
  3. 在 Windows 和 Linux 上按 Ctrl+Shift+V;或在 macOS 上按 Cmd+Shift+V,將程式碼貼到 Cloud Shell工作階段中。Paste the code into the Cloud Shell session with Ctrl+Shift+V on Windows and Linux, or Cmd+Shift+V on macOS.
  4. 按下 Enter 鍵執行程式碼。Press Enter to run the code.

如果您想要在本機使用 Azure CLI,必須安裝 Azure CLI 2.0.46 版或更新版本,並使用 az login 登入。If you'd like to use the Azure CLI locally, you must have Azure CLI version 2.0.46 or later installed and logged in with az login. 執行 az --version 以尋找版本。Run az --version to find the version. 如果您需要安裝或升級 CLI,請參閱安裝 Azure CLIIf you need to install or upgrade the CLI, see Install Azure CLI.

必要條件Prerequisites

取得範例程式碼Get sample code

本教學課程假設您已完成上一個教學課程中的步驟,並已派生和複製範例存放庫。This tutorial assumes you've already completed the steps in the previous tutorial, and have forked and cloned the sample repository. 如果您尚未完成上一個教學課程的必要條件一節中的步驟,請先加以完成,再繼續操作。If you haven't already done so, complete the steps in the Prerequisites section of the previous tutorial before proceeding.

容器登錄Container registry

您的 Azure 訂用帳戶中必須要有 Azure 容器登錄,才能完成本教學課程。You must have an Azure container registry in your Azure subscription to complete this tutorial. 如果您需要登錄,請參閱上一個教學課程快速入門:使用 Azure CLI 建立容器登錄If you need a registry, see the previous tutorial, or Quickstart: Create a container registry using the Azure CLI.

建立 GitHub 個人存取權杖Create a GitHub personal access token

為了在認可至 Git 存放庫時觸發工作,ACR 工作需要以個人存取權杖 (PAT) 存取存放庫。To trigger a task on a commit to a Git repository, ACR Tasks need a personal access token (PAT) to access the repository. 如果您還沒有 PAT,請依照下列步驟在 GitHub 中產生 PAT:If you do not already have a PAT, follow these steps to generate one in GitHub:

  1. 瀏覽至 GitHub 上的 PAT 建立頁面 (https://github.com/settings/tokens/new )Navigate to the PAT creation page on GitHub at https://github.com/settings/tokens/new

  2. 輸入權杖的簡短說明,例如「ACR 工作示範」Enter a short description for the token, for example, "ACR Tasks Demo"

  3. 選取 ACR 的範圍以存取存放庫。Select scopes for ACR to access the repo. 若要如同本教學課程一般地存取公用存放庫,請在存放庫底下,啟用 repo:statuspublic_repoTo access a public repo as in this tutorial, under repo, enable repo:status and public_repo

    GitHub 中的個人存取權杖產生頁面的螢幕擷取畫面

    注意

    若要產生 PAT 以存取「私人」 存放庫,請選取完整存放庫控制的範圍。To generate a PAT to access a private repo, select the scope for full repo control.

  4. 選取 [產生權杖] 按鈕 (系統可能會要求您確認密碼)Select the Generate token button (you may be asked to confirm your password)

  5. 安全的位置複製並儲存產生的權杖 (當您在下一節定義工作時,將會使用此權杖)Copy and save the generated token in a secure location (you use this token when you define a task in the following section)

    GitHub 中已產生的個人存取權杖的螢幕擷取畫面

建立建置工作Create the build task

現在,您已完成啟用 ACR 工作以讀取認可狀態以及在存放庫中建立 Webhook 所需的步驟,接下來可以建立工作,以在認可至存放庫時觸發容器映像建置。Now that you've completed the steps required to enable ACR Tasks to read commit status and create webhooks in a repository, you can create a task that triggers a container image build on commits to the repo.

首先,請在這些殼層環境變數中填入您的環境適用的值。First, populate these shell environment variables with values appropriate for your environment. 此步驟並不是必要動作,但可簡化在本教學課程中執行多行 Azure CLI 命令的作業。This step isn't strictly required, but makes executing the multiline Azure CLI commands in this tutorial a bit easier. 若未填入這些環境變數,則必須手動取代命令範例中出現的每個值。If you don't populate these environment variables, you must manually replace each value wherever it appears in the example commands.

ACR_NAME=<registry-name>        # The name of your Azure container registry
GIT_USER=<github-username>      # Your GitHub user account name
GIT_PAT=<personal-access-token> # The PAT you generated in the previous section

現在,請執行下列 az acr task create 命令以建立工作:Now, create the task by executing the following az acr task create command:

az acr task create \
    --registry $ACR_NAME \
    --name taskhelloworld \
    --image helloworld:{{.Run.ID}} \
    --context https://github.com/$GIT_USER/acr-build-helloworld-node.git \
    --branch master \
    --file Dockerfile \
    --git-access-token $GIT_PAT

重要

如果您先前已在預覽期間使用 az acr build-task 命令建立工作,則必須使用 az acr task 命令重新建立這些工作。If you previously created tasks during the preview with the az acr build-task command, those tasks need to be re-created using the az acr task command.

此工作會指定只要有程式碼認可至 --context 所指定之存放庫中的「主要」 分支,ACR 工作即會從該分支中的程式碼建置容器映像。This task specifies that any time code is committed to the master branch in the repository specified by --context, ACR Tasks will build the container image from the code in that branch. 系統會使用 --file 所指定、位於存放庫根目錄中的 Dockerfile 來建置映像。The Dockerfile specified by --file from the repository root is used to build the image. --image 引數會針對映像標記的版本部分指定 {{.Run.ID}} 的參數化值,以確保建置的映像會與特定的組建相互關聯,並加上唯一標記。The --image argument specifies a parameterized value of {{.Run.ID}} for the version portion of the image's tag, ensuring the built image correlates to a specific build, and is tagged uniquely.

成功執行的 az acr task create 命令會產生如下的輸出:Output from a successful az acr task create command is similar to the following:

{
  "agentConfiguration": {
    "cpu": 2
  },
  "creationDate": "2018-09-14T22:42:32.972298+00:00",
  "id": "/subscriptions/<Subscription ID>/resourceGroups/myregistry/providers/Microsoft.ContainerRegistry/registries/myregistry/tasks/taskhelloworld",
  "location": "westcentralus",
  "name": "taskhelloworld",
  "platform": {
    "architecture": "amd64",
    "os": "Linux",
    "variant": null
  },
  "provisioningState": "Succeeded",
  "resourceGroup": "myregistry",
  "status": "Enabled",
  "step": {
    "arguments": [],
    "baseImageDependencies": null,
    "contextPath": "https://github.com/gituser/acr-build-helloworld-node",
    "dockerFilePath": "Dockerfile",
    "imageNames": [
      "helloworld:{{.Run.ID}}"
    ],
    "isPushEnabled": true,
    "noCache": false,
    "type": "Docker"
  },
  "tags": null,
  "timeout": 3600,
  "trigger": {
    "baseImageTrigger": {
      "baseImageTriggerType": "Runtime",
      "name": "defaultBaseimageTriggerName",
      "status": "Enabled"
    },
    "sourceTriggers": [
      {
        "name": "defaultSourceTriggerName",
        "sourceRepository": {
          "branch": "master",
          "repositoryUrl": "https://github.com/gituser/acr-build-helloworld-node",
          "sourceControlAuthProperties": null,
          "sourceControlType": "GitHub"
        },
        "sourceTriggerEvents": [
          "commit"
        ],
        "status": "Enabled"
      }
    ]
  },
  "type": "Microsoft.ContainerRegistry/registries/tasks"
}

測試建置工作Test the build task

現在,您已有定義組建的工作。You now have a task that defines your build. 若要測試組建管線,請執行 az acr task run 命令以手動觸發建置:To test the build pipeline, trigger a build manually by executing the az acr task run command:

az acr task run --registry $ACR_NAME --name taskhelloworld

根據預設,az acr task run 命令會在您執行命令時將記錄輸出串流處理至主控台。By default, the az acr task run command streams the log output to your console when you execute the command.

$ az acr task run --registry $ACR_NAME --name taskhelloworld

2018/09/17 22:51:00 Using acb_vol_9ee1f28c-4fd4-43c8-a651-f0ed027bbf0e as the home volume
2018/09/17 22:51:00 Setting up Docker configuration...
2018/09/17 22:51:02 Successfully set up Docker configuration
2018/09/17 22:51:02 Logging in to registry: myregistry.azurecr.io
2018/09/17 22:51:03 Successfully logged in
2018/09/17 22:51:03 Executing step: build
2018/09/17 22:51:03 Obtaining source code and scanning for dependencies...
2018/09/17 22:51:05 Successfully obtained source code and scanned for dependencies
Sending build context to Docker daemon  23.04kB
Step 1/5 : FROM node:9-alpine
9-alpine: Pulling from library/node
Digest: sha256:8dafc0968fb4d62834d9b826d85a8feecc69bd72cd51723c62c7db67c6dec6fa
Status: Image is up to date for node:9-alpine
 ---> a56170f59699
Step 2/5 : COPY . /src
 ---> 5f574fcf5816
Step 3/5 : RUN cd /src && npm install
 ---> Running in b1bca3b5f4fc
npm notice created a lockfile as package-lock.json. You should commit this file.
npm WARN helloworld@1.0.0 No repository field.

up to date in 0.078s
Removing intermediate container b1bca3b5f4fc
 ---> 44457db20dac
Step 4/5 : EXPOSE 80
 ---> Running in 9e6f63ec612f
Removing intermediate container 9e6f63ec612f
 ---> 74c3e8ea0d98
Step 5/5 : CMD ["node", "/src/server.js"]
 ---> Running in 7382eea2a56a
Removing intermediate container 7382eea2a56a
 ---> e33cd684027b
Successfully built e33cd684027b
Successfully tagged myregistry.azurecr.io/helloworld:da2
2018/09/17 22:51:11 Executing step: push
2018/09/17 22:51:11 Pushing image: myregistry.azurecr.io/helloworld:da2, attempt 1
The push refers to repository [myregistry.azurecr.io/helloworld]
4a853682c993: Preparing
[...]
4a853682c993: Pushed
[...]
da2: digest: sha256:c24e62fd848544a5a87f06ea60109dbef9624d03b1124bfe03e1d2c11fd62419 size: 1366
2018/09/17 22:51:21 Successfully pushed image: myregistry.azurecr.io/helloworld:da2
2018/09/17 22:51:21 Step id: build marked as successful (elapsed time in seconds: 7.198937)
2018/09/17 22:51:21 Populating digests for step id: build...
2018/09/17 22:51:22 Successfully populated digests for step id: build
2018/09/17 22:51:22 Step id: push marked as successful (elapsed time in seconds: 10.180456)
The following dependencies were found:
- image:
    registry: myregistry.azurecr.io
    repository: helloworld
    tag: da2
    digest: sha256:c24e62fd848544a5a87f06ea60109dbef9624d03b1124bfe03e1d2c11fd62419
  runtime-dependency:
    registry: registry.hub.docker.com
    repository: library/node
    tag: 9-alpine
    digest: sha256:8dafc0968fb4d62834d9b826d85a8feecc69bd72cd51723c62c7db67c6dec6fa
  git:
    git-head-revision: 68cdf2a37cdae0873b8e2f1c4d80ca60541029bf


Run ID: da2 was successful after 27s

透過認可觸發建置Trigger a build with a commit

現在您已藉由手動執行測試了工作,接下來請透過原始程式碼的變更自動加以觸發。Now that you've tested the task by manually running it, trigger it automatically with a source code change.

首先,請確定您位於存放庫的本機複本所在的目錄中:First, ensure you're in the directory containing your local clone of the repository:

cd acr-build-helloworld-node

接著,執行下列命令以建立新檔案,然後將其認可並推送至 GitHub 上的存放庫分支:Next, execute the following commands to create, commit, and push a new file to your fork of the repo on GitHub:

echo "Hello World!" > hello.txt
git add hello.txt
git commit -m "Testing ACR Tasks"
git push origin master

在您執行 git push 命令時,系統可能會要求您提供 GitHub 認證。You may be asked to provide your GitHub credentials when you execute the git push command. 請提供您的 GitHub 使用者名稱,並輸入您先前為密碼建立的個人存取權杖 (PAT)。Provide your GitHub username, and enter the personal access token (PAT) that you created earlier for the password.

$ git push origin master
Username for 'https://github.com': <github-username>
Password for 'https://githubuser@github.com': <personal-access-token>

在您將認可推送至存放庫後,ACR 工作所建立的 Webhook 即會在 Azure Container Registry 中引發並啟動建置。Once you've pushed a commit to your repository, the webhook created by ACR Tasks fires and kicks off a build in Azure Container Registry. 請顯示目前所執行工作的記錄,以確認並監視建置進度:Display the logs for the currently running task to verify and monitor the build progress:

az acr task logs --registry $ACR_NAME

輸出會類似於下列內容,顯示目前正在執行 (或最後執行) 的工作:Output is similar to the following, showing the currently executing (or last-executed) task:

$ az acr task logs --registry $ACR_NAME
Showing logs of the last created run.
Run ID: da4

[...]

Run ID: da4 was successful after 38s

列出建置List builds

若要查看 ACR 工作已為登錄完成的工作流程執行,請執行 az acr task list-runs 命令:To see a list of the task runs that ACR Tasks has completed for your registry, run the az acr task list-runs command:

az acr task list-runs --registry $ACR_NAME --output table

此命令的輸出應類似於下列內容。Output from the command should appear similar to the following. ACR 工作已執行的流程執行會顯示出來,且最新工作的 [觸發程序] 資料行中會出現「Git 認可」:The runs that ACR Tasks has executed are displayed, and "Git Commit" appears in the TRIGGER column for the most recent task:

$ az acr task list-runs --registry $ACR_NAME --output table

RUN ID    TASK             PLATFORM    STATUS     TRIGGER     STARTED               DURATION
--------  --------------  ----------  ---------  ----------  --------------------  ----------
da4       taskhelloworld  Linux       Succeeded  Git Commit  2018-09-17T23:03:45Z  00:00:44
da3       taskhelloworld  Linux       Succeeded  Manual      2018-09-17T22:55:35Z  00:00:35
da2       taskhelloworld  Linux       Succeeded  Manual      2018-09-17T22:50:59Z  00:00:32
da1                       Linux       Succeeded  Manual      2018-09-17T22:29:59Z  00:00:57

後續步驟Next steps

在本教學課程中,您已了解如何使用工作,在將原始程式碼認可至 Git 存放庫時於 Azure 中自動觸發容器映像建置。In this tutorial, you learned how to use a task to automatically trigger container image builds in Azure when you commit source code to a Git repository. 請進入下一個教學課程,以了解如何建立會在容器映像的基底映像更新時觸發建置的工作。Move on to the next tutorial to learn how to create tasks that trigger builds when a container image's base image is updated.