func runScript(ctx context.Context, key, value string) error {
	var u *url.URL
	if strings.HasSuffix(key, "-url") {
		var err error
		u, err = url.Parse(strings.TrimSpace(value))
		if err != nil {
			return err
		}
	}
	dir, err := ioutil.TempDir(config.Section("MetadataScripts").Key("run_dir").String(), "metadata-scripts")
	if err != nil {
		return err
	}
	defer os.RemoveAll(dir)
	tmpFile := filepath.Join(dir, key)
	for _, ext := range []string{"bat", "cmd", "ps1"} {
		if strings.HasSuffix(key, "-"+ext) || (u != nil && strings.HasSuffix(u.Path, "."+ext)) {
			tmpFile = fmt.Sprintf("%s.%s", tmpFile, ext)
			break
		}
	}
	if u != nil {
		file, err := os.OpenFile(tmpFile, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0755)
		if err != nil {
			return fmt.Errorf("error opening temp file: %v", err)
		}
		if err := downloadScript(ctx, value, file); err != nil {
			file.Close()
			return err
		}
		if err := file.Close(); err != nil {
			return fmt.Errorf("error closing temp file: %v", err)
		}
	} else {
		value = strings.TrimLeft(value, " \n\v\f\t\r")
		if err := ioutil.WriteFile(tmpFile, []byte(value), 0755); err != nil {
			return fmt.Errorf("error writing temp file: %v", err)
		}
	}
	var c *exec.Cmd
	if strings.HasSuffix(tmpFile, ".ps1") {
		c = exec.Command("powershell.exe", append(powerShellArgs, tmpFile)...)
	} else {
		if runtime.GOOS == "windows" {
			c = exec.Command(tmpFile)
		} else {
			c = exec.Command(config.Section("MetadataScripts").Key("default_shell").MustString("/bin/bash"), "-c", tmpFile)
		}
	}
	return runCmd(c, key)
}
runScript makes a temporary directory and temporary file for the script, downloads and then runs it.
package main
import (
	"bufio"
	"context"
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"net"
	"net/http"
	"net/url"
	"os"
	"os/exec"
	"path/filepath"
	"regexp"
	"runtime"
	"strings"
	"time"
	"cloud.google.com/go/storage"
	"github.com/GoogleCloudPlatform/guest-logging-go/logger"
	"github.com/go-ini/ini"
	"github.com/tarm/serial"
)
var (
	programName    = "GCEMetadataScripts"
	version        = "dev"
	metadataURL    = "http://169.254.169.254/computeMetadata/v1"
	metadataHang   = "/?recursive=true&alt=json&timeout_sec=10&last_etag=NONE"
	defaultTimeout = 20 * time.Second
	powerShellArgs = []string{"-NoProfile", "-NoLogo", "-ExecutionPolicy", "Unrestricted", "-File"}
	errUsage       = fmt.Errorf("No valid arguments specified. Specify one of \"startup\", \"shutdown\" or \"specialize\"")
	config         *ini.File
	storageURL = "storage.googleapis.com"
	bucket = `([a-z0-9][-_.a-z0-9]*)`
	object = `(.+)`
	bucketRegex = regexp.MustCompile(fmt.Sprintf(`^gs: 
	gsRegex     = regexp.MustCompile(fmt.Sprintf(`^gs: 
	gsHTTPRegex1 = regexp.MustCompile(fmt.Sprintf(`^http[s]?: 
	gsHTTPRegex2 = regexp.MustCompile(fmt.Sprintf(`^http[s]?: 
	gsHTTPRegex3 = regexp.MustCompile(fmt.Sprintf(`^http[s]?: 
	testStorageClient *storage.Client
)
const (
	winConfigPath = `C:\Program Files\Google\Compute Engine\instance_configs.cfg`
	configPath    = `/etc/default/instance_configs.cfg`
)
func newStorageClient(ctx context.Context) (*storage.Client, error) {
	if testStorageClient != nil {
		return testStorageClient, nil
	}
	return storage.NewClient(ctx)
}
func downloadGSURL(ctx context.Context, bucket, object string, file *os.File) error {
	client, err := newStorageClient(ctx)
	if err != nil {
		return fmt.Errorf("failed to create storage client: %v", err)
	}
	defer client.Close()
	r, err := client.Bucket(bucket).Object(object).NewReader(ctx)
	if err != nil {
		return fmt.Errorf("error reading object %q: %v", object, err)
	}
	defer r.Close()
	_, err = io.Copy(file, r)
	return err
}
func downloadURL(url string, file *os.File) error {
	var res *http.Response
	var err error
	for i := 1; ; i++ {
		res, err = http.Get(url)
		if err != nil && i > 3 {
			return err
		}
		if err == nil {
			break
		}
		time.Sleep(1 * time.Second)
	}
	defer res.Body.Close()
	if res.StatusCode != http.StatusOK {
		return fmt.Errorf("GET %q, bad status: %s", url, res.Status)
	}
	_, err = io.Copy(file, res.Body)
	return err
}
func downloadScript(ctx context.Context, path string, file *os.File) error {
	for i := 0; i < 20; i++ {
		if _, err := net.LookupHost(storageURL); err == nil {
			break
		}
		time.Sleep(5 * time.Second)
	}
	bucket, object := parseGCS(path)
	if bucket != "" && object != "" {
		for i := 1; ; i++ {
			err := downloadGSURL(ctx, bucket, object, file)
			if err == nil {
				return nil
			}
			if err != nil && i > 3 {
				logger.Infof("Failed to download GCS path: %v", err)
				break
			}
			time.Sleep(1 * time.Second)
		}
		logger.Infof("Trying unauthenticated download")
		path = fmt.Sprintf("https://%s/%s/%s", storageURL, bucket, object)
	}
	return downloadURL(path, file)
}
func parseGCS(path string) (string, string) {
	for _, re := range []*regexp.Regexp{gsRegex, gsHTTPRegex1, gsHTTPRegex2, gsHTTPRegex3} {
		match := re.FindStringSubmatch(path)
		if len(match) == 3 {
			return match[1], match[2]
		}
	}
	return "", ""
}
func getMetadataKey(key string) (string, error) {
	md, err := getMetadata(key, false)
	if err != nil {
		return "", err
	}
	return string(md), nil
}
func getMetadataAttributes(key string) (map[string]string, error) {
	md, err := getMetadata(key, true)
	if err != nil {
		return nil, err
	}
	var att map[string]string
	return att, json.Unmarshal(md, &att)
}
func getMetadata(key string, recurse bool) ([]byte, error) {
	client := &http.Client{
		Timeout: defaultTimeout,
	}
	url := metadataURL + key
	if recurse {
		url += metadataHang
	}
	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		return nil, err
	}
	req.Header.Add("Metadata-Flavor", "Google")
	var res *http.Response
	var rt time.Duration
	for i := 1; ; i++ {
		res, err = client.Do(req)
		if err == nil {
			break
		}
		if i < 6 {
			rt = time.Duration(3*i) * time.Second
		}
		logger.Errorf("error connecting to metadata server, retrying in %s, error: %v", rt, err)
		time.Sleep(rt)
	}
	defer res.Body.Close()
	md, err := ioutil.ReadAll(res.Body)
	if err != nil {
		return nil, err
	}
	return md, nil
}