Fatal: Could not read password for 'https://[email protected]': terminal prompts disabled
S

7

29

I'm trying to merge the develop branch to the master branch when building with Azure Pipelines PowerShell task.

But while executing the command git push, I'm getting this error:

Fatal: Could not read password for 'https://[email protected]': terminal prompts disabled

The code repository is "Azure Repos Git".

git checkout -b master
git config --global user.email "[email protected]"
git config --global user.name "xxxxx"
git merge origin/develop 
git push origin master

After referring some URLs, I've created the Personal Access Token, and modified the push command as git push https://[email protected]/OrganizationName, but it's still not working.

Please let me know, if you find a solution for this issue.

Scrogan answered 24/6, 2019 at 9:45 Comment(3)
PAT is your solution, what is "it also not worked"? what you got?Homoeo
Got the error as "fatal: unable to update url base from redirection:"Scrogan
You need to append the team project and the git repo in the urlHomoeo
H
31

As you mentioned you need to use PAT but in this way:

git push https://{PAT}@dev.azure.com/{organization}/{project}/_git/{repo-name}

Another solution is to "Allow scripts to access the OAuth token" in the job options:

photo

In the git push use the System.AccessToken:

git push https://$env:[email protected]/......

And give push permissions to the build user (in the repo settings):

enter image description here

Homoeo answered 24/6, 2019 at 10:8 Comment(6)
For .yaml build pipelines (currently the default for Azure Pipelines), set the persistCredentials: true. See the Checkout options.Votary
there is nocontribute permission in Azure today, what could be an alternate permission ?Joab
I can see the Contribute permissions today..Homoeo
In bash pass the _SYSTEM_ACCESSTOKEN to the script as environment variable env: SYSTEM_ACCESSTOKEN: $(System.AccessToken) and use it inside the script without the $env prefix, git ls-remote --exit-code --heads https://[email protected]/<company>/<teamProject>/_git/<repository> refs/heads/<branch>. That worked for me.Carrington
It worked for me with minor chages while using Bash: git push https://$(System.AccessToken)@dev.azure.com/[...]Viaticum
Great answer - using the PAT worked for me (Classic pipeline).Relume
D
10

Add checkout as the first step:


steps:
- checkout: self
  persistCredentials: true

Make sure you set the git config

git config --global user.email "[email protected]"
git config --global user.name "Your Name"

Make sure to Grant version control permissions to the build service.

  1. Go to project settings --> Repositories menu --> Your repository --> Security tab, and grant the following permissions to the Project Collection Build Service ({your organization}) identity:
  • Create branch: Allow
  • Contribute: Allow
  • Read: Allow
  • Create tag: Allow

You should now be able to use git commands without having to manually append the access token to any git commands.

More info see here: https://learn.microsoft.com/en-us/azure/devops/pipelines/scripts/git-commands?view=azure-devops&tabs=yaml

Disorganize answered 6/6, 2022 at 21:20 Comment(1)
This answer need more upvote! thxVespasian
K
2
# Node.js
# Build a general Node.js project with npm.
# Add steps that analyze code, save build artifacts, deploy, and more:
# https://learn.microsoft.com/azure/devops/pipelines/languages/javascript

trigger:
  - master
  - your-branch-name-here

pr: none

pool:
  vmImage: "macos-latest"

jobs:
  - job: Perform_Commit_From_CI
    steps:
      - checkout: self
        persistCredentials: true #Important - Persist creds to run further git command
        clean: true
      - task: NodeTool@0
        inputs:
          versionSpec: "16.13.2"
        displayName: "Install Node.js"
      - script: |
          git config --global user.email [email protected]
          git config --global user.name "Test User"
        displayName: Configure git
      - script: |
          yarn install
          yarn start NAME_OF_THE_SCRIPT_YOU_WANT_TO_EXECUTE
          git add -A
          git commit -m 'Test commit [skip ci]'
          git push origin HEAD:your-branch-name-here 
        displayName: "Test Script"

This will work without PAT.

Kimbell answered 12/6, 2022 at 6:58 Comment(1)
Something that is important to note with this example is the [skip ci] part in the commit message. This will prevent the CI from triggering on the same branch with your pushCurtain
U
1

Similar to Shayki's answer, but if you are not running a powershell task use:

git push https://$(System.AccessToken)@dev.azure.com/......

I am notably using

  • classic pipelines
  • an onprem Windows build agent
    • Agent job settings has Allow scripts to access the OAuth token enabled
  • command line task
Unassuming answered 18/3, 2021 at 13:34 Comment(0)
C
0

An alternative to personal access tokens is to use a Git credential helper such as Git Credential Manager (included in Git for Windows) or git-credential-azure (included in several Linux distributions). Both support authentication to Azure Repos (dev.azure.com).

The first time you authenticate, the helper opens a browser window to Microsoft login. Subsequent authentication is non interactive.

Corrigan answered 3/8, 2023 at 16:50 Comment(0)
W
0

WORKS IN 2024
Azure DevOps Pipeline solution

@Kailash Uniyal does not have enough upvotes on their answer, nor @Newteq Developer on their comment.

First, you must allow your Build Service User the correct permissions:

  • Bypass policies when completing pull requests: Allow
  • Bypass policies when pushing: Allow
  • Contribute: Allow
  • Force push (rewrite history, delete branches and tags): Allow

Screenshot of aforementioned permissions for Build Service

Microsoft documentation for the checkout step accessing the system token

The clean: true config option for the checkout step is crucial if you are creating a git tag or doing anything that might persist. "Certain kinds of changes to the local repository aren't automatically cleaned up by the build pipeline"

This is the only approach that worked for me out of all of the answers provided in 2024. (YAML below is for a very basic custom script for incrementing semantic versioning based on merged PRs containing Conventional Commit messages).

trigger:
  - main

pool:
  vmImage: "ubuntu-latest"

jobs:
  - job: PreMergeValidation
    displayName: "Pre-Merge Validation"
    condition: and(succeeded(), eq(variables['Build.Reason'], 'PullRequest'))
    steps:
      - task: PowerShell@2
        inputs:
          targetType: "inline"
          script: |
            if ($env:SYSTEM_PULLREQUEST_PULLREQUESTID) {
              # PR Validation context
              $url = "$($env:SYSTEM_TEAMFOUNDATIONCOLLECTIONURI)$env:SYSTEM_TEAMPROJECTID/_apis/git/repositories/$($env:BUILD_REPOSITORY_ID)/pullRequests/$($env:SYSTEM_PULLREQUEST_PULLREQUESTID)?api-version=7.0"

              $headers = @{
                Authorization = "Bearer $($env:SYSTEM_ACCESSTOKEN)"
              }

              $pullRequestInfo = Invoke-RestMethod -Uri $url -Method 'GET' -ContentType 'application/json' -Headers $headers
              # Write-Host "Pull Request Info: $($pullRequestInfo | ConvertTo-Json -Depth 100)"

              $title = $pullRequestInfo.title
              Write-Host "PR Title: $title"

              # Regular expression for conventional commits
              $regex = "^(feat|fix|docs|style|refactor|perf|test|chore|build|ci|revert|BREAKING CHANGE)(\(.+\))?!?: .+"
              if ($title -notmatch $regex) {
                Write-Error "PR title does not follow Conventional Commit guidelines. Please ensure the title starts with one of the allowed types (e.g., feat, fix) followed by an optional scope and a colon."
                exit 1
              } else {
                Write-Host "PR title follows Conventional Commits format"
              }
            }
        env:
          SYSTEM_ACCESSTOKEN: $(System.AccessToken)
        displayName: "Validate PR Title against Conventional Commits"

  - job: PostMergeActions
    displayName: "Post-Merge Actions"
    condition: and(succeeded(), eq(variables['Build.SourceBranch'], 'refs/heads/main'))
    steps:
      - checkout: self
        persistCredentials: true #Important - Persist creds to run further git command
        clean: true #Important - Certain kinds of changes to the local repository aren't automatically cleaned up by the build pipeline
      - task: PowerShell@2
        inputs:
          targetType: "inline"
          script: |
            git config --global user.email "[email protected]"
            git config --global user.name "ADO pipeline"

            # Fetch the latest changes
            git fetch --all

            # Ensure the branch exists and switch to it
            git checkout main

            # Read and increment the version number
            $versionFilePath = "version.txt"
            $version = Get-Content $versionFilePath
            $versionParts = $version -split '\.'

            $major = [int]$versionParts[0]
            $minor = [int]$versionParts[1]
            $patch = [int]$versionParts[2]

            $commitMessage = git log -1 --pretty=%B
            Write-Host "Latest commit message: $commitMessage"

            if ($commitMessage -match "(?i)^Merged PR \d+: BREAKING CHANGE") {
                $major++
                $minor = 0
                $patch = 0
            } elseif ($commitMessage -match "(?i)^Merged PR \d+: feat") {
                $minor++
                $patch = 0
            } else {
                $patch++
            }

            # Update the version number
            $newVersion = "$major.$minor.$patch"
            Set-Content -Path $versionFilePath -Value $newVersion
            Write-Host "Bumping version to $newVersion"

            # Commit and tag the new version
            git add $versionFilePath
            git commit -m "chore(release): bump version to $newVersion [skip ci]"
            # git tag -a "v$newVersion" -m "Release $newVersion"

            # Push changes and tags
            git push --follow-tags
        displayName: "Validate Commit Message and Bump Version"
Weeny answered 5/6 at 12:57 Comment(0)
O
-3

The issue might come up because the Azure Repository you are using is a Private one.

Changing the Project visibility to Public solved the issue.

Overtone answered 4/11, 2022 at 6:40 Comment(1)
security wise, this is a bad decision. You should rather fix the root cause instead of loosening up securityUnearth

© 2022 - 2024 — McMap. All rights reserved.