使用 Bicep Linter

Bicep Linter 会检查 Bicep 文件是否存在语法错误以及违反最佳做法。 Linter 在开发过程中提供指导,帮助用户实施代码标准。 你可以自定义最佳做法,用于检查文件。

Linter 要求

Linter 已集成到 Bicep CLI 和 Visual Studio Code 的 Bicep 扩展中。 若要使用它,必须具有 Bicep CLI 0.4 或更高版本。

默认规则

默认的 Linter 规则集最小,取自 arm-ttk 测试用例。 扩展和 Bicep CLI 会在默认层级检查以下规则。

Linter 规则 默认级别
adminusername-should-not-be-literal 警告
artifacts-parameters 警告
decompiler-cleanup 警告
explicit-values-for-loc-parameters 关
max-asserts 错误
max-outputs 错误
max-parameters 错误
max-resources 错误
max-variables 错误
nested-deployment-template-scoping 错误
no-conflicting-metadata 警告
no-conflicting-version-constraints 错误
no-deployments-resources 警告
no-explicit-any 警告
no-hardcoded-env-urls 警告
no-hardcoded-location 关
no-hardcoded-outputs 关
no-incompatible-entrypoint-version 警告
no-loc-expr-outside-parameters 关
no-module-name 关
no-unnecessary-dependson 警告
no-unused-existing-resources 警告
no-unused-imports 警告
no-unused-parameters 警告
no-unused-types 警告
no-unused-vars 警告
outputs-should-not-contain-secrets 警告
prefer-interpolation 警告
prefer-unquoted-property-names 警告
protect-commandtoexecute-secrets 警告
secure-parameter-default 警告
secure-parameters-in-nested-deploy 警告
secure-parameters-in-parameters-file 警告
secure-secrets-in-parameters 警告
简化插值 警告
simplify-json-null 警告
use-description-outputs 关
use-description-params 关
use-description-type-properties 关
use-description-types 关
use-description-vars 关
use-parent-property 警告
use-recent-api-versions 关
use-recent-az-powershell-version 警告
use-recent-module-versions 关
use-recognized-resource-type 警告
use-resource-id-functions 关
use-resource-symbol-reference 警告
use-safe-access 警告
use-secure-value-for-secure-inputs 警告
use-stable-resource-identifiers 警告
use-stable-vm-image 警告
use-user-defined-types 关
what-if-short-circuiting 关

可以启用或禁用所有 linter 规则,并控制如何使用配置文件应用它们。 若要替代默认行为,请使用自定义设置创建 bicepconfig.json 文件。 有关应用这些设置的详细信息,请参阅在 Bicep 配置文件中添加自定义设置。

在 Visual Studio Code 中使用

以下屏幕截图显示了 Visual Studio Code 中的 Linter:

Visual Studio Code中的Bicep linter 用法。

在 “问题 ”窗格中,屏幕截图显示四个错误、一个警告和一条信息消息。 信息消息显示了所使用的 Bicep 配置文件。 仅当在配置文件中将verbose设置为true时,才显示这一信息。

将鼠标光标悬停在问题区域之一上。 linter 提供有关错误或警告的详细信息。 选择该区域,还会显示蓝色灯泡:

Visual Studio Code中的Bicep linter 用法 - 显示快速修复。

选择灯泡或“快速修复”链接以查看解决方法:

Visual Studio Code 中的 Bicep linter 用法 - 显示快速修复解决方案。

选择解决方法以自动解决问题。

使用 Bicep CLI

以下屏幕截图显示了命令行中的 Linter。 lint 命令和 build 命令显示任何规则违反情况。

Bicep命令行中的 linter 用法。

可以将这些检查集成到您的 CI/CD 流水线中。 可以使用 GitHub 操作来尝试生成 Bicep。 错误会导致流水线失败。

消除误报

有时,规则会产生误报。 例如,可能需要直接包含 Blob 存储的链接,而无需使用 environment() 函数。

可以使用 disable-next-line 和 disable-diagnostics 来忽略 Bicep linter 规则。 请参阅 指令。 如果要取消 linter 规则,请将规则级别更改为 Offbicepconfig.json。 在以下示例中,会抑制 no-deployments-resources 规则:

{
  "analyzers": {
    "core": {
      "rules": {
        "no-deployments-resources": {
          "level": "off"
        }
      }
    }
  }
}

后续步骤