skip to Main Content

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.

2

Answers


  1. Chosen as BEST ANSWER

    You can do this with FileTransform

    1. Create a file, variables.json

       {
           "buildNumber": ""
       }
      
    2. Import into your environment file/s

      import variables from '../../variables.json';
      export const environment = {
      buildNumber: variables.buildNumber,    ...
      
    3. 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'
      

  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search