Python 云服务中的 Azure 环境变量

Azure Environment Variables in Python Cloud Service

我在 Microsoft Azure 上有一个 Python 云服务 运行,它应该使用不同的存储帐户(用于 blob 存储和队列)当它在 运行 开发与暂存中与生产。

我宁愿不对存储帐户凭据进行硬编码,而是从环境中获取它们。或者,我想要一个环境变量或指示我是在暂存还是生产中的东西。当我尝试 print(os.environ) 时,我没有看到任何 azure 存储凭证,也没有看到指示暂存或生产的值。

有什么办法可以实现吗?

您可以在 ServiceDefinition.csdef 文件中设置自定义运行时变量,然后您可以利用 os.environ.get('MY_ENV_NAME').

调用它

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

我正在回答我自己的问题,因为我使用了多种解决方案的组合来制作适合我的东西。

我能够在多个 ServiceConfiguration 文件中定义我的设置,例如 ServiceConfiguration.Local.cscfgServiceConfiguration.Dev.cscfgServiceConfiguration.Production.cscfg。在<ConfigurationSettings>下添加<Setting name="settingname" value="settingvalue" />,或使用Visual Studio中的接口。发布时,您可以选择要使用的配置文件,而无需修改任何代码。另一个好处是,这些设置也可以在服务发布后通过 Azure 门户进行修改。参见 this post and this post

下一个挑战是将这些变量注入 Python 环境。与 ServiceDefinition.csdef 中定义的变量不同,配置设置不适用于 Python 环境。然而,它们存储在某处的 DLL 中,可以使用一些 C# 方法调用访问并注入到 Python 环境中(我对整个过程一无所知,我只是遵循 this post)。只需将这些行添加到 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)

现在您会发现该设置在 Python 到 os.environ.get('SETTINGNAME')

中可用