azure-devopsazure-pipelines-yamlazure-devops-rest-api

Create Pull Request on user's behalf from an Azure DevOps Pipeline


I have the following code when creating a branch/commit in a pipeline. I'm using the $(Build.RequestedFor) and $(Build.RequestedForEmail) so that when I push the commit to the repo it shows as the requesting user.

- pwsh: |
    $message = "create {0} from template" -f $env:PIPELINENAME
    $branchName = "feature/{0}" -f $env:PIPELINENAME

    git config --global user.email $env:REQUESTEDFOREMAIL
    git config --global user.name $env:REQUESTEDFOR

    git checkout -b $branchName
    git add .
    git commit -m $message
    git push -u origin HEAD
  displayName: 'create and push branch'
  env:
    PIPELINENAME: $(pipelineName)
    REQUESTEDFOREMAIL: $(Build.RequestedForEmail)
    REQUESTEDFOR: $(Build.RequestedFor)

I have a subsequent step to create a pull request using the following:

- pwsh: |
    $title = "Experiment {0}" -f $env:PIPELINENAME
    $branchName = "feature/{0}" -f $env:PIPELINENAME

    write-host "Creating PR: '$title' for branch '$branchName'"

    az repos pr create `
       --title $title `
       --source-branch $branchName `
       --repository $env:REPOSITORY
  displayName: 'Create pull request'
  env:
    AZURE_DEVOPS_EXT_PAT: $(System.AccessToken)
    REPOSITORY: $(Build.Repository.Name)
    PIPELINENAME: $(pipelineName)
    PIPELINEFULLPATH: $(pipelineFullPath)

This all works great.

However, when the pull request is created it shows that it was created by the Pipeline Agent.

Pull Request created by...

My main concern is that when I look at the Repos > PullRequests, the Pull Request doesn't show in the "Mine" tab, and I have to dig through the "Active" tab to find it.

Is there a way that I can specify who created the pull request programmatically, or alter the Pull Request so that it shows on the "Mine" tab?


Solution

  • The az cli does not support an option to create the pull request on another user's behalf. However, by adding the $(Build.RequestedForEmail) as a required-reviewer the Pull Request will show up on the Mine tab of the pull requests.

    - pwsh: |
        $title = "Experiment {0}" -f $env:PIPELINENAME
        $branchName = "feature/{0}" -f $env:PIPELINENAME
    
        write-host "Creating PR: '$title' for branch '$branchName'"
    
        az repos pr create `
           --title $title `
           --source-branch $branchName `
           --repository $env:REPOSITORY `
           --required-reviewers $env:REQUESTEDFOREMAIL `
    
      displayName: 'Create pull request'
      env:
        AZURE_DEVOPS_EXT_PAT: $(System.AccessToken)
        REPOSITORY: $(Build.Repository.Name)
        REQUESTEDFOREMAIL: $(Build.RequestedForEmail)
        PIPELINENAME: $(pipelineName)
        PIPELINEFULLPATH: $(pipelineFullPath)