extract environment variables from gae config

Google App Engine (GAE) applications are deployed with an app.yaml file which contains all of the application configuration required.

If, however, you wanted to run an application locally before deploying to GAE, you may need to extract the environment variables defined in the app.yaml file into a local .env file.

To accomplish this, I wrote a small Golang package:

yamlenv.go
package yamlenv

import (
	"io/ioutil"
	"os"

	"gopkg.in/yaml.v2"
)

// AppConfig contains the GAE-formatted config data
type AppConfig struct {
	Environment map[string]string `yaml:"env_variables"`
}

// Export exports the environment data from file f to AppConfig
func Export(f string) (*AppConfig, error) {
	ac := &AppConfig{}
	var e error
	yd, rerr := ioutil.ReadFile(f)
	if rerr != nil {
		return ac, rerr
	}
	err := yaml.Unmarshal(yd, ac)
	if err != nil {
		return ac, err
	}
	return ac, e
}

// ExportToFile exports the environment data from file f to destination d
// Defaults to append to file if exists, over bool will overwrite if true
func ExportToFile(f string, d string, over bool) error {
	var e error
	ac, err := Export(f)
	if err != nil {
		return err
	}
	var fd string
	if _, err := os.Stat(d); err == nil && over == false {
		bd, rerr := ioutil.ReadFile(d)
		if rerr != nil {
			return rerr
		}
		fd = string(bd) + "\n"
	}
	for k, v := range ac.Environment {
		fd += k + "=" + v + "\n"
	}
	werr := ioutil.WriteFile(d, []byte(fd), 0644)
	if werr != nil {
		return werr
	}
	return e
}


To use, simply call yamlenv.ExportToFile("/path/to/app.yaml", "/path/to/.env", true). Set the third param (bool) to false to append rather than overwrite.

last updated 2022-08-20