练习 - 将 Lint 分析和验证阶段添加到管道

已完成

你已与你的团队交谈,并决定使用管道进一步自动执行部署。 你想要对部署的内容建立更多信心。

在此练习中,你将向管道添加验证阶段。 然后,在每个部署之前运行 Linter 和预检验证。

在此过程中,你将:

  • 更新现有管道,以添加两个新阶段来对 Bicep 代码执行 Lint 分析和验证。
  • 运行管道。
  • 解决管道检测到的所有问题。

更新管道以准备阶段

首先,需要更新管道文件以定义一个阶段。 Azure Pipelines 会自动创建一个阶段,但由于你很快会添加更多阶段,因此需要更新管道以显式定义阶段。

  1. 在 Visual Studio Code 中,打开 deploy 文件夹中的 azure-pipelines.yml 文件。

  2. 删除文件第 14 行到文件底部的所有内容。 请务必同时删除 jobs: 行。

  3. 在文件底部添加以下代码:

    stages:
    
    - stage: Deploy
      jobs:
      - job: Deploy
        steps:
          - task: AzureResourceManagerTemplateDeployment@3
            name: Deploy
            displayName: Deploy to Azure
            inputs:
              connectedServiceName: $(ServiceConnectionName)
              deploymentName: $(Build.BuildNumber)
              location: $(DeploymentDefaultLocation)
              resourceGroupName: $(ResourceGroupName)
              csmFile: deploy/main.bicep
              overrideParameters: >
                -environmentType $(EnvironmentType)
    

    提示

    YAML 文件对缩进敏感。 无论是键入还是粘贴此代码,都请确保缩进正确。 在下一部分中,你将看到完整的 YAML 管道定义,以便可验证文件是否匹配。

将 Lint 分析和验证阶段添加到管道

  1. stages: 行下方,添加 lint 分析阶段:

    - stage: Lint
      jobs:
      - job: LintCode
        displayName: Lint code
        steps:
          - script: |
              az bicep build --file deploy/main.bicep
            name: LintBicepCode
            displayName: Run Bicep linter
    

    此阶段定义了一个步骤,该步骤运行 az bicep build 命令来对 Bicep 文件执行 Lint 分析。

  2. 在刚添加的行下面,添加验证阶段:

    - stage: Validate
      jobs:
      - job: ValidateBicepCode
        displayName: Validate Bicep code
        steps:
          - task: AzureResourceManagerTemplateDeployment@3
            name: RunPreflightValidation
            displayName: Run preflight validation
            inputs:
              connectedServiceName: $(ServiceConnectionName)
              location: $(deploymentDefaultLocation)
              deploymentMode: Validation
              resourceGroupName: $(ResourceGroupName)
              csmFile: deploy/main.bicep
              overrideParameters: >
                -environmentType $(EnvironmentType)
    

    此阶段定义了一个运行预检验证的步骤。 请注意,该步骤包括对服务连接的引用,因为预检验证过程需要与 Azure 通信。

    管道定义现在有 3 个阶段。 第一个是对 Bicep 文件运行 Linter,第二个是执行预检验证,第三个是执行到 Azure 的部署。

  3. 保存文件。

配置 Linter

默认情况下,Bicep Linter 会在检测到文件有问题时发出警告。 Azure Pipelines 不会将 Linter 警告视为应停止管道的问题。 若要自定义此行为,请创建一个 bicepconfig.json 文件来重新配置 Linter。

  1. 在 deploy 文件夹中添加一个新文件,并将其命名为 bicepconfig.json。

    Screenshot of Visual Studio Code Explorer, with the new file shown in the deploy folder.

  2. 将以下代码复制到文件中:

    {
      "analyzers": {
        "core": {
          "enabled": true,
          "verbose": true,
          "rules": {
            "adminusername-should-not-be-literal": {
              "level": "error"
            },
            "max-outputs": {
              "level": "error"
            },
            "max-params": {
              "level": "error"
            },
            "max-resources": {
              "level": "error"
            },
            "max-variables": {
              "level": "error"
            },
            "no-hardcoded-env-urls": {
              "level": "error"
            },
            "no-unnecessary-dependson": {
              "level": "error"
            },
            "no-unused-params": {
              "level": "error"
            },
            "no-unused-vars": {
              "level": "error"
            },
            "outputs-should-not-contain-secrets": {
              "level": "error"
            },
            "prefer-interpolation": {
              "level": "error"
            },
            "secure-parameter-default": {
              "level": "error"
            },
            "simplify-interpolation": {
              "level": "error"
            },
            "protect-commandtoexecute-secrets": {
              "level": "error"
            },
            "use-stable-vm-image": {
              "level": "error"
            }
          }
        }
      }
    }
    
  3. 保存文件。

验证并提交管道定义

  1. 验证 azure-pipelines.yml 文件是否如下文件所示:

    trigger:
      batch: true
      branches:
        include:
        - main
    
    pool:
      vmImage: ubuntu-latest
    
    variables:
      - name: deploymentDefaultLocation
        value: westus3
    
    stages:
    
    - stage: Lint
      jobs:
      - job: LintCode
        displayName: Lint code
        steps:
          - script: |
              az bicep build --file deploy/main.bicep
            name: LintBicepCode
            displayName: Run Bicep linter
    
    - stage: Validate
      jobs:
      - job: ValidateBicepCode
        displayName: Validate Bicep code
        steps:
          - task: AzureResourceManagerTemplateDeployment@3
            name: RunPreflightValidation
            displayName: Run preflight validation
            inputs:
              connectedServiceName: $(ServiceConnectionName)
              location: $(deploymentDefaultLocation)
              deploymentMode: Validation
              resourceGroupName: $(ResourceGroupName)
              csmFile: deploy/main.bicep
              overrideParameters: >
                -environmentType $(EnvironmentType)
    
    - stage: Deploy
      jobs:
      - job: Deploy
        steps:
          - task: AzureResourceManagerTemplateDeployment@3
            name: Deploy
            displayName: Deploy to Azure
            inputs:
              connectedServiceName: $(ServiceConnectionName)
              deploymentName: $(Build.BuildNumber)
              location: $(DeploymentDefaultLocation)
              resourceGroupName: $(ResourceGroupName)
              csmFile: deploy/main.bicep
              overrideParameters: >
                -environmentType $(EnvironmentType)
    

    如果不是,请更新它以匹配此示例,然后保存。

  2. 通过在 Visual Studio Code 终端中运行以下命令来提交更改并将其推送到 Git 存储库:

    git add .
    git commit -m "Add lint and validation stages"
    git push
    

    推送后,Azure Pipelines 会立即启动新的管道运行。

查看管道运行

  1. 在浏览器中,转到“管道”。

  2. 选择管道的最新运行。

    Screenshot of Azure DevOps with the link to the latest pipeline run highlighted.

    如果管道仍在运行,请等到运行完成。 虽然 Azure Pipelines 会使用最新状态自动更新页面,但仍建议偶尔刷新页面。

  3. 请注意,管道运行现在显示了你在 YAML 文件中定义的 3 个阶段。 另请注意,“Lint 分析”阶段已失败。

    Screenshot of a pipeline run in Azure DevOps, with the Lint stage reporting failure.

  4. 选择“Lint 分析”阶段以查看其详细信息。

    Screenshot of a pipeline run in Azure DevOps, with the name of the Lint stage highlighted.

  5. 选择“运行 Bicep Linter”步骤以查看管道日志。

    Screenshot of the pipeline log for the Lint stage, with the step for running a Bicep linter highlighted.

    请注意,显示的错误如下所示:

    错误 no-unused-params: 声明了参数 "storageAccountNameParam",但从未使用过该参数。

    此错误表示 Linter 在 Bicep 文件中发现了规则冲突。

修复 Linter 错误

确定问题后,可以在 Bicep 文件中修复它。

  1. 在 Visual Studio Code 中,打开 deploy 文件夹中的 main.bicep 文件。

  2. 请注意,Bicep Linter 还检测到 storageAccountNameParam 参数未使用。 Visual Studio Code 使用波浪线指示未使用的参数。 通常情况下,这一行会呈黄色以表示警告。 但由于你自定义了 bicepconfig.json 文件,因此 Linter 将代码视为错误,并以红色显示该行。

    param storageAccountNameParam string = uniqueString(resourceGroup().id)
    
  3. 删除 storageAccountNameParam 参数。

  4. 保存文件。

  5. 通过在 Visual Studio Code 终端中运行以下命令来提交更改并将其推送到 Git 存储库:

    git add .
    git commit -m "Remove unused parameter"
    git push
    

    同样,Azure Pipelines 会自动触发管道的新运行。

再次查看管道运行

  1. 在浏览器中,转到你的管道。

  2. 选择最近的运行。

    等待管道运行完成。 虽然 Azure Pipelines 会使用最新状态自动更新页面,但仍建议偶尔刷新页面。

  3. 请注意,“Lint 分析”阶段已成功完成,但现在“验证”阶段失败了。

    Screenshot of the pipeline run, with the Lint stage reporting success and the Validate stage reporting failure.

  4. 选择“验证”阶段以查看其详细信息。

  5. 选择“运行预检验证”步骤以查看管道日志。

    Screenshot of the pipeline log for the Validate stage, with the step for running preflight validation highlighted.

    请注意,日志中显示的错误包括以下消息:

    mystorageresourceNameSuffix 不是有效的存储帐户名称。 存储帐户名称长度必须为 3 到 24 个字符,并且只能使用数字和小写字母。

    此错误表示存储帐户名称无效。

修复验证错误

你在 Bicep 文件中发现了另一个问题。 修复此问题的方法如下:

  1. 在 Visual Studio Code 中,打开 deploy 文件夹中的 main.bicep 文件。

  2. 查看 storageAccountName 变量的定义:

    var appServiceAppName = 'toy-website-${resourceNameSuffix}'
    var appServicePlanName = 'toy-website'
    var applicationInsightsName = 'toywebsite'
    var logAnalyticsWorkspaceName = 'workspace-${resourceNameSuffix}'
    var storageAccountName = 'mystorageresourceNameSuffix'
    

    似乎有拼写错误,并且字符串内插未正确配置。

  3. 更新 storageAccountName 变量以正确使用字符串内插:

    var storageAccountName = 'mystorage${resourceNameSuffix}'
    
  4. 保存文件。

  5. 通过在 Visual Studio Code 终端中运行以下命令来提交更改并将其推送到 Git 存储库:

    git add .
    git commit -m "Fix string interpolation"
    git push
    

查看成功的管道运行

  1. 在浏览器中,转到你的管道。

  2. 选择最近的运行。

    等待管道运行完成。 虽然 Azure Pipelines 会使用最新状态自动更新页面,但仍建议偶尔刷新页面。

  3. 请注意,管道的所有三个阶段都已成功完成:

    Screenshot of the pipeline run in Azure DevOps, with all three stages reporting success.

你现在拥有一个管道,可以在部署过程的早期成功检测到 Bicep 代码中的错误,如果没有错误,则部署到 Azure。