azure-devopsazure-pipelinesazure-yaml-pipelines

Use output of a bash command as parameter input of a job template in Azure DevOps pipeline


There is a job template (externally managed). I want to use this template in my pipeline. I have to provide a number of parameters for this template to work. I would like to dynamically generate the value for one of these parameters, namely a password.

I thought of using pwgen for this like so:

  jobs:
    - job: generate_key_password
      steps:
        - bash: |
            set -e
            echo "Installing pwgen"
            sudo apt install pwgen && echo "Successfully installed pwgen"
            pw=$(pwgen -y -s 25 1)
          displayName: Installing pwgen

I then would like to use the output of this step in a template:

- template: /x/y/z/a-template.yml@some-repo
  parameters:
    theParameterName: <this should be the password I generated>

I have used vso in the past to pass on variables from one job to another, but this doesn't seem to be possible in the context of my task (I cannot set dependsOn). Is there any straightforward strategy to pass on the variable and use it in a subsequent template job or not?

Tied together, it would look like this:

stages:
  - stage: the_stage
    jobs:
      - job: generate_key_password
        steps:
          - bash: |
              set -e
              echo "Installing pwgen"
              sudo apt install pwgen && echo "Successfully installed pwgen"
              pw=$(pwgen -y -s 25 1)
            displayName: Installing pwgen
      - template: /x/y/z/a-template.yml@some-repo
        parameters:
          theParameterName: <this should be the password I generated>

Solution

  • If you can set dependsOn on stage level, you can transfer the variable to next stage. Please refer to my sample below:

    main.yml:

    trigger: none
    
    pool:
      vmImage: ubuntu-latest
    
    stages:
    - stage: One
      jobs:
      - job: A
        steps:
          - bash: echo "##vso[task.setvariable variable=MyVar;isOutput=true]testpwd"
            name: ProduceVar
    
    - stage: Two
      dependsOn: One
      variables:
        varFromA: $[ stageDependencies.One.A.outputs['ProduceVar.MyVar'] ]
      jobs:
        - template: template4.yml
          parameters:
            pwd: $(varFromA)
    

    template4.yml

    parameters:
      - name: pwd
        type: string
    
    jobs:
    - job: job2
      steps:
      - script: echo ${{ parameters.pwd}}
    

    The execution result:

    enter image description here

    Or you can consider to put the template in a new pipeline. You can generate the password in 1st pipeline, use rest api Runs - Run Pipeline to trigger the 2nd build pipeline, and set the parameter to 2nd pipeline for template parameter.

    You can find the sample in my answer here.