Bromide
Bromide

Reputation: 1112

How to read environmental variables in app.yaml?

I am using Google App Engine and have an app.yaml file that looks like this:

runtime: go115

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

Using this Github as a refernce, I am using this to read those values:

dbUser = mustGetenv("DB_USER")

I do a gcloud app deploy and then check for the variable with the set command. I do not see the variable there, and likewise, when my program runs it can not find the variable.

I seem to be doing everything the example is doing, but my variable is not being found by my program. Is there any specific formating of the yaml file? Is there some other step I need to be doing before trying to read the variable?

Upvotes: 0

Views: 1794

Answers (2)

Sachin Chavan
Sachin Chavan

Reputation: 286

You can try using viper 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)
  }
}

Add this initialisation in you main then you can access using following anywhere in code

viper.GetString("env_variables.INSTANCE_CONNECTION_NAME")

Upvotes: 0

N.F.
N.F.

Reputation: 4192

You can read variables with os.Getenv.

dbUser = os.Getenv("DB_USER")

And you have to quote your values.

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

Upvotes: 1

Related Questions