I want to reference Azure CI Build.BuildNumber variable in my Angular app, but need a way to inject the build number into the environment file.
I have tried referencing the Azure environment variables but these are not replaced automatically on build.
CodePudding user response:
You can do this with FileTransform
Create a file, variables.json
{ "buildNumber": "" }
Import into your environment file/s
import variables from '../../variables.json'; export const environment = { buildNumber: variables.buildNumber, ...
In your pipeline YML file:
variables: - name: buildNumber value: '$(Build.BuildNumber)' ... steps: ... - task: FileTransform@1 displayName: 'Update Version Number' inputs: folderPath: '**/my-app-name' fileType: 'json' targetFiles: 'variables.json'
CodePudding user response:
I would recommend to use replaceToken task https://marketplace.visualstudio.com/items?itemName=qetza.replacetokens to do the magic.
trigger:
- none
variables:
buildNumber: '$(Build.BuildNumber)'
- task: replacetokens@5
inputs:
rootDirectory: '$(Pipeline.Workspace)/s/MyProjectDirectory/'
targetFiles: '**/environment.ts'
encoding: 'auto'
tokenPattern: 'custom'
tokenPrefix: '${'
tokenSuffix: '}'
writeBOM: true
verbosity: 'detailed'
actionOnMissing: 'fail'
keepToken: false
actionOnNoFiles: 'continue'
enableTransforms: false
enableRecursion: false
useLegacyPattern: false
enableTelemetry: true
Create environment.ts file with conten.
{
"buildNumber": "${buildNumber}"
}
How this works? Pipeline variables that you have defined inside variables section will pick up buildNumber as pipeline variables. Now in replaceToken task, it will check for target file that is in our case environment.ts file and token prefix/suffix that in our case defined as ${}. When in replacetoken task, it will replace all variables that are encapsulated inside ${} prefix/suffix that is ${buildNumber} in our case. A similar case is also discussed here Best way to change a docker image tag in a azure pipeline with kubernetes