Set git credentials inside a Azure yaml pipeline

Viewed 3892

I'm writing an Azure YAML pipeline which have to do a 'git push' to repo so, I've written my git commands inside a CmdLine@2 task. Something like this :

            git checkout -b foo-branch-$(Build.BuildId)
            
            git add myGeneratedFile

            git commit -m "My commit message"

            git config user.email "$(GitUserName)@foo.com"
            git config user.name "$(GitUserName)"

            git push --set-upstream origin feature/foo-branch-$(Build.BuildId)

Obviously this code doesn't work as git credentials aren't set anywhere. How can specify that commands?

My idea is reading them from a parameter just like $(GitUserName) or from a git secret.

Is there any parameter that I can hide to avoid showing the value in the log and when the user type it?

1 Answers

Based on your latest commnet, the option Allow scripts to access the OAuth token only exists in classic editor.

In Yaml pipeline, you could use the following command:

- checkout: self
  persistCredentials: true

The persistCredentials will leave the OAuth token in the Git config after the initial fetch.

Here is the example:

steps:
- checkout: self
  persistCredentials: true

- script: |
   git config --global user.email "email"
   git config --global user.name "Kevin Lu"
   
   
   
   git checkout -b master
   
   git add .
   
   git commit -m "My commit message"
   
    git push origin HEAD:master
   
  displayName: 'Command Line Script'

For more detailed info, you could refer to this doc.

Update2:

To solve this permission issue, you need to grant the Contributor permission to the service account: Projectname Build Service(OrganizationName) in Project Settings -> Repositories -> Target Repo -> Permission.

enter image description here

Update3:

enter image description here

Related