'Create file automatically when repo is created in Azure Devops

Is it possible to automatically create a file when a repository is created?

For Example: Create 'Changelog.md'

Like 'Readme.md' is created with every repo.



Solution 1:[1]

Short answer: no, there is no option to setup a template repo or change the default template.

Solution 2:[2]

You can use rest api to create repos with predefined files:

  1. Create Repo
  2. Initial commit (Create a new branch)

PowerShell Script Example:

$user = ""
$token = "<pat>" #https://docs.microsoft.com/en-us/azure/devops/organizations/accounts/use-personal-access-tokens-to-authenticate

$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $user,$token)))
$orgUrl = "https://dev.azure.com/<org>"
$teamProject = "<TeamProjectName>"
$repoName = "NEW_REPO"

$restApiInitialCommit = "$orgUrl/$teamProject/_apis/git/repositories/$repoName/pushes?api-version=6.1-preview.2"
$restApiCreateRepo = "$orgUrl/$teamProject/_apis/git/repositories?api-version=7.1-preview.1"

$repoBody = "{`"name`": `"$repoName`"}"

$commitBody = @"
{
    "refUpdates": [
      {
        "name": "refs/heads/main",
        "oldObjectId": "0000000000000000000000000000000000000000"
      }
    ],
    "commits": [
      {
        "comment": "Updates file",
        "changes": [
          {
            "changeType": "add",
            "item": {
              "path": "/Changelog.md"
            },
            "newContent": {
              "content": "{newFileContentToUpdate}",
              "contentType": "rawtext"
            }
          }
        ]
      }
    ]
  }
"@

function InvokePostRequest ($PostUrl, $body)
{   
    return Invoke-RestMethod -Uri $PostUrl -Method Post -ContentType "application/json" -Headers @{Authorization=("Basic {0}" -f $base64AuthInfo)}  -Body $body
}

InvokePostRequest $restApiCreateRepo $repoBody

$fileContent = Get-Content -Path "C:/temp/Changelog.md" -Raw

$fileContentToCommit = $fileContent.Replace("\", "\\")
$fileContentToCommit = $fileContentToCommit.Replace("`"", "\`"")

$updateBody = $commitBody.Replace("{newFileContentToUpdate}", $fileContentToCommit);

InvokePostRequest $restApiInitialCommit $updateBody

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 jessehouwing
Solution 2 Shamrai Aleksander