'How to do a simple string token replacement in Azure pipelines?
In a YAML release pipeline, I need to do a simple replacement in the js files contained in the artifact coming from another pipeline. These files have a certain token (#TOKEN_URL#) that must be replaced in an Angular js bundled file.
The release has the following parameter that will determine the value to replace:
parameters:
- name: environment
displayName: Environment
type: string
default: staging
values:
- staging
- production
And also have the following variables:
variables:
tokenUrl: '#TOKEN_URL#'
tokenUrlValueProd: 'https://www.xxxx.com'
tokenUrlValueTest: 'https://www.test-xxxx.com'
tokenUrl is the token to search in different JS and JSON files. The idea is to replace the '#TOKEN_URL#' whenever it appears with tokenUrlValueProd or tokenUrlValueTest, depending on the parameters.environment value.
I have found the tasks ReplaceTokens@1 and FileTransform@1 for replacements, but, in both cases, I don't see where to tell the token to search nor the values to put instead of the token.
Is there a simple way to do this?
Solution 1:[1]
It was a lot of trial and error until I could find a way. The selected answer in this link was also of great help, I had to check closely in the screenshots.
The documentation was not clear enough to me. I finally used ReplaceTokens@1 which works pretty similar to FileTransform@1, but it works obviously for tokens, while FileTransform@1 works for a certain structure in JSON and XML files.
First, I have a file with some tokens to be replaced:
//Code fragment:
urlServices: {
urlServicesPayment: '#{tokenUrl}#/getSession',
},
Initially it was something like '#TOKEN_URL#'. Then, to match the PascalCase in the Yaml variable names, I changed to: '#{TokenUrl}#'.
In my case, I have diferent values for test and prod, so I needed a setup like this:
variables: ##Job variables
${{ if eq(parameters.environment, 'production') }}:
tokenUrl: 'https://www.xxxx.com'
${{ if eq(parameters.environment, 'test') }}:
tokenUrl: 'https://www.test-xxxx.com)'
And the replacement task is just:
- task: ReplaceTokens@1
inputs:
sourcePath: '$(Pipeline.Workspace)/dist'
filePattern: '*.js'
tokenRegex: '#{(\w+)}#'
- SourcePath is the path containing the files to transform
- FilePattern is a wildcard to process one or many files
- TokenRegex is the regex pattern to find the tokens that have names like my variables.
In this case '#{(\w+)}#' matches with '#{TokenUrl}#' and TokenUrl is the pipeline variable containing the value to replace. So, '#{TokenUrl}#' will become 'https://www.xxxx.com' inside the transformed file
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 |
