【问题标题】:Azure Environment Variables in Python Cloud ServicePython 云服务中的 Azure 环境变量
【发布时间】:2016-04-08 01:58:51
【问题描述】:

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

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

有什么方法可以实现吗?

【问题讨论】:

  • 这在 Azure Web Apps 中是可能的,但我不知道 Azure 云服务。

标签: python azure azure-storage azure-cloud-services


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

    您可以在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了解更多详情。

    【讨论】:

    • 非常有用,谢谢!我看到您可以区分启动和运行时,但您也可以区分暂存和生产吗?这就是我需要的。
    • 嗨,加里,我设计了一种方法来获得我需要的东西并将其作为单独的答案发布。感谢您让我上路,我会很感激任何 cmets!
    猜你喜欢
    • 2021-08-21
    • 1970-01-01
    • 2022-12-14
    • 2016-12-09
    • 2014-09-30
    • 1970-01-01
    • 1970-01-01
    • 2011-06-21
    • 1970-01-01
    相关资源
    最近更新 更多