使用 Helm 来与 Kubernetes 部署集成Integrate with Kubernetes Deployment using Helm

使用 Helm 可以定义、安装和升级 Kubernetes 中运行的应用程序。Helm provides a way to define, install, and upgrade applications running in Kubernetes. Helm 图表包含创建 Kubernetes 应用程序实例所需的信息。A Helm chart contains the information necessary to create an instance of a Kubernetes application. 配置存储在图表本身外部的名为 values.yaml 的文件中 。Configuration is stored outside of the chart itself, in a file called values.yaml.

在发布过程中,Helm 会将图表与正确的配置合并,以运行应用程序。During the release process, Helm merges the chart with the proper configuration to run the application. 例如,可将 values.yaml 中定义的变量作为正在运行的容器内部的环境变量进行引用 。For example, variables defined in values.yaml can be referenced as environment variables inside the running containers. Helm 还支持创建 Kubernetes 机密,可将这些机密装载为数据卷,或公开为环境变量。Helm also supports creation of Kubernetes Secrets, which can be mounted as data volumes or exposed as environment variables.

在运行 Helm 时,可以通过在命令行中提供其他基于 YAML 的配置文件来重写 values.yaml 中存储的值 。You can override the values stored in values.yaml by providing additional YAML-based configuration files on the command line when running Helm. Azure 应用程序配置支持将配置值导出到 YAML 文件。Azure App Configuration supports exporting configuration values to YAML files. 将此导出功能集成到部署中可让 Kubernetes 应用程序利用应用程序配置中存储的配置值。Integrating this export capability into your deployment allows your Kubernetes applications to leverage configuration values stored in App Configuration.

在本教程中,你将了解如何执行以下操作:In this tutorial, you learn how to:

  • 在使用 Helm 将应用程序部署到 Kubernetes 时使用应用程序配置中的值。Use values from App Configuration when deploying an application to Kubernetes using Helm.
  • 基于应用程序配置中的 Key Vault 参考创建 Kubernetes 机密。Create a Kubernetes Secret based on a Key Vault reference in App Configuration.

本教程假定读者基本了解如何使用 Helm 管理 Kubernetes。This tutorial assumes basic understanding of managing Kubernetes with Helm. Azure Kubernetes 服务中详细了解如何使用 Helm 安装应用程序。Learn more about installing applications with Helm in Azure Kubernetes Service.

先决条件Prerequisites

  • 如果没有 Azure 试用版订阅,请在开始前创建一个试用版订阅If you don't have an Azure trail subscription, create a trial subscription before you begin.
  • 安装 Azure CLI(2.4.0 或更高版本)Install Azure CLI (version 2.4.0 or later)
  • 安装 Helm(2.14.0 或更高版本)Install Helm (version 2.14.0 or later)
  • 一个 Kubernetes 群集。A Kubernetes cluster.

创建应用配置存储区Create an App Configuration store

  1. 若要创建新应用程序配置存储区,请登录 Azure 门户To create a new App Configuration store, sign in to the Azure portal. 在主页的左上角,选择“创建资源” 。In the upper-left corner of the home page, select Create a resource. 在“搜索市场”框中,输入“应用程序配置”并选择 Enter 。In the Search the Marketplace box, enter App Configuration and select Enter.

    搜索应用配置

  2. 在搜索结果中选择“应用程序配置”,然后选择“创建” 。Select App Configuration from the search results, and then select Create.

    选择“创建”

  3. 在“创建应用配置”窗格中,输入以下设置:On the Create App Configuration pane, enter the following settings:

    设置Setting 建议的值Suggested value 说明Description
    订阅Subscription 订阅Your subscription 选择要用来测试应用配置的 Azure 订阅。Select the Azure subscription that you want to use to test App Configuration. 如果帐户只有一个订阅,则会自动选择该订阅并且不显示“订阅”列表 。If your account has only one subscription, it's automatically selected and the Subscription list isn't displayed.
    资源组Resource group AppConfigTestResources AppConfigTestResources 为应用程序配置存储区资源选择或创建资源组。Select or create a resource group for your App Configuration store resource. 此组可用于组织多个资源,删除该资源组可以同时删除这些资源。This group is useful for organizing multiple resources that you might want to delete at the same time by deleting the resource group. 有关详细信息,请参阅使用资源组管理 Azure 资源For more information, see Use resource groups to manage your Azure resources.
    资源名称Resource name 全局唯一名称Globally unique name 输入要用于应用程序配置存储区资源的唯一资源名称。Enter a unique resource name to use for the App Configuration store resource. 该名称必须是包含 5 到 50 个字符的字符串,只能包含数字、字母和 - 字符。The name must be a string between 5 and 50 characters and contain only numbers, letters, and the - character. 该名称的开头或末尾不能是 - 字符。The name can't start or end with the - character.
    位置Location 中国东部 2China East 2 使用“位置”指定在其中托管应用配置存储区的地理位置 。Use Location to specify the geographic location in which your app configuration store is hosted. 为获得最佳性能,请在应用程序的其他组件所在的同一区域创建资源。For the best performance, create the resource in the same region as other components of your application.
    定价层Pricing tier 免费Free 选择所需的定价层。Select the desired pricing tier. 有关详细信息,请参阅应用配置定价页For more information, see the App Configuration pricing page.
  4. 选择“查看 + 创建”以验证自己的设置 。Select Review + create to validate your settings.

  5. 选择“创建”。Select Create. 部署可能需要几分钟。The deployment might take a few minutes.

  6. 部署完成后,导航到“应用程序配置”资源。After the deployment finishes, navigate to the App Configuration resource. 选择“设置” > “访问密钥”。Select Settings > Access keys. 记下只读主密钥连接字符串。Make a note of the primary read-only key connection string. 稍后将使用此连接字符串来配置应用程序,以与创建的应用程序配置存储区进行通信。You'll use this connection string later to configure your application to communicate with the App Configuration store that you created.

  1. 选择“配置资源管理器” > “创建”来添加以下键值对 :Select Configuration Explorer > Create to add the following key-value pairs:

    密钥Key Value
    settings.colorsettings.color 白色White
    settings.messagesettings.message Azure 应用配置的数据Data from Azure App Configuration

    暂时将“标签”和“内容类型”保留为空 。Leave Label and Content Type empty for now.

将 Key Vault 引用添加到应用程序配置Add a Key Vault reference to App Configuration

  1. 登录到 Azure 门户,将名称为 Password、值为 myPassword 的机密添加到 Key VaultSign in to the Azure portal and add a secret to Key Vault with name Password and value myPassword.

  2. 选择在上一部分创建的应用程序存储实例。Select the App Configuration store instance that you created in previous section.

  3. 选择“配置资源管理器”。 Select Configuration Explorer.

  4. 选择“+ 创建” > “Key Vault 引用”,然后指定以下值: Select + Create > Key vault reference, and then specify the following values:

    • 密钥:选择“secrets.password” 。Key: Select secrets.password.
    • 标签:将此值保留空白。Label: Leave this value blank.
    • “订阅”、“资源组”和“Key Vault”: 输入上一步在 Key Vault 中创建的项相对应的值。Subscription, Resource group, and Key vault: Enter the values corresponding to those in the key vault you created in previous step.
    • 机密:选择在上一部分创建的名为 Password 的机密 。Secret: Select the secret named Password that you created in the previous section.

创建 Helm 图表Create Helm chart

首先,使用以下命令创建一个示例 Helm 图表First, create a sample Helm chart with the following command

helm create mychart

Helm 将采用如下所示的结构创建名为 mychart 的一个新目录。Helm creates a new directory called mychart with the structure shown below.

提示

在此图表指南中了解更多信息。Follow this charts guide to learn more.

mychart
|-- Chart.yaml
|-- charts
|-- templates
|   |-- NOTES.txt
|   |-- _helpers.tpl
|   |-- deployment.yaml
|   |-- ingress.yaml
|   `-- service.yaml
`-- values.yaml

接下来,更新 deployment.yaml 文件的 spec:template:spec:containers 节 。Next, update the spec:template:spec:containers section of the deployment.yaml file. 以下代码片段将两个环境变量添加到容器。The following snippet adds two environment variables to the container. 在部署时,你将动态设置这些变量的值。You'll set their values dynamically at deployment time.

env:
- name: Color
    value: {{ .Values.settings.color }}
- name: Message
    value: {{ .Values.settings.message }}

更新后的完整 deployment.yaml 文件应如下所示 。The complete deployment.yaml file after the update should look like below.

apiVersion: apps/v1beta2
kind: Deployment
metadata:
  name: {{ include "mychart.fullname" . }}
  labels:
    app.kubernetes.io/name: {{ include "mychart.name" . }}
    helm.sh/chart: {{ include "mychart.chart" . }}
    app.kubernetes.io/instance: {{ .Release.Name }}
    app.kubernetes.io/managed-by: {{ .Release.Service }}
spec:
  replicas: {{ .Values.replicaCount }}
  selector:
    matchLabels:
      app.kubernetes.io/name: {{ include "mychart.name" . }}
      app.kubernetes.io/instance: {{ .Release.Name }}
  template:
    metadata:
      labels:
        app.kubernetes.io/name: {{ include "mychart.name" . }}
        app.kubernetes.io/instance: {{ .Release.Name }}
    spec:
      containers:
        - name: {{ .Chart.Name }}
          image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}"
          imagePullPolicy: {{ .Values.image.pullPolicy }}
          env:
            - name: Color
              value: {{ .Values.settings.color }}
            - name: Message
              value: {{ .Values.settings.message }}
          ports:
            - name: http
              containerPort: 80
              protocol: TCP
          livenessProbe:
            httpGet:
              path: /
              port: http
          readinessProbe:
            httpGet:
              path: /
              port: http
          resources:
{{ toYaml .Values.resources | indent 12 }}
    {{- with .Values.nodeSelector }}
      nodeSelector:
{{ toYaml . | indent 8 }}
    {{- end }}
    {{- with .Values.affinity }}
      affinity:
{{ toYaml . | indent 8 }}
    {{- end }}
    {{- with .Values.tolerations }}
      tolerations:
{{ toYaml . | indent 8 }}
    {{- end }}

若要将敏感数据存储为 Kubernetes 机密,请在 templates 文件夹下添加一个 secrets.yaml 文件 。To store sensitive data as Kubernetes Secrets, add a secrets.yaml file under the templates folder.

提示

详细了解如何使用 Kubernetes 机密Learn more about how to use Kubernetes Secrets.

apiVersion: v1
kind: Secret
metadata:
  name: mysecret
type: Opaque
data:
  password: {{ .Values.secrets.password | b64enc }}

最后,使用以下内容更新 values.yaml 文件,以便选择性地为 deployment.yaml 和 secrets.yaml 文件中引用的配置设置和机密提供默认值 。Finally, update the values.yaml file with the following content to optionally provide default values of the configuration settings and secrets that referenced in the deployment.yaml and secrets.yaml files. 从应用程序配置中提取的配置将覆盖其实际值。Their actual values will be overwritten by configuration pulled from App Configuration.

# settings will be overwritten by App Configuration
settings:
    color: red
    message: myMessage

在 Helm 安装中传递应用程序配置中的配置Pass configuration from App Configuration in Helm install

首先,将应用程序配置中的配置下载到 myConfig.yaml 文件 。First, download the configuration from App Configuration to a myConfig.yaml file. 使用密钥筛选器,以便仅下载以 settings. 开头的密钥 。Use a key filter to only download those keys that start with settings.. 如果密钥筛选器不足以排除 Key Vault 引用的密钥,可以使用参数 --skip-keyvault 来排除它们 。If in your case the key filter is not sufficient to exclude keys of Key Vault references, you may use the argument --skip-keyvault to exclude them.

提示

详细了解 export 命令Learn more about the export command.

az appconfig kv export -n myAppConfiguration -d file --path myConfig.yaml --key "settings.*"  --separator "." --format yaml

接下来,将机密下载到名为 mySecrets.yaml 的文件 。Next, download secrets to a file called mySecrets.yaml. 命令行参数 --resolve-keyvault 通过检索 Key Vault 中的实际值来解析 Key Vault 参考 。The command-line argument --resolve-keyvault resolves the Key Vault references by retrieving the actual values in Key Vault. 需要使用对相应 Key Vault 拥有访问权限的凭据来运行此命令。You'll need to run this command with credentials that have access permissions to the corresponding Key Vault.

警告

由于此文件包含敏感信息,因此请谨慎保存此文件,并在不再需要时清理其内容。As this file contains sensitive information, keep the file with care and clean up when it's not needed anymore.

az appconfig kv export -n myAppConfiguration -d file --path mySecrets.yaml --key "secrets.*" --separator "." --resolve-keyvault --format yaml

使用 helm upgrade 的 -f 参数传入你创建的两个配置文件 。Use helm upgrade's -f argument to pass in the two configuration files you've created. 这些文件将使用从应用程序配置导出的值重写 values.yaml 中定义的配置值 。They'll override the configuration values defined in values.yaml with the values exported from App Configuration.

helm upgrade --install -f myConfig.yaml -f mySecrets.yaml "example" ./mychart 

还可以使用 --set 参数让 helm upgrade 传递文本密钥值 。You can also use the --set argument for helm upgrade to pass literal key values. 使用 --set 参数能够很好地避免在磁盘中保存敏感数据 。Using the --set argument is a good way to avoid persisting sensitive data to disk.

$secrets = az appconfig kv list -n myAppConfiguration --key "secrets.*" --resolve-keyvault --query "[*].{name:key, value:value}" | ConvertFrom-Json

foreach ($secret in $secrets) {
  $keyvalues += $secret.name + "=" + $secret.value + ","
}

if ($keyvalues){
  $keyvalues = $keyvalues.TrimEnd(',')
  helm upgrade --install --set $keyvalues "example" ./mychart 
}
else{
  helm upgrade --install "example" ./mychart 
}

访问 Kubernetes 仪表板来验证是否已成功设置配置和机密。Verify that configurations and secrets were set successfully by accessing the Kubernetes Dashboard. 你将看到,应用程序配置中的 color 和 message 值已填充到容器的环境变量中 。You'll see that the color and message values from App Configuration were populated into the container's environment variables.

本地启动应用快速入门

此外,已将一个在应用程序配置中作为 Key Vault 参考存储的机密 password 添加到了 Kubernetes 机密 。One secret, password, stores as Key Vault reference in App Configuration was also added into Kubernetes Secrets.

本地启动应用快速入门

清理资源Clean up resources

如果不想继续使用本文中创建的资源,请删除此处创建的资源组以避免产生费用。If you do not want to continue using the resources created in this article, delete the resource group you created here to avoid charges.

重要

删除资源组的操作不可逆。Deleting a resource group is irreversible. 将永久删除资源组以及其中的所有资源。The resource group and all the resources in it are permanently deleted. 请确保不要意外删除错误的资源组或资源。Make sure that you don't accidentally delete the wrong resource group or resources. 如果在包含要保留的其他资源的资源组中创建了本文的资源,请从相应的窗格中单独删除每个资源,而不是删除该资源组。If you created the resources for this article inside a resource group that contains other resources you want to keep, delete each resource individually from its respective pane instead of deleting the resource group.

  1. 登录到 Azure 门户,然后选择“资源组”。Sign in to the Azure portal, and select Resource groups.
  2. 在“按名称筛选”框中,输入资源组的名称。In the Filter by name box, enter the name of your resource group.
  3. 在结果列表中,选择资源组名称以查看概述。In the result list, select the resource group name to see an overview.
  4. 选择“删除资源组”。Select Delete resource group.
  5. 系统会要求确认是否删除资源组。You're asked to confirm the deletion of the resource group. 重新键入资源组的名称进行确认,然后选择“删除” 。Enter the name of your resource group to confirm, and select Delete.

片刻之后,将会删除该资源组及其所有资源。After a few moments, the resource group and all its resources are deleted.

后续步骤Next steps

在本教程中,你已通过 Helm 导出了要在 Kubernetes 部署中使用的 Azure 应用程序配置数据。In this tutorial, you exported Azure App Configuration data to be used in a Kubernetes deployment with Helm. 若要了解有关如何使用应用程序配置的更多信息,请继续阅读 Azure CLI 示例。To learn more about how to use App Configuration, continue to the Azure CLI samples.