Search code examples
azure-pipelines

How can I make replacetokens@5 work in an Azure Devops pipeline?


I have to use the replacetokens@5 task to perform a substitution in a yaml file and was unable to make it work. I've created this test case for it, as I can't share my original code and data due to an NDA.

contents of AzurePipelines/Replace.txt:

test file
${REPLACE}

variables and task in the pipeline:

variables:
    - name: REPLACE
        value: 'XYZ'
steps:
    - task: replacetokens@5
        inputs:
            targetFiles: 'AzurePipelines/Replace.txt'
            encoding: 'auto'
            tokenPrefix: '${'
            tokenSuffix: '}'
            writeBOM: true
            verbosity: 'detailed'
            actionOnMissing: 'fail'
            keepToken: true
            actionOnNoFiles: 'fail'
            enableTransforms: false
            enableRecursion: false
            useLegacyPattern: false
            enableTelemetry: false

According to what I read on the internet on what Rider AI assistant told me, it should substitute variables that are defined in the pipeline. It doesn't do anything, altho it tells me that it found the files successfully and performed 0 substitutions. I also tried to define the variables inline in the task, that doesn't substitute the variables either. I also tried to use the 'default' token pattern and the ${} preset, none of those changes made a difference in the outcome.

Is there something wrong in my task or why doesn't it substitute?


Solution

  • You missed the field "tokenPattern: 'custom'" on the task. The correct configurations should looks like below.

    steps:
    - task: replacetokens@5
      displayName: 'Replace Tokens'
      inputs:
        targetFiles: 'AzurePipelines/Replace.txt'
        encoding: 'auto'
        tokenPattern: 'custom'
        tokenPrefix: '${'
        tokenSuffix: '}'
        writeBOM: true
        verbosity: 'detailed'
        actionOnMissing: 'fail'
        keepToken: true
        actionOnNoFiles: 'fail'
        enableTransforms: false
        enableRecursion: false
        useLegacyPattern: false
        enableTelemetry: false
    

    In addition, this task has a latest version replacetokens@6, you can use the v6 version task like as below. It also can work as expected.

    steps:
    - task: replacetokens@6
      displayName: 'Replace Tokens'
      inputs:
        sources: 'AzurePipelines/Replace.txt'
        tokenPattern: 'custom'
        tokenPrefix: '${'
        tokenSuffix: '}'
        addBOM: true
        missingVarAction: 'keep'
        missingVarLog: 'error'
        ifNoFilesFound: 'error'