Auto merge using git commands in Azure .yml pipeline

780 views Asked by At

I have a requirement to automate the merge through azure pipeline upon deployment is complete.
For example : I have a branch - 'release/1.0.0' which is used for the deployment, post deployment this branch needs to be auto merged into main branch without any pull request.

I'm using a bash task to execute the git commands as below:

- ${{ if startsWith(variables['Build.SourceBranch'], 'refs/heads/release/') }}:
  - task: Bash@3
    displayName: "Auto merge release"
    name: "Auto_merge"
    inputs:
      targetType: "inline"
      script: |
        git config --global user.name "AzureDevOps Agent"
        git config --global user.email "[email protected]" 
        git checkout origin/main
        git fetch
        git merge --ff $(Build.SourceBranchName)
        git push origin

Here is the error in azure pipeline:

error in azure pipeline

Can you please help me fix this ?

Note: I don't want to create any pull request to handle the auto merge, just not to clutter the Pull requests in ADO.
I want to achieve this through git merge without any pull request

2

There are 2 answers

3
VonC On

Regarding git merge, there is an option --ff, but not -ff.

With --ff, when possible resolve the merge as a fast-forward (only update the branch pointer to match the merged branch; do not create a merge commit). When not possible (when the merged-in history is not a descendant of the current history), create a merge commit.

Make sure to use the right syntax.

2
Bowman Zhu-MSFT On

Vonc's answer is already to solve your first issue.

And I write a YAML with related scripts to achieve your requirements(without PR):

trigger:
- none

pool:
  vmImage: ubuntu-latest


variables: #Define variables here.
 personal_access_token: xxx
 organization_name: xxx
 project_name: xxx


steps:
- checkout: self
  persistCredentials: true
  
- ${{ if startsWith(variables['Build.SourceBranch'], 'refs/heads/release/') }}:

  - script: echo This is release.
    displayName: 'Release Task'
  - task: Bash@3
    displayName: auto_merge
    inputs:
      targetType: 'inline'
      script: |
        git clone https://$(personal_access_token)@dev.azure.com/$(organization_name)/$(project_name)/_git/$(Build.Repository.Name)
        cd $(Build.Repository.Name)
        str=$(Build.SourceBranch)
        #get the value after the "refs/heads/" string
        branch_name=${str#refs/heads/}
        echo $branch_name
        merge_branch="origin/"$branch_name
        echo $merge_branch
        git fetch origin main
        git merge --ff $merge_branch
        git push

I works fine on my side:

enter image description here