0

Scenerio is that:

  1. We have Azure DevOps and we can run a pipeline into one of x number of named environments enter image description here

  2. We make use of Azure App Configuration, and labels for the values for each environment. So for each setting, it might have a different value depending on the label

enter image description here

It occurs to me that if i match up the label to the same as the names of the environments, then in code, when i get the config value, if I can somehow determine what environment I've been deployed to (speaking from the code's point of view) then i can just pass this variable when getting the app config and i will have the correct config settings for my environment.

            var environment = // HERE find my deployed to environment as in pipeline (1.)
        var credentials = new DefaultAzureCredential();


            configurationBuild.AddAzureAppConfiguration(options =>
            {
                options.Connect(settings.GetValue<string>("ConnectionStrings:AppConfig"))
                        .Select(KeyFilter.Any, LabelFilter.Null)
                        .Select(KeyFilter.Any, labelFilter: environment);
            });

I was thinking that the solution would be something of the form of setting the environment in the azure-pipelines.yaml where the pipeline somehow knows the choice of environment and then reading it in code back out of the environment variable. but i dont know how to do that, or if there is a better way to do it? Thanks in advance for any help offered.

JML
  • 382
  • 7
  • 18

1 Answers1

1

You can use the pipeline variables to pass the environment value to your code. The pipeline variables you defined in azure-pipelines.yaml will get injected as environment variables for your platform, which allows you to get their values in your code using Environment.GetEnvironmentVariable().

So you can define a pipeline variable in the azure-pipelines.yaml like below example(ie.DeployEnv):

parameters:
- name: Environment
  displayName: Deploy to environment
  type: string
  values:
  - none
  - test
  - dev

variables:
  DeployEnv: ${{parameters.Environment}}

trigger: none

pool:
  vmImage: 'windows-latest'

Then you can get the pipeline variable (ie.DeployEnv) in you code like below:

 using System;

 var environment = Environment.GetEnvironmentVariable("DeployEnv");
 
 var credentials = new DefaultAzureCredential();
 ....

Another workaround is to define an environment property in the config(eg.web.config) file. And you can read the environment property in your code. In the pipeline you need to add tasks to replace the value of the environment property in the config file. See this thread for more information.

Levi Lu-MSFT
  • 27,483
  • 2
  • 31
  • 43
  • thank you so much for answering. small point i think the yaml variable declaration should be: variables: - name: DeployEnv - value: ${{parameters.Environment}} is that correct? thanks. – JML Jan 27 '21 at 09:17