How to Create a Userstory from project 1 to project 2 in azure DevOps?

74 Views Asked by At

I have diff project in the same organization each team has his own project and i want to automate the creation of userstory from one project to another for exemple if i have Userstory X in Project 1 assigned to Team1 and i need the intervention of team 2 so we will create a new related userstory in project 1 . i want that new US to be created automatically in the project2 of the second team .

  • service hooks to trigger when the userstory is updated and become related to another UserStory
  • External Service Endpoints
2

There are 2 best solutions below

0
On

You can make use of below 2 Approaches to achieve your goal:-

Approach 1:- Azure CLI

Command:-

In this method you get a specific Work Item from source project and then use the output of the Get Work item to create new work item in another project

#make sure you login with your azure devops user account in the browser
az login

# Retrieve the details of an existing work item
$jsonoutput = az boards work-item show --id 93 --org https://dev.azure.com/sid24desai0738 

$jsonoutput

# Capture the output and use it to create a new work item
az boards work-item create --title "New Work Item1" --type "Task" --org https://dev.azure.com/sid24desai0738 --project "Agile" --description "Description of the new work item" --fields $jsonoutput.fields

Output:- Destination Project:-

enter image description here

Approach 2:- Rest API

You can make use of Get Work Item with Project Name parameter set to the source project name then call Create Work Item API to create new Work Item similar to previous Get Work Item fields.

Approach 2:-

Powershell script to Get Work Item:-

$PAT = "35b3vduxekw2xmfvq2kwvlghb2ysss2du5qtgboosfp3rov6klqa"
$OrgName = "sid24desai0738"
$ProjectName = "AzureDevops"
$ApiVersion = "7.0"
$type = "Task"

$services = Invoke-RestMethod -Uri "https://dev.azure.com/sid24desai0738/AzureDevops/_apis/wit/workitems/3?api-version=7.1-preview.3" -Method Get -Headers @{Authorization=("Basic {0}" -f [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$PAT")))}

$services

Output:-

enter image description here

Now use Create Work Item to create the Work Item from previous response:-

Sample Powershell code:-

# Set up authentication and project details
$PAT = "35b3xxxxxxx6klqa"
$OrgName = "sid24desai0738"
$ProjectName = "AzureDevops"
$ApiVersion = "7.0"

# Retrieve the original work item
$originalWorkItem = Invoke-RestMethod -Uri "https://dev.azure.com/$OrgName/$ProjectName/_apis/wit/workitems/3?api-version=$ApiVersion" -Method Get -Headers @{
    Authorization = "Basic " + [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(":$PAT"))
}

# Extract necessary fields from the original work item
$title = $originalWorkItem.fields.'System.Title'
$areaPath = $originalWorkItem.fields.'System.AreaPath'
$iterationPath = $originalWorkItem.fields.'System.IterationPath'
$workItemType = $originalWorkItem.fields.'System.WorkItemType'
$state = $originalWorkItem.fields.'System.State'
$assignedTo = $originalWorkItem.fields.'System.AssignedTo'

# Define new project and type for the new work item
$newProjectName = "AnotherProject"
$newType = "Task"

# Create a new work item payload using the extracted fields
$newWorkItemData = @{
    'System.Title' = $title
    'System.AreaPath' = $areaPath
    'System.IterationPath' = $iterationPath
    'System.WorkItemType' = $workItemType
    'System.State' = $state
    'System.AssignedTo' = $assignedTo
    # Add other fields as needed
} | ConvertTo-Json

$newWorkItemData

# Define API parameters for creating the new work item
$newWorkItemUrl = "https://dev.azure.com/sid24desai0738/AzureDevops/_apis/wit/workitems/$newType?api-version=$ApiVersion"

try {
    # Create the new work item in the specified project
    $newWorkItem = Invoke-RestMethod -Uri $newWorkItemUrl -Method Post -Headers @{
        Authorization = "Basic " + [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(":$PAT"))
        "Content-Type" = "application/json"
    } -Body $newWorkItemData -ErrorAction Stop

    Write-Output "New work item created successfully:"
    $newWorkItem
} catch {
    Write-Error "Error creating new work item: $_"
}

References:-

Work Items - Get Work Item - REST API (Azure DevOps Work Item Tracking) | Microsoft Learn

Work Items - Create - REST API (Azure DevOps Work Item Tracking) | Microsoft Learn

az boards work-item | Microsoft Learn

1
On

You can try to use the webhook based triggers to meet your demands with following configurations in project1:

  1. Go to "Project Settings" > "Service hooks" to create a web hook with the "Work item updated" event.

    enter image description here

    The request URL is with the format like as below.

    https://dev.azure.com/<ADO Organization>/_apis/public/distributedtask/webhooks/<WebHook Name>?api-version=6.0-preview
    

    For example: https://dev.azure.com/MyOrg/_apis/public/distributedtask/webhooks/UsAssignedToTeam1?api-version=6.0-preview

  2. Go to "Project Settings" > "Service connections" to create a new "Incoming Webhook" service connection. Ensure the WebHook Name is consistent with that in the request URL.

    enter image description here

  3. Set up a YAML pipeline like as below.

resources:
  webhooks:
  - webhook: UsAssignedToTeam1
    connection: UsAssignedToTeam1Connetion

stages:
- stage: A
  jobs:
  - job: A1
    steps:
    - checkout: none
    
    - task: Bash@3
      displayName: 'Create User Story'
      env:
        SYSTEM_ACCESSTOKEN: $(System.AccessToken)
      inputs:
        targetType: inline
        script: |
          echo "Get the details of the User Story assigned to Team1 in Project1:"
          workItemId=${{ parameters.UsAssignedToTeam1.resource.workItemId }}
          workItemUrl=${{ parameters.UsAssignedToTeam1.resource._links.parent.href }}
          echo "workItemId = $workItemId"
          echo "workItemUrl = $workItemUrl"

          echo "------------------------------------------"

          echo "Create a new User Story in Project2:"
          url="https://dev.azure.com/{organization}/{project}/_apis/wit/workitems/\$User%20Story?api-version=7.0"
          curl -X POST -u :$SYSTEM_ACCESSTOKEN $url \
          -H 'Content-Type: application/json-patch+json' \
          -d '[
                # Set the title of the new User Story.
                {
                  "op": "add",
                  "path": "/fields/System.Title",
                  "value": "New User Story in Project2 related to User Story ($workItemId) in project1"
                },
                # Set the Area Path of the new User Story. e.g.: Project2\\AreaTeam2\\SubArea
                {
                  "op": "add",
                  "path": "/fields/System.AreaPath",
                  "value": "{Area Path of Team2 in Project2}"
                },
                # Set the Iteration Path of the new User Story. e.g.: Project2\\Iteration2024\\SubIteration
                {
                  "op": "add",
                  "path": "/fields/System.IterationPath",
                  "value": "{Iteration Path in Project2}"
                },
                # Link the User Story in project1 as 'Related' on the new User Story.
                {
                  "op": "add",
                  "path": "/relations/-",
                  "value": {
                    "rel": "System.LinkTypes.Related",
                    "url": "$workItemUrl",
                    "attributes": {
                      "isLocked": false,
                      "name": "Related"
                    }
                  }
                }
              ]'

By this, when a User Story was assigned to the area path of Team1 in project1, it will trigger the web hook, then the web hook will trigger the YAML pipeline. The pipeline will call the RESI API "Work Items - Create" to create a new User Story in project2 and link the User Story in project1 as the "Related" type.

enter image description here