Help us learn about your current experience with the documentation. Take the survey.

在 GitLab CI/CD 中使用 Azure Key Vault 密钥

  • Tier: Premium, Ultimate
  • Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated

您可以在 GitLab CI/CD 管道中使用存储在 Azure Key Vault 中的密钥。

先决条件:

  • 在 Azure 上拥有一个 Key Vault
    • 您的 IAM 用户必须被授予分配给 Key Vault 的 资源组Key Vault Administrator 角色分配 权限。否则,您无法在 Key Vault 中创建密钥。
  • 在 Azure 中配置 OpenID Connect 以获取临时凭据。这些步骤包括如何创建用于 Key Vault 访问的 Azure AD 应用的说明。
  • 向您的项目 添加 CI/CD 变量 以提供有关您的 Vault 服务器的详细信息:
    • AZURE_KEY_VAULT_SERVER_URL: 您的 Azure Key Vault 服务器 URL,例如 https://vault.example.com
    • AZURE_CLIENT_ID: Azure 应用的客户端 ID。
    • AZURE_TENANT_ID: Azure 应用的租户 ID。

在 CI/CD 作业中使用 Azure Key Vault 密钥

您可以通过使用 azure_key_vault 关键字定义来使用存储在 Azure Key Vault 中的密钥:

job:
  id_tokens:
    AZURE_JWT:
      aud: 'https://gitlab.com'
  secrets:
    DATABASE_PASSWORD:
      token: $AZURE_JWT
      azure_key_vault:
        name: 'test'
        version: '00000000000000000000000000000000'

在此示例中:

  • aud 是受众,必须与 创建联合身份凭据 时使用的受众匹配
  • name 是 Azure Key Vault 中密钥的名称。
  • version 是 Azure Key Vault 中密钥的版本。版本是一个生成的无连字符 GUID,可以在 Azure Key Vault 密钥页面上找到。
  • GitLab 从 Azure Key Vault 获取密钥并将值存储在临时文件中。此文件的路径存储在 DATABASE_PASSWORD CI/CD 变量中,类似于 文件类型 CI/CD 变量

故障排除

有关设置 Azure OIDC 时的常见问题,请参阅 Azure OIDC 故障排除

JWT token is invalid or malformed 消息

从 Azure Key Vault 获取密钥时,您可能会收到此错误:

RESPONSE 400 Bad Request
AADSTS50027: JWT token is invalid or malformed.

这是由于 GitLab Runner 中的一个 已知问题 导致 JWT 令牌解析不正确。要解决此问题,请升级到 GitLab Runner 16.6 或更高版本。

Caller is not authorized to perform action on resource 消息

从 Azure Key Vault 获取密钥时,您可能会收到此错误:

RESPONSE 403: 403 Forbidden
ERROR CODE: Forbidden
Caller is not authorized to perform action on resource.\r\nIf role assignments, deny assignments or role definitions were changed recently, please observe propagation time.
ForbiddenByRbac

如果您的 Azure Key Vault 使用 RBAC,您必须向您的 Azure AD 应用添加 Key Vault Secrets User 角色分配。

例如:

appId=$(az ad app list --display-name gitlab-oidc --query '[0].appId' -otsv)
az role assignment create --assignee $appId --role "Key Vault Secrets User" --scope /subscriptions/<subscription-id>

您可以在以下位置找到您的订阅 ID:

The secrets provider can not be found. Check your CI/CD variables and try again. 消息

尝试启动配置为访问 Azure Key Vault 的作业时,您可能会收到此错误:

The secrets provider can not be found. Check your CI/CD variables and try again.

由于一个或多个必需变量未定义,无法创建作业:

  • AZURE_KEY_VAULT_SERVER_URL
  • AZURE_CLIENT_ID
  • AZURE_TENANT_ID