Partilhar via


Gerenciar variáveis em grupos de variáveis com a CLI do Azure DevOps

Serviços de DevOps do Azure | Azure DevOps Server

Gerenciar variáveis no Azure Pipelines é crucial para manter a flexibilidade e a segurança em seus fluxos de trabalho de CI/CD. Este artigo mostra como usar a CLI Azure DevOps para criar e gerir variáveis secretas e não secretas dentro de um grupo de variáveis Azure Pipelines. Usando grupos de variáveis, você pode centralizar o gerenciamento de variáveis e garantir que as informações confidenciais sejam tratadas com segurança.

Ao usar o exemplo deste artigo, aprende como:

  • Defina um pipeline do Azure Pipelines usando um arquivo YAML armazenado no GitHub.
  • Crie um grupo de variáveis contendo variáveis secretas e não secretas.
  • Execute o pipeline usando a CLI do Azure DevOps e monitore o processamento da execução e a saída.

Nota

Este exemplo demonstra a funcionalidade da CLI do Azure DevOps com grupos de variáveis. Para aumentar a segurança, defina variáveis em grupos de variáveis na interface do usuário do Pipelines ou vincule um grupo de variáveis a segredos no Cofre de Chaves do Azure.

Pré-requisitos

Guardar ficheiro YAML do pipeline

Guarde a seguinte definição do pipeline YAML como um ficheiro chamado azure-pipelines.yml no diretório raiz e main na ramificação do seu repositório GitHub.

parameters:
- name: image
  displayName: 'Pool image'
  default: ubuntu-latest
  values:
  - windows-latest
  - ubuntu-latest
  - macOS-latest
- name: test
  displayName: Run Tests?
  type: boolean
  default: false

variables:
- group: "Contoso Variable Group"
- name: va
  value: $[variables.a]
- name: vb
  value: $[variables.b]
- name: vcontososecret
  value: $[variables.contososecret]

trigger:
- main

pool:
  vmImage: ubuntu-latest

steps:
- script: |
    echo "Hello, world!"
    echo "Pool image: ${{ parameters.image }}"
    echo "Run tests? ${{ parameters.test }}"
  displayName: 'Show runtime parameter values'

- script: |
    echo "a=$(va)"
    echo "b=$(vb)"
    echo "contososecret=$(vcontososecret)"
    echo
    echo "Count up to the value of the variable group's nonsecret variable *a*:"
    for number in {1..$(va)}
    do
        echo "$number"
    done
    echo "Count up to the value of the variable group's nonsecret variable *b*:"
    for number in {1..$(vb)}
    do
        echo "$number"
    done
    echo "Count up to the value of the variable group's secret variable *contososecret*:"
    for number in {1..$(vcontososecret)}
    do
        echo "$number"
    done
  displayName: 'Test variable group variables (secret and nonsecret)'
  env:
    SYSTEM_ACCESSTOKEN: $(System.AccessToken)

O script de exemplo

Este script de exemplo executa as seguintes tarefas:

  • Cria os recursos DevOps
  • Executa o oleoduto
  • Modifica os valores das variáveis três vezes
  • Executa o pipeline novamente cada vez que os valores das variáveis mudam

O script cria os seguintes recursos no Azure DevOps:

  • Um projeto em sua organização de DevOps
  • Uma conexão de serviço GitHub
  • Um gasoduto
  • Um grupo de variáveis com duas variáveis não secretas e uma variável secreta

Antes de executares o script, substitui os seguintes marcadores de posição:

  • <devops-organization> O nome da sua organização Azure DevOps. Por exemplo, se o Azure DevOps URL for https://dev.azure.com/Contoso, use Contoso.
  • <github-organization> A sua organização no GitHub ou nome de utilizador. Por exemplo, myusername ou myorganization.
  • <github-repository> O nome do teu repositório no GitHub. Por exemplo, se o URL do seu repositório for https://github.com/myusername/my-repo, use my-repo.
  • <pipelinename> Um nome para o pipeline que tenha entre 3 e 19 caracteres e contenha apenas numerais e letras minúsculas. O script adiciona um identificador exclusivo de cinco dígitos. Por exemplo, mypipeline.

Salve sua PAT do GitHub em seu ambiente local.

AZURE_DEVOPS_EXT_GITHUB_PAT=<your-github-pat>

Depois de armazenar o ficheiro YAML no GitHub, execute o seguinte script CLI do Azure DevOps numa shell Bash no Azure Cloud Shell ou localmente.

Importante

Certifique-se de que tem a versão mais recente do Azure CLI e da extensão DevOps instaladas. Execute az upgrade e az extension add --name azure-devops antes de executar este script.

#!/bin/bash

# ===== CONFIGURATION =====
# Replace the placeholder values with your own.
devopsOrg="https://dev.azure.com/<devops-organization>"
githubOrg="<github-organization>"
githubRepo="<github-repository>"
pipelineName="<pipeline-name>"
repoName="$githubOrg/$githubRepo"
repoType="github"
branch="main"

# Declare other variables.
uniqueId=$RANDOM
devopsProject="Contoso DevOps Project $uniqueId"
serviceConnectionName="Contoso Service Connection $uniqueId"
variableGroupName="Contoso Variable Group $uniqueId"

# ===== AUTHENTICATION =====
# Sign in to Azure CLI and follow the sign-in instructions, if necessary.
echo "Signing in to Azure CLI..."
az login

# Sign in to Azure DevOps with your Azure DevOps PAT, if necessary.
# Uncomment the following line if your Azure AD account doesn't have Azure DevOps access.
# echo "Signing in to Azure DevOps..."
# az devops login

# ===== PROJECT CREATION =====
# Create the Azure DevOps project and set defaults.
echo "Creating Azure DevOps project..."
projectId=$(az devops project create \
    --name "$devopsProject" \
    --organization "$devopsOrg" \
    --visibility private \
    --query id \
    --output tsv)
echo "Project created with ID: $projectId"

# Set default organization and project for subsequent commands.
az devops configure --defaults organization="$devopsOrg" project="$devopsProject"
pipelineRunUrlPrefix="$devopsOrg/$projectId/_build/results?buildId="

# ===== SERVICE CONNECTION =====
# Create GitHub service connection.
echo "Creating GitHub service connection..."
githubServiceEndpointId=$(az devops service-endpoint github create \
    --name "$serviceConnectionName" \
    --github-url "https://www.github.com/$repoName" \
    --query id \
    --output tsv)
echo "Service connection created with ID: $githubServiceEndpointId"

# ===== PIPELINE CREATION =====
# Create the pipeline from the YAML file.
echo "Creating pipeline..."
pipelineId=$(az pipelines create \
    --name "$pipelineName" \
    --skip-first-run \
    --repository $repoName \
    --repository-type $repoType \
    --branch $branch \
    --service-connection $githubServiceEndpointId \
    --yml-path azure-pipelines.yml \
    --query id \
    --output tsv)
echo "Pipeline created with ID: $pipelineId"

# ===== VARIABLE GROUP =====
# Create a variable group with 2 non-secret variables and 1 secret variable.
echo "Creating variable group..."
variableGroupId=$(az pipelines variable-group create \
    --name "$variableGroupName" \
    --authorize true \
    --variables a=12 b=29 \
    --query id \
    --output tsv)
echo "Variable group created with ID: $variableGroupId"

# Add a secret variable to the group.
echo "Adding secret variable to the group..."
az pipelines variable-group variable create \
    --group-id $variableGroupId \
    --name contososecret \
    --secret true \
    --value 17

# ===== PIPELINE RUNS =====
# Run the pipeline for the first time.
echo "Running pipeline (1st run)..."
pipelineRunId1=$(az pipelines run \
    --id $pipelineId \
    --query id \
    --output tsv)
echo "Pipeline run 1 started with ID: $pipelineRunId1"
echo "Go to the pipeline run's web page to view the output results of the 'Test variable group variables' job."
echo "URL: ${pipelineRunUrlPrefix}${pipelineRunId1}"
read -p "Press Enter to change the value of variable 'a', then run again:"

# Change the value of one of the variable group's nonsecret variables.
echo "Updating variable 'a'..."
az pipelines variable-group variable update \
    --group-id $variableGroupId \
    --name a \
    --value 22

# Run the pipeline for the second time.
echo "Running pipeline (2nd run)..."
pipelineRunId2=$(az pipelines run \
    --id $pipelineId \
    --query id \
    --output tsv)
echo "Pipeline run 2 started with ID: $pipelineRunId2"
echo "URL: ${pipelineRunUrlPrefix}${pipelineRunId2}"
read -p "Press Enter to change the value of the secret variable, then run once more:"

# Change the value of the variable group's secret variable.
echo "Updating secret variable 'contososecret'..."
az pipelines variable-group variable update \
    --group-id $variableGroupId \
    --name contososecret \
    --value 35

# Run the pipeline for the third time.
echo "Running pipeline (3rd run)..."
pipelineRunId3=$(az pipelines run \
    --id $pipelineId \
    --query id \
    --output tsv)
echo "Pipeline run 3 started with ID: $pipelineRunId3"
echo "URL: ${pipelineRunUrlPrefix}${pipelineRunId3}"
read -p "Press Enter to continue:"

Limpar recursos

Para evitar custos pelo projeto Azure, elimine o projeto de exemplo. Esta ação também elimina o seu recurso.

Copie o id do projeto de exemplo do resultado do seguinte comando:

az devops project list --org <your-organization>

Exclua o projeto executando o seguinte comando:

az devops project delete --id <project-id> --org <your-organization> --yes

Limpe seu ambiente local executando os seguintes comandos:

export AZURE_DEVOPS_EXT_GITHUB_PAT=""
az devops configure --defaults organization="" project=""

Referências da CLI do Azure

O exemplo neste artigo usa os seguintes comandos da CLI do Azure: