[英]Azure Environment Variables in Python Cloud Service
我有一个在Microsoft Azure上运行的Python云服务,当它在开发,登台和生产中运行时,应该使用其他存储帐户(用于Blob存储和队列)。
我宁愿不对存储帐户凭据进行硬编码,而是从环境中获取它们。 另外,我想要一个环境变量或一些表明我是在演出还是生产中的东西。 当我尝试print(os.environ)
我看不到任何蔚蓝的存储凭据,也看不到指示暂存或生产的值。
有什么办法可以做到这一点?
我正在回答自己的问题,因为我已经使用了多种解决方案组合来做出对我有用的东西。
我能够在多个ServiceConfiguration文件中定义我的设置,例如ServiceConfiguration.Local.cscfg
, ServiceConfiguration.Dev.cscfg
和ServiceConfiguration.Production.cscfg
。 在<ConfigurationSettings>
,添加<Setting name="settingname" value="settingvalue" />
,或使用Visual Studio中的界面。 发布时,您可以选择要使用的配置文件,而无需修改任何代码。 附加优势在于,在发布服务之后,还可以通过Azure门户修改这些设置。 看到这篇文章和这篇文章 。
下一个挑战是将这些变量注入Python环境。 与ServiceDefinition.csdef
中定义的变量不同,配置设置不适用于Python环境。 但是,它们存储在某个地方的DLL中,可以使用一些C#方法调用进行访问并注入到Python环境中(我对整个过程一无所知,我只是关注这篇文章 )。 只需将这些行添加到LaunchWorker.ps1
,即在iex "py $worker_command"
之前的任何位置:
# search for the Dll
$Splathashtable = @{
'Path' = "$env:windir\Microsoft.NET\assembly\";
'Filter' = 'Microsoft.WindowsAzure.ServiceRuntime.dll';
'Include' = '*.dll'
}
$dllfile = Get-ChildItem @Splathashtable -Recurse | Select-Object -Last 1
# selecting only one object, in case of multiple results
# add the DLL to the current PowerShell session
Add-Type -Path $dllfile.FullName
# Call the Static method on the class to retrieve the setting value
$Setting = [Microsoft.WindowsAzure.ServiceRuntime.RoleEnvironment]::GetConfigurationSettingValue('settingname')
# add setting to environment
[Environment]::SetEnvironmentVariable('settingname', $Setting)
现在,您可以通过os.environ.get('SETTINGNAME')
找到该设置在Python中os.environ.get('SETTINGNAME')
您可以在ServiceDefinition.csdef
文件中设置自定义运行时变量,然后可以利用os.environ.get('MY_ENV_NAME')
调用它。
EG ServiceDefinition.csdef
的内容应为:
<WorkerRole name="WorkerRole1" vmsize="Small">
<ConfigurationSettings>
...
</ConfigurationSettings>
<Startup>
...
</Startup>
<Runtime>
<Environment>
<Variable name="MY_ENV_NAME" value="my_value" />
<Variable name="EMULATED">
<RoleInstanceValue xpath="/RoleEnvironment/Deployment/@emulated" />
</Variable>
</Environment>
...
</Runtime>
...
</WorkerRole>
您可以参考http://blog.toddysm.com/2011/03/what-environment-variables-can-you-use-in-windows-azure.html了解更多详细信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.