DEV Community

Sanjeevi Subramani
Sanjeevi Subramani

Posted on • Originally published at lkgforit.com on

File Transform Variable Substitution using replace token task in Azure Devops

File transform using replace token Azure Devops extension, below is the link for the extension which we are going to use in this article.

https://marketplace.visualstudio.com/items?itemName=qetza.replacetokens

Another article with default File Transform task is available here.

https://lkgforit.com/file-transformation-variable-substitution-and-issues-faced-in-azure-devops-yaml-3556a92de0b2

Let's go into how we are going to use this replace token extension task in Azure Devops for variable substitution.

Below is the sample code to substitute variables from pipeline into the file where the start of end of tag/token is passed and it takes the middle content as name of pipeline variable to replace in the file with variable value in that place.

Here in this example, we are using "{#" and "#}" as tokenPrefix and tokenSuffix respectively.

In the file wherever a content starts with this prefix and ends with end token suffix then the text is replaced with the value of a variable with same text as name.

    - task: replacetokens@3
      inputs:
        targetFiles: "$(Pipeline.Workspace)/codepath/jsonFileName.json"
        encoding: "auto"
        writeBOM: true
        verbosity: "detailed"
        actionOnMissing: "warn"
        keepToken: false
        tokenPrefix: "{#"
        tokenSuffix: "#}"
      displayName: Perform variable substitution in json file

Enter fullscreen mode Exit fullscreen mode

if we pass the below json file as input then it will replace pipeline variable values of variable1 and variable2 inside the tag.

{
  "headtag": "ens",
  "modelName": {
    "textProp": {
      "language": [
        {
          "property1": "{#Variable1#}",
          "property2": "{#Variable2#}"
        }
      ]
    }

Enter fullscreen mode Exit fullscreen mode

For example, consider the below are variables used.

variables:
  variable1: "value1"  
  variable2: "value2"

Enter fullscreen mode Exit fullscreen mode

then the output json file will be like below:

{
  "headtag": "ens",
  "modelName": {
    "textProp": {
      "language": [
        {
          "property1": "value1",
          "property2": "value2"
        }
      ]
    }

Enter fullscreen mode Exit fullscreen mode

Thanks.

Refer videos in my channel for live explanations.

https://youtu.be/_iPfzH3ENAk

https://youtu.be/QxJ_y6pV6No

https://youtu.be/dGLWBWZavhw

https://youtu.be/C8t4EUV6yok

YouTube Channel

https://www.youtube.com/channel/UCnYzqHl_und412jN2RTjJVA

Top comments (0)