Condividi tramite


Parametri del modello

È possibile specificare i parametri e i relativi tipi di dati in un modello e fare riferimento a tali parametri in una pipeline. Con templateContext è anche possibile passare proprietà a fasi, passaggi e processi usati come parametri in un modello.

È anche possibile usare parametri esterni ai modelli. È possibile usare valori letterali solo per i valori predefiniti dei parametri. Altre informazioni sui parametri nello schema YAML.

Passaggio dei parametri

I parametri devono contenere un nome e un tipo di dati. In azure-pipelines.yml, quando il parametro yesNo è impostato su un valore booleano, la compilazione ha esito positivo. Quando yesNo è impostato su una stringa, applesad esempio , la compilazione ha esito negativo.

# File: simple-param.yml
parameters:
- name: yesNo # name of the parameter; required
  type: boolean # data type of the parameter; required
  default: false

steps:
- script: echo ${{ parameters.yesNo }}
# File: azure-pipelines.yml
trigger:
- main

extends:
  template: simple-param.yml
  parameters:
      yesNo: false # set to a non-boolean value to have the build fail

Usare templateContext per passare le proprietà ai modelli

È possibile usare templateContext per passare più proprietà a fasi, passaggi e processi usati come parametri in un modello. In particolare, è possibile specificare templateContext all'interno del tipo di dati del parametro jobList, deploymentList o stageList.

È possibile usare templateContext per semplificare la configurazione degli ambienti durante l'elaborazione di ogni processo. Raggruppando un processo e l'oggetto delle proprietà dell'ambiente, templateContext può aiutarti a mantenere un YAML più gestibile e più facile da comprendere.

In questo esempio il parametro testSet in testing-template.yml ha il tipo di jobListdati . Il modello testing-template.yml crea una nuova variabile testJob usando la parola chiave each. Il modello fa quindi riferimento a testJob.templateContext.expectedHTTPResponseCode, che viene impostato in azure-pipeline.yml e passato al modello.

Quando il codice di risposta è 200, il modello effettua una richiesta REST. Quando il codice di risposta è 500, il modello restituisce tutte le variabili di ambiente per il debug.

templateContext può contenere proprietà.

#testing-template.yml

parameters: 
- name: testSet
  type: jobList

jobs:
- ${{ each testJob in parameters.testSet }}:  # Iterate over each job in the 'testSet' parameter
  - ${{ if eq(testJob.templateContext.expectedHTTPResponseCode, 200) }}: # Check if the HTTP response is 200
    - job:
      steps: 
      - powershell: 'Invoke-RestMethod -Uri https://blogs.msdn.microsoft.com/powershell/feed/ | Format-Table -Property Title, pubDate'
      - ${{ testJob.steps }}    
  - ${{ if eq(testJob.templateContext.expectedHTTPResponseCode, 500) }}: # Check if the HTTP response is 500
    - job:
      steps:
      - powershell: 'Get-ChildItem -Path Env:\' # Run a PowerShell script to list environment variables
      - ${{ testJob.steps }} # Include additional steps from the 'testJob' object
#azure-pipeline.yml

trigger: none

pool:
  vmImage: ubuntu-latest

extends:
  template: testing-template.yml 
  parameters:
    testSet:  # Define the 'testSet' parameter to pass to the template
    - job: positive_test # Define a job named 'positive_test'
      templateContext:
        expectedHTTPResponseCode: 200 # Set the expected HTTP response code to 200 for this job
      steps:
      - script: echo "Run positive test" 
    - job: negative_test # Define a job named 'negative_test'
      templateContext:
        expectedHTTPResponseCode: 500 # Set the expected HTTP response code to 500 for this job
      steps:
      - script: echo "Run negative test" 

Parametri per selezionare un modello in fase di esecuzione

È possibile chiamare modelli diversi da un YAML della pipeline a seconda di una condizione. In questo esempio, YAML experimental.yml viene eseguito quando il parametro experimentalTemplate è true.

#azure-pipeline.yml
parameters:
- name: experimentalTemplate 
  displayName: 'Use experimental build process?'
  type: boolean
  default: false

steps:
- ${{ if eq(parameters.experimentalTemplate, true) }}: # Check if 'experimentalTemplate' is true
  - template: experimental.yml
- ${{ if not(eq(parameters.experimentalTemplate, true)) }}:  # Check if 'experimentalTemplate' is not true
  - template: stable.yml

Tipi di dati dei parametri

Tipo di dati Note
string string
number può essere limitato a values:, altrimenti è accettata qualsiasi stringa simile a un numero.
boolean true oppure false
object qualsiasi struttura YAML
step un singolo passaggio
stepList sequenza di passaggi
job un unico lavoro
jobList sequenza di processi
deployment un singolo processo di implementazione
deploymentList sequenza di lavori di distribuzione
stage una singola fase
stageList sequenza di fasi

I tipi di dati step, stepList, job, jobList, deployment, deploymentList, stage e stageList usano tutti il formato di schema YAML standard. Questo esempio include string, number, boolean, object, step e stepList.

parameters:
- name: myString  # Define a parameter named 'myString'
  type: string  # The parameter type is string
  default: a string  # Default value is 'a string'

- name: myMultiString  # Define a parameter named 'myMultiString'
  type: string  # The parameter type is string
  default: default  # Default value is 'default'
  values:  # Allowed values for 'myMultiString'
  - default  
  - ubuntu  

- name: myNumber  # Define a parameter named 'myNumber'
  type: number  # The parameter type is number
  default: 2  # Default value is 2
  values:  # Allowed values for 'myNumber'
  - 1  
  - 2  
  - 4  
  - 8  
  - 16  

- name: myBoolean  # Define a parameter named 'myBoolean'
  type: boolean  # The parameter type is boolean
  default: true  # Default value is true

- name: myObject  # Define a parameter named 'myObject'
  type: object  # The parameter type is object
  default:  # Default value is an object with nested properties
    foo: FOO  # Property 'foo' with value 'FOO'
    bar: BAR  # Property 'bar' with value 'BAR'
    things:  # Property 'things' is a list
    - one  
    - two  
    - three  
    nested:  # Property 'nested' is an object
      one: apple  # Property 'one' with value 'apple'
      two: pear  # Property 'two' with value 'pear'
      count: 3  # Property 'count' with value 3

- name: myStep  # Define a parameter named 'myStep'
  type: step  # The parameter type is step
  default:  # Default value is a step
    script: echo my step 

- name: mySteplist  # Define a parameter named 'mySteplist'
  type: stepList  # The parameter type is stepList
  default:  # Default value is a list of steps
    - script: echo step one  
    - script: echo step two  

trigger: none  

jobs: 
- job: stepList  # Define a job named 'stepList'
  steps: ${{ parameters.mySteplist }}  # Use the steps from the 'mySteplist' parameter

- job: myStep  # Define a job named 'myStep'
  steps:
    - ${{ parameters.myStep }}  # Use the step from the 'myStep' parameter

È possibile scorrere un oggetto e stampare ogni stringa nell'oggetto .

parameters:
- name: listOfStrings  
  type: object
  default: 
  - one
  - two

steps:
- ${{ each value in parameters.listOfStrings }}: # Iterate over each value in the 'listOfStrings' parameter
  - script: echo ${{ value }} # Output the current value in the iteration

Inoltre, è possibile scorrere gli elementi annidati all'interno di un oggetto .

parameters:
- name: listOfFruits
  type: object
  default:
  - fruitName: 'apple'
    colors: ['red','green']
  - fruitName: 'lemon'
    colors: ['yellow'] 

steps:
- ${{ each fruit in parameters.listOfFruits }} : # Iterate over each fruit in the 'listOfFruits'
  - ${{ each fruitColor in fruit.colors}} : # Iterate over each color in the current fruit's colors
    - script: echo ${{ fruit.fruitName}} ${{ fruitColor }} # Echo the current fruit's name and color

È anche possibile fare riferimento direttamente alle chiavi di un oggetto e ai valori corrispondenti.

parameters:
  - name: myObject
    type: object
    default:
      key1: 'value1'
      key2: 'value2'
      key3: 'value3'

jobs:
- job: ExampleJob
  displayName: 'Example object parameter job'
  pool:
    vmImage: 'ubuntu-latest'
  steps:
  - script: |
      echo "Keys in myObject:"
      echo "Key1: ${{ parameters.myObject.key1 }}"
      echo "Key2: ${{ parameters.myObject.key2 }}"
      echo "Key3: ${{ parameters.myObject.key3 }}"
    displayName: 'Display object keys and values'

Parametri obbligatori

Le pipeline segnalano automaticamente un errore se manca un parametro. È possibile aggiungere un passaggio di convalida all'inizio del modello per verificare la presenza dei parametri necessari ed eseguire un'azione appropriata.

Di seguito è riportato un esempio che verifica la presenza del solution parametro usando Bash:

# File: steps/msbuild.yml

parameters:
- name: 'solution'
  default: ''
  type: string

steps:
- bash: |
    if [ -z "$SOLUTION" ]; then
      echo "##vso[task.logissue type=error;]Missing template parameter \"solution\""
      echo "##vso[task.complete result=Failed;]"
    fi
  env:
    SOLUTION: ${{ parameters.solution }}
  displayName: Check for required parameters
- task: msbuild@1
  inputs:
    solution: ${{ parameters.solution }}
- task: vstest@2
  inputs:
    solution: ${{ parameters.solution }}

Per indicare che il modello ha esito negativo se manca il parametro obbligatorio:

# File: azure-pipelines.yml

# This will fail since it doesn't set the "solution" parameter to anything,
# so the template will use its default of an empty string
steps:
- template: steps/msbuild.yml