Search code examples
pythonazureazure-devopsazure-pipelinesazure-pipelines-yaml

How do I push a pipeline variable to an azure repo?


I have an Azure pipeline that runs a Python script. This script makes an API call that returns a json. Here are the last few lines of the script:

r = s.get(api_get_dashboard_by_uid + targetDashboardUid)

# set name of the variable
name = 'myJson'
# set value of the variable
value = r.json()

print(f'##vso[task.setvariable variable={name};]{value}')

my pipeline's yaml file looks like this:


- task: PythonScript@0
  inputs:
    scriptSource: 'filePath'
    scriptPath: '$(System.DefaultWorkingDirectory)/myTestPythonFile.py'

- bash: echo $(myJson)

the last line prints out the json, but I'm interested in storing it (indefinitely). I believe pushing it to an azure repo is an option, but I just can't make sense of the documentation / SO questions. Could anyone tell me what I need to replace - bash: echo $(myJson) with for my json to be stored in my project's repo? Thanks.


Solution

  • You can output the json value into a .json file, and then push this file into the git repository using related git CLI.

    In the Python script.

    . . .
    value = r.json()
    
    
    # Serializing json
    json_object = json.loads(value)
    json_formatted_str = json.dumps(json_object, indent=2)
    
    # Writing to myJson.json
    with open("myJson.json", "w") as outfile:
        outfile.write(json_formatted_str)
    

    In the pipeline, use the bash task to push the json file to Azure Git repos.

    steps:
    - bash: |
       git config --global user.name {username}
       git config --global user.email {email}
       
       git add myJson.json
       git commit -m "Add file myJson.json"
       git push
      displayName: 'Push json file to repo'