【问题标题】:How to read environmental variables in app.yaml?如何读取 app.yaml 中的环境变量?
【发布时间】:2021-12-27 04:29:20
【问题描述】:

我正在使用 Google App Engine,并且有一个如下所示的 app.yaml 文件:

runtime: go115

env_variables:
  INSTANCE_CONNECTION_NAME: secret:northamerica-northeast1:special
  DB_USER: db_username
  DB_PASS: p@ssword
  DB_NAME: superduper

使用这个Github 作为参考,我正在使用它来读取这些值:

dbUser = mustGetenv("DB_USER")

我执行 gcloud app deploy 然后使用 set 命令检查变量。我在那里看不到变量,同样,当我的程序运行时它找不到变量。

我似乎正在执行示例正在执行的所有操作,但我的程序没有找到我的变量。 yaml文件是否有任何特定格式?在尝试读取变量之前我还需要执行其他步骤吗?

【问题讨论】:

    标签: go google-app-engine google-cloud-platform


    【解决方案1】:

    您可以使用os.Getenv 读取变量。

    dbUser = os.Getenv("DB_USER")
    

    你必须引用你的价值观。

    env_variables:
      INSTANCE_CONNECTION_NAME: 'secret:northamerica-northeast1:special'
      DB_USER: 'db_username'
      DB_PASS: 'p@ssword'
      DB_NAME: 'superduper'
    

    【讨论】:

      【解决方案2】:

      您可以尝试使用毒蛇https://github.com/spf13/viper

      func Init() {
        // Set the file name of the configurations file
        viper.SetConfigName("app")
      
        // Set the path to look for the configurations file
        viper.AddConfigPath("./config")
      
        // Enable VIPER to read Environment Variables
        viper.AutomaticEnv()
      
        viper.SetConfigType("yaml")
      
        if err := viper.ReadInConfig(); err != nil {
            fmt.Printf("Error reading config file, %s", err)
        }
      }
      

      在你的 main 中添加这个初始化,然后你可以在代码中的任何地方使用以下代码来访问

      viper.GetString("env_variables.INSTANCE_CONNECTION_NAME")
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-05-18
        • 1970-01-01
        • 2019-06-05
        • 2012-04-17
        • 2020-09-18
        • 2017-11-03
        • 2018-07-01
        • 2017-09-04
        相关资源
        最近更新 更多