用于将容器部署到 Kubernetes 服务的 GitHub ActionsGitHub Actions for deploying to Kubernetes service

可以通过 GitHub Actions 灵活地生成自动化软件开发生命周期工作流。GitHub Actions gives you the flexibility to build an automated software development lifecycle workflow. 可以使用多个 Kubernetes 操作通过 GitHub Actions 将 Azure 容器注册表中的容器部署到 Azure Kubernetes 服务。You can use multiple Kubernetes actions to deploy to containers from Azure Container Registry to Azure Kubernetes Service with GitHub Actions.

先决条件Prerequisites

工作流文件概述Workflow file overview

工作流通过存储库的 /.github/workflows/ 路径中的 YAML (.yml) 文件定义。A workflow is defined by a YAML (.yml) file in the /.github/workflows/ path in your repository. 此定义包含组成工作流的各种步骤和参数。This definition contains the various steps and parameters that make up the workflow.

对于以 AKS 为目标的工作流,该文件包含三个部分:For a workflow targeting AKS, the file has three sections:

部分Section 任务Tasks
身份验证Authentication 登录到专用容器注册表 (ACR)Login to a private container registry (ACR)
生成Build 生成和推送容器映像Build & push the container image
部署Deploy 1.设置目标 AKS 群集1. Set the target AKS cluster
2.在 Kubernetes 群集中创建通用/docker 注册表机密2. Create a generic/docker-registry secret in Kubernetes cluster
3.部署到 Kubernetes 群集3. Deploy to the Kubernetes cluster

创建服务主体Create a service principal

可以在 Azure CLI 中使用 az ad sp create-for-rbac 命令创建服务主体You can create a service principal by using the az ad sp create-for-rbac command in the Azure CLI.

az ad sp create-for-rbac --name "myApp" --role contributor --scopes /subscriptions/<SUBSCRIPTION_ID>/resourceGroups/<RESOURCE_GROUP> --sdk-auth

在上述命令中,将占位符替换为你的订阅 ID 和资源组。In the above command, replace the placeholders with your subscription ID, and resource group. 输出是用于访问资源的角色分配凭据。The output is the role assignment credentials that provide access to your resource. 此命令应输出下面这样的 JSON 对象。The command should output a JSON object similar to this.

  {
    "clientId": "<GUID>",
    "clientSecret": "<GUID>",
    "subscriptionId": "<GUID>",
    "tenantId": "<GUID>",
    (...)
  }

请复制此 JSON 对象,它可以用来从 GitHub 进行身份验证。Copy this JSON object, which you can use to authenticate from GitHub.

配置 GitHub 机密Configure the GitHub secrets

按照以下步骤配置机密:Follow the steps to configure the secrets:

  1. GitHub 中浏览到存储库,选择“设置”>“机密”>“添加新机密”。 In GitHub, browse to your repository, select Settings > Secrets > Add a new secret.

    屏幕截图显示了存储库的“添加新机密”链接。

  2. 将上述 az cli 命令的内容作为机密变量的值粘贴。Paste the contents of the above az cli command as the value of secret variable. 例如,AZURE_CREDENTIALSFor example, AZURE_CREDENTIALS.

  3. 同样,为容器注册表凭据定义以下附加机密,并在 Docker 登录操作中设置它们。Similarly, define the following additional secrets for the container registry credentials and set them in Docker login action.

    • REGISTRY_USERNAMEREGISTRY_USERNAME
    • REGISTRY_PASSWORDREGISTRY_PASSWORD
  4. 在定义后,会看到如下所示的机密。You will see the secrets as shown below once defined.

    屏幕截图显示了存储库的现有机密。

生成容器映像并将其部署到 Azure Kubernetes 服务群集Build a container image and deploy to Azure Kubernetes Service cluster

容器映像的生成和推送使用 Azure/docker-login@v1 操作完成。The build and push of the container images is done using Azure/docker-login@v1 action.

env:
  REGISTRY_NAME: {registry-name}
  CLUSTER_NAME: {cluster-name}
  CLUSTER_RESOURCE_GROUP: {resource-group-name}
  NAMESPACE: {namespace-name}
  APP_NAME: {app-name}

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@main

    # Connect to Azure Container registry (ACR)
    - uses: azure/docker-login@v1
      with:
        login-server: ${{ env.REGISTRY_NAME }}.azurecr.cn
        username: ${{ secrets.REGISTRY_USERNAME }} 
        password: ${{ secrets.REGISTRY_PASSWORD }}

    # Container build and push to a Azure Container registry (ACR)
    - run: |
        docker build . -t ${{ env.REGISTRY_NAME }}.azurecr.cn/${{ env.APP_NAME }}:${{ github.sha }}
        docker push ${{ env.REGISTRY_NAME }}.azurecr.cn/${{ env.APP_NAME }}:${{ github.sha }}

部署到 Azure Kubernetes 服务群集Deploy to Azure Kubernetes Service cluster

若要将容器映像部署到 AKS,需使用 Azure/k8s-deploy@v1 操作。To deploy a container image to AKS, you will need to use the Azure/k8s-deploy@v1 action. 该操作有五个参数:This action has five parameters:

参数Parameter 解释Explanation
namespacenamespace (可选)选择目标 Kubernetes 命名空间。(Optional) Choose the target Kubernetes namespace. 如果未提供命名空间,则命令会在默认命名空间中运行If the namespace is not provided, the commands will run in the default namespace
manifestsmanifests (必需)将要用于部署的清单文件的路径(Required) Path to the manifest files, that will be used for deployment
imagesimages (可选)将要用于在清单文件上进行替换的映像的完全限定资源 URL(Optional) Fully qualified resource URL of the image(s) to be used for substitutions on the manifest files
imagepullsecretsimagepullsecrets (可选)已在群集中设置的 docker 注册表机密的名称。(Optional) Name of a docker-registry secret that has already been set up within the cluster. 这些机密名称的每一个都在输入清单文件中的工作负载的 imagePullSecrets 字段下添加Each of these secret names is added under imagePullSecrets field for the workloads found in the input manifest files
kubectl-versionkubectl-version (可选)安装 kubectl 二进制文件的特定版本(Optional) Installs a specific version of kubectl binary

在部署到 AKS 之前,需要设置目标 Kubernetes 命名空间并创建映像拉取机密。Before you can deploy to AKS, you'll need to set target Kubernetes namespace and create an image pull secret. 请参阅将映像从 Azure 容器注册表拉取到 Kubernetes 群集,以详细了解拉取映像的工作原理。See Pull images from an Azure container registry to a Kubernetes cluster, to learn more about how pulling images works.

  # Create namespace if doesn't exist
  - run: |
      kubectl create namespace ${{ env.NAMESPACE }} --dry-run -o json | kubectl apply -f -

  # Create image pull secret for ACR
  - uses: azure/k8s-create-secret@v1
    with:
      container-registry-url: ${{ env.REGISTRY_NAME }}.azurecr.cn
      container-registry-username: ${{ secrets.REGISTRY_USERNAME }}
      container-registry-password: ${{ secrets.REGISTRY_PASSWORD }}
      secret-name: ${{ env.SECRET }}
      namespace: ${{ env.NAMESPACE }}
      force: true

使用 k8s-deploy 操作完成部署。Complete your deployment with the k8s-deploy action. 将环境变量替换为应用程序的值。Replace the environment variables with values for your application.


on: [push]

# Environment variables available to all jobs and steps in this workflow
env:
  REGISTRY_NAME: {registry-name}
  CLUSTER_NAME: {cluster-name}
  CLUSTER_RESOURCE_GROUP: {resource-group-name}
  NAMESPACE: {namespace-name}
  SECRET: {secret-name}
  APP_NAME: {app-name}

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@main

    # Connect to Azure Container registry (ACR)
    - uses: azure/docker-login@v1
      with:
        login-server: ${{ env.REGISTRY_NAME }}.azurecr.cn
        username: ${{ secrets.REGISTRY_USERNAME }} 
        password: ${{ secrets.REGISTRY_PASSWORD }}

    # Container build and push to a Azure Container registry (ACR)
    - run: |
        docker build . -t ${{ env.REGISTRY_NAME }}.azurecr.cn/${{ env.APP_NAME }}:${{ github.sha }}
        docker push ${{ env.REGISTRY_NAME }}.azurecr.cn/${{ env.APP_NAME }}:${{ github.sha }}

    # Set the target Azure Kubernetes Service (AKS) cluster. 
    - uses: azure/aks-set-context@v1
      with:
        creds: '${{ secrets.AZURE_CREDENTIALS }}'
        cluster-name: ${{ env.CLUSTER_NAME }}
        resource-group: ${{ env.CLUSTER_RESOURCE_GROUP }}

    # Create namespace if doesn't exist
    - run: |
        kubectl create namespace ${{ env.NAMESPACE }} --dry-run -o json | kubectl apply -f -

    # Create image pull secret for ACR
    - uses: azure/k8s-create-secret@v1
      with:
        container-registry-url: ${{ env.REGISTRY_NAME }}.azurecr.cn
        container-registry-username: ${{ secrets.REGISTRY_USERNAME }}
        container-registry-password: ${{ secrets.REGISTRY_PASSWORD }}
        secret-name: ${{ env.SECRET }}
        namespace: ${{ env.NAMESPACE }}
        force: true

    # Deploy app to AKS
    - uses: azure/k8s-deploy@v1
      with:
        manifests: |
          manifests/deployment.yml
          manifests/service.yml
        images: |
          ${{ env.REGISTRY_NAME }}.azurecr.cn/${{ env.APP_NAME }}:${{ github.sha }}
        imagepullsecrets: |
          ${{ env.SECRET }}
        namespace: ${{ env.NAMESPACE }}

清理资源Clean up resources

不再需要 Kubernetes 群集、容器注册表和存储库时,请通过删除资源组和 GitHub 存储库来清理部署的资源。When your Kubernetes cluster, container registry, and repository are no longer needed, clean up the resources you deployed by deleting the resource group and your GitHub repository.

更多 Kubernetes GitHub ActionsMore Kubernetes GitHub Actions

  • Kubectl 工具安装程序 (azure/setup-kubectl):在运行器上安装 kubectl 的特定版本。Kubectl tool installer (azure/setup-kubectl): Installs a specific version of kubectl on the runner.
  • Kubernetes 设置上下文 (azure/k8s-set-context):设置将由其他操作使用的目标 Kubernetes 群集上下文,或运行任何 kubectl 命令。Kubernetes set context (azure/k8s-set-context): Set the target Kubernetes cluster context which will be used by other actions or run any kubectl commands.
  • AKS 设置上下文 (azure/aks-set-context):设置目标 Azure Kubernetes 服务群集上下文。AKS set context (azure/aks-set-context): Set the target Azure Kubernetes Service cluster context.
  • Kubernetes 创建机密 (azure/k8s-create-secret):在 Kubernetes 群集中创建通用机密或 docker 注册表机密。Kubernetes create secret (azure/k8s-create-secret): Create a generic secret or docker-registry secret in the Kubernetes cluster.
  • Kubernetes 部署 (azure/k8s-deploy):烘焙清单并将清单部署到 Kubernetes 群集。Kubernetes deploy (azure/k8s-deploy): Bake and deploy manifests to Kubernetes clusters.
  • 设置 Helm (azure/setup-helm):在运行器上安装 Helm 二进制文件的特定版本。Setup Helm (azure/setup-helm): Install a specific version of Helm binary on the runner.
  • Kubernetes 烘培 (azure/k8s-bake):烘焙清单文件,用于通过 helm2、kustomize 或 kompose 进行部署。Kubernetes bake (azure/k8s-bake): Bake manifest file to be used for deployments using helm2, kustomize or kompose.
  • Kubernetes lint (azure/k8s-lint):验证/lint 清单文件。Kubernetes lint (azure/k8s-lint): Validate/lint your manifest files.