Configuring Auzre Service Fabric with Environment Variables
Configuring Azure Service Fabric applications was always a bit of a pain. I'm not entirely sure why, is this because of it's age? Or backward compatibility? But the truth is, editing XML files is not a joy. Although XSD Schema is provided not many text editors these days support it out of the box. Anyway, this is not what i'm tryint to say.
In addition to XML document, to read a configuration value you need to use Service Fabric specific API. To do that, you will typically access
ServiceContext passed into your stateful or stateless service, and the read configuration object. This is another step of convolution you need to deal with.
Unfortunately, we can't do anything with the problem of XML files, however we can make our life a little bit easier by forcing Fabric to set environment variables instead of internal confifuration values. There are a few steps involved in this, similar to the way you use normal settings:
ServiceManifest.xml and go under
CodePackage. Then add
EnvironmentVariables element under it, listing the variables your service will read.
<CodePackage Name="Code" Version="1.0.0"> <EntryPoint> <ExeHost> <Program>MyService.exe</Program> </ExeHost> </EntryPoint> <EnvironmentVariables> <EnvironmentVariable Name="MySetting" Value=""/> </EnvironmentVariables> </CodePackage>
Note that at this stage
Value tag is set to empty, this is important.
The second step is to add that parameter in
<Parameters> ... <Parameter Name="MySetting" DefaultValue="" /> ...
DefaultValue is set to empty, but you can set it to anything you want here, this value is used when none of the enrivonment files override it.
Now, in the same file, find your service under
ServiceManifestImport and override environment variable from a value from
Parameters section like this:
<ServiceManifestImport> <ServiceManifestRef ServiceManifestName="MyServicePkg" ServiceManifestVersion="1.0.0" /> <EnvironmentOverrides CodePackageRef="Code"> <EnvironmentVariable Name="MySetting" Value="[MySetting]" /> </EnvironmentOverrides> </ServiceManifestImport>
Depending on how you run your cluster you will have a file that contains values for that specific environment (by default VS creates
Local.1Node.xml etc.). To set the actual value for this variable you need to add it under
<Parameter Name="MySetting" Value="value in environment" />
Now to read these values from your service code you can use cross-platform API for working with environment variables. Or if you don't care about multiple platforms, this at least doesn't require an orchestrator specific dependencies.
To help you even further, you can use our LogMagic Environment Variables Provider.
Thanks for reading. If you would like to follow up with future posts please subscribe to our rss feed.
These are my courses you should definitely check out on Pluralsight: