如何从 DevOps 管道安全登录 Az CLI

How to securely login in Az CLI from a DevOps Pipeline

我想从我的 Azure DevOps 管道执行 AZ cli 命令。在我的 YAML 文件中我有这个:

trigger:
- master

pool:
  vmImage: 'ubuntu-latest'

variables:
  buildConfiguration: 'Release'

steps:
- task: UsePythonVersion@0
  inputs:
    versionSpec: '3.x'
    architecture: 'x64'

# Updating pip to latest
- script: python -m pip install --upgrade pip
  displayName: 'Upgrade pip'

# Updating to latest Azure CLI version.
- script: pip install --pre azure-cli --extra-index-url https://azurecliprod.blob.core.windows.net/edge
  displayName: 'upgrade azure cli'

- script: az --version
  displayName: 'Show Azure CLI version'

- script: az extension add -n azure-devops
  displayName: 'Install Azure DevOps Extension'

- script: echo ${AZURE_DEVOPS_CLI_PAT} | az devops login
  env:
    AZURE_DEVOPS_CLI_PAT: $(System.AccessToken)
  displayName: 'Login Azure DevOps Extension'

- script: az aks show --name census-k8s  --resource-group Census
  displayName: 'Show AKS'

echo ${AZURE_DEVOPS_CLI_PAT} | az devops login 步骤已完成(显然成功)并出现一条警告消息

Failed to store PAT using keyring; falling back to file storage.
You can clear the stored credential by running az devops logout.
Refer https://aka.ms/azure-devops-cli-auth to know more on sign in with PAT.

az aks show 步骤失败:

Please run 'az login' to setup account.

我有点迷茫。 az devops login 命令应该能让我使用 az cli,对吗?如果不是,我是否应该使用 az login 而不是 az devops login?如果我应该使用 az login,我该如何以安全的方式传递我的凭据?

不,你不需要 az devops login。你需要的是 Azure CLI Task:

- task: AzureCLI@2
  displayName: Azure CLI
  inputs:
    azureSubscription: <Name of the Azure Resource Manager service connection>
    scriptType: ps
    scriptLocation: inlineScript
    inlineScript: |
      az --version
      az account show

但是您不必进行任何登录。请在那里打电话给你的 az aks show --name census-k8s --resource-group Census

补充一下 Krzysztof 的回答(以及评论中的 jeromerg 问题):在 Azure CLI 步骤中,您还可以使用其他工具然后 az,这需要使用 AzureCLI 登录:

- task: AzureCLI@2
  displayName: Publish Function
  inputs:
    azureSubscription: <Name of the Azure Resource Manager service connection>
    scriptType: ps
    scriptLocation: inlineScript
    inlineScript: |
      func azure publish <function-name>

如果您的 scriptLocation 是 scriptPath,请使用以下示例

  - task: AzureCLI@2
    displayName: 'update function appsettings'
    inputs:
    azureSubscription: 'MY-AzureSubscriptionName'
    scriptType: ps
    scriptLocation: 'scriptPath'
    scriptPath: '$(System.DefaultWorkingDirectory)/Scripts/updateSettings.ps1'
    arguments:
        -ResourceGroupName 'MY-ResourceGroupName' `
        -FunctionAppName 'MY-FunctionAppName'

更新设置。ps1

param (
    [string]$ResourceGroupName,
    [string]$FunctionAppName)
)
.
. script body here
.