How To Replace Tokens in Azure Pipelines Using ASP.NET Core

During the execution of the CI/CD process, the Replace Tokens extension in Azure DevOps can be used to replace tokens in the code files with variable values (which can be defined in the Pipelines Library). The setting for the Replace Tokens will be the main topic of this article.

 

Step 1 – Define tokens.

In the appsettings.json file, define the tokens as ‘#token name#’. You can look at the code below,

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "connection": "#{conString}#",
    "DataSource": "#{DataSourceValue}#",
    "InitialCataloge": "#{InitialCatalogeValue}#",
    "UserId": "#{UserIdValue}#",
    "Password": "#{PasswordValue}#"

  }
}

 

Step 2 – Set Variables in Azure DevOps

Go to the Azure DevOps site and create variable groups for the sets of variables. The variable group might be given based on the surroundings.

Navigation : Azure DevOps => Organization Page => Your Project => Pipelines => Library

Maintain consistency between the Variable’s name and the names of the tokens listed in appsettings.json. Fill out the values in the next input box, then save your changes. You can look at the image below.

 

Step 3 – Installing Replace token extension

Search for Replace Tokens in the marketplace or go there by clicking. Next, select “Get it free.”

 

 

Select your organization and click on “Install,”

 

Then you should see this page,

Your Azure DevOps environment has now been updated with the Replace Tokens extension. The extensions you have can be viewed by selecting “Organization Settings” > “Extensions”:

 

Step 4 – Replace tokens in Azure Pipelines

For the purpose of replacing tokens in Azure pipelines, the task is driven by YAML. You can use the YAML code below for that. The YAML provided operates as follows:

  • The program will be created.
  • The software will be compressed and included to the pipeline artifacts.
  • The extracted files will be placed in a folder.
  • The job called “replace tokens” will swap out the tokens.
  • Older files will be removed.
  • The updated files (with the updated token values) will be zipped.
  • The updated files will be released together with the updated token values.
  • The program will be installed on an App Service.

 

trigger:
- master

pool:
  vmImage: ubuntu-latest

variables:
  buildConfiguration: 'Release'
  azureSubscription: 'Put your azure subscrition here'

stages:

- stage: Build

  jobs:
  - job: build

    steps:

    - task: DotNetCoreCLI@2
      displayName: Build solution
      inputs:
        command: 'build'
        projects: '**/*.sln'
        arguments: '--configuration $(buildConfiguration)'

    # Publish
    - task: DotNetCoreCLI@2
      inputs:
        command: publish
        publishWebProjects: True
        arguments: '--configuration $(buildConfiguration) --output $(Build.ArtifactStagingDirectory)'
        zipAfterPublish: True

    # Pack the files and uploads them as an artifact of the build
    - task: PublishPipelineArtifact@1
      inputs:
        targetPath: '$(Build.ArtifactStagingDirectory)'
        artifact: 'replacetokensbackend'
        publishLocation: 'pipeline'

- stage: Development
  displayName: 'Deploy to Development'
  dependsOn: Build
  condition: succeeded()
  variables:
    - group: development

  jobs:
  - deployment: DeploymentDevelopment
    pool:
      vmImage: 'ubuntu-latest'
    environment: Development
    strategy:
      runOnce:
        deploy:
          steps:

          # Replace tokens
          - task: ExtractFiles@1
            inputs:
              archiveFilePatterns: '$(Pipeline.Workspace)/**/*.zip'
              destinationFolder: '$(Pipeline.Workspace)/application'
              cleanDestinationFolder: true
              overwriteExistingFiles: false

          - task: replacetokens@5
            inputs:
              targetFiles: '$(Pipeline.Workspace)/application/appsettings*.json'
              encoding: 'auto'
              tokenPattern: 'default'
              writeBOM: true
              actionOnMissing: 'warn'
              keepToken: false
              actionOnNoFiles: 'continue'
              enableTransforms: false
              enableRecursion: false
              useLegacyPattern: false
              enableTelemetry: true

          - task: DeleteFiles@1
            inputs:
              SourceFolder: '$(Pipeline.Workspace)/drop/'
              Contents: '*.zip'

          - task: ArchiveFiles@2
            inputs:
              rootFolderOrFile: '$(Pipeline.Workspace)/application/'
              includeRootFolder: false
              archiveType: 'zip'
              archiveFile: '$(Pipeline.Workspace)/drop/$(Build.BuildId).zip'
              replaceExistingArchive: true
          - task: AzureWebApp@1
            displayName: 'Deploy App Service'
            inputs:
              azureSubscription: $(azureSubscription)
              appType: 'webApp'
              appName: 'resource_name_here'
              package: '$(Pipeline.Workspace)/drop/*.zip'

 

Following the pipeline’s trigger, the tasks are executed sequentially, and the designated task replaces the provided tokens.

 

Conclusion
In this manner, we may substitute variables defined and kept in Azure DevOps for the values in appsettings.json. As a result, automating the procedure in accordance with the surroundings is simple.

Gratitude for reading!

 

 

 

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories