Rename and Replace Placeholder Task in Azure DevOps CI pipeline

2.4k views Asked by At

I searched it, but I am not able to find any out-of-the-box task for a build pipeline of AzureDevOps to perform the following tasks;

  • file rename (in my case it's a Javascript file)
  • replace placeholder like the following: #placeholder# inside the renamed .js file

Is there something available out-of-the box to perform this tasks?

enter image description here

1

There are 1 answers

9
Krzysztof Madej On

For first part you can call simply from powershell/script task and rename-item:

Rename-Item -Path "daily_file.txt" -NewName "monday_file.txt"

Or mv command and bash task.

For the second part you may use Token replace extension

so let's say you have file create-container-instance.sh

az container create -g TheCodeManual --name myapp1 --image #{Image}

and in yaml

- task: replacetokens@3
  inputs:
    targetFiles: 'stackoverflow/12-container-instance/create-container-instance.sh'
    encoding: 'auto'
    writeBOM: true
    actionOnMissing: 'warn'
    keepToken: false
    tokenPrefix: '#{'
    tokenSuffix: '}#'
    useLegacyPattern: false
    enableTelemetry: true

and for that token #{Image}# is replaced by Image variable.

This is my pipeline:

enter image description here

Task group has task fro replacing tokens.

Here is variable declaration:

enter image description here

and token was replaced as expected:

enter image description here

If you want to use powershell to replace tokens you can try this

function Replace-Tokens
{
  param(
        [string]$inputFile,
        [string]$outputFile,
        [string]$token,
        [string]$tokenValue
    )

    (Get-Content $inputFile) | foreach-object { $_ -replace $token, $tokenValue } | Set-Content $outputFile
    Write-Host "Processed: " + $inputFile
}

All credit goes to Tim Hobson