やりたいこと
.Net Core MVCで環境ごとのappsetting.json(appsetting.env.json)を利用するために環境変数を設定したい。
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true).AddEnvironmentVariables();
{env.EnvironmentName}は環境変数ASPNETCORE_ENVIRONMENTの値を参照します。
やり方
ServiceManifest.xmlの設定
Web系プロジェクトのServiceManifest.xmlを開きます。(~/PackageRoot/ServiceManifest.xml)
CodePackageに下記のようにEnvironmentVariablesを追記します。
<CodePackage Name="Code" Version="1.0.0">
<EntryPoint>
<ExeHost>
<Program>Hoge.Web.exe</Program>
<WorkingFolder>CodePackage</WorkingFolder>
</ExeHost>
</EntryPoint>
<EnvironmentVariables>
<EnvironmentVariable Name="ASPNETCORE_ENVIRONMENT" Value="" />
</EnvironmentVariables>
</CodePackage>
ApplicationManifest.xmlの設定
ServiceFabricプロジェクトのApplicationManifest.xmlを開きます。(~/ApplicationPackageRoot/ApplicationManifest.xml)
Parametersに環境変数設定用のprameterを追記します。
Nameは任意(例ではAspNetCoreEnvironment)、DefaultValueは開発環境に設定したいためDevelopmentとします。
<Parameters>
<Parameter Name="AspNetCoreEnvironment" DefaultValue="Development" />
</Parameters>
環境変数を設定するサービスのServiceManifestImport設定に環境変数を先ほど設定したparamでoverrideする設定を追記します。
Valueの部分は"[]"も必要です
<ServiceManifestImport>
<ServiceManifestRef ServiceManifestName="Hoge.WebPkg" ServiceManifestVersion="1.0.0" />
<ConfigOverrides />
<EnvironmentOverrides CodePackageRef="Code">
<EnvironmentVariable Name="ASPNETCORE_ENVIRONMENT" Value="[AspNetCoreEnvironment]" />
</EnvironmentOverrides>
</ServiceManifestImport>
Staging環境用のデプロイ定義の作成
今回は例としてStaging環境用の定義を作成します。
Staging用ApplicationParametersの作成
ApplicationParametersのCloud.xmlをコピーし同じディレクトリにCloud.Staging.xmlを追加します。(~/ApplicationParameters/Cloud.Staging.xml)
Cloud.Staging.xmlにAspNetCoreEnvironmentのParameterを追記します。
Parameter Nameは先ほどのApplicationManifestで追記したものと同じにしてください。
<Parameters>
<Parameter Name="AspNetCoreEnvironment" Value="Staging" />
</Parameters>
Staging用PublishProfilesの作成
PublishProfilesのCloud.xmlをコピーし同じディレクトリにCloud.Staging.xmlを追加します。(~/PublishProfiles/Cloud.Staging.xml)
参照しているApplicationParameterFileをStagingのものに変更します。
<ApplicationParameterFile Path="..\ApplicationParameters\Cloud.Staging.xml" />
デプロイ
Staging環境デプロイ時に作成した~/PublishProfiles/Cloud.Staging.xmlを指定することで
環境変数ASPNETCORE_ENVIRONMENTにStagingが設定されます。