Search code examples
jsonazure-devopsazure-pipelinesazure-repos

Passing values from json file to Azure pipeline variables


I have a pipeline in azure that is triggered by commit on specific folder in repository. In this folder there is a file.json with example values:

{
    "example": {
        "vaule1": "one",
        "vaule2": "two",
}
}

how can I pass those values to pipeline and set them as global variable or parameter

name: "test"

trigger: none

variables: 
  value1: ''
  value2: ''
  
jobs:

  - job: example_job
    displayName: 'example_job'
    condition: eq('${{ variables.value1}}', 'false')

    steps:
    - checkout: self

Solution

  • The global pipeline variables and parameters must be set before the pipeline has been triggered. It is not possible to set them during the run time.

    As a workaround, you can try like as below:

    1. Set a job as the very first job of your pipeline. And in this job, you can try to parse the Json file to get the values and set the values as output variables of the pipeline.

    2. Set other jobs to depend on the first job so that they can use the output variables generated in the first job.

    For more details, you can refer the document about "Output variables".

    Below is an example as reference.

    jobs:
    - job: A
      displayName: 'Job A'
      pool:
        vmImage: windows-latest
      steps:
      - task: Bash@3
        displayName: 'Get Json values and set output variables'
        name: setOutput
        inputs:
          targetType: inline
          script: |
    # Parse the Json file and get the values.
            vaule1=$(cat file.json | jq -r '.example.value1')
            vaule2=$(cat file.json | jq -r '.example.value2')
    # Set the values as output variables.
            echo "##vso[task.setvariable variable=vaule1;isoutput=true]$vaule1"
            echo "##vso[task.setvariable variable=vaule2;isoutput=true]$vaule2"
    
    - job: B
      displayName: 'Job B'
      dependsOn: A
      variables:
    # Map the output variables as job level variables. 
        vaule1: $[ dependencies.A.outputs['setOutput.vaule1'] ]
        vaule2: $[ dependencies.A.outputs['setOutput.vaule2'] ]
      pool:
        vmImage: windows-latest
      steps:
      - task: Bash@3
        displayName: 'Print variables'
        inputs:
          targetType: inline
          script: |
            echo "vaule1 = $(vaule1)"
            echo "vaule2 = $(vaule2)"
    

    enter image description here