github.com/emc-advanced-dev/unik@v0.0.0-20190717152701-a58d3e8e33b7/containers/compilers/rump/go/stub/bootstrap_ec2.go (about)

     1  // +build ec2
     2  
     3  package main
     4  
     5  import (
     6  	"encoding/json"
     7  	"errors"
     8  	"io/ioutil"
     9  	"log"
    10  	"net"
    11  	"net/http"
    12  	"time"
    13  )
    14  
    15  func bootstrap() error {
    16  	log.Printf("bootstrapping using ec2 metadata service")
    17  	env, err := getEnvAmazon()
    18  	if err != nil {
    19  		return errors.New("failed to get env from ec2: " + err.Error())
    20  	}
    21  	if err := setEnv(env); err != nil {
    22  		return errors.New("setting env: " + err.Error())
    23  	}
    24  	return nil
    25  }
    26  
    27  var timeout = time.Duration(2 * time.Second)
    28  
    29  func dialTimeout(network, addr string) (net.Conn, error) {
    30  	return net.DialTimeout(network, addr, timeout)
    31  }
    32  
    33  func getEnvAmazon() (map[string]string, error) {
    34  	client := http.Client{
    35  		Transport: &http.Transport{
    36  			Dial: dialTimeout,
    37  		},
    38  	}
    39  	resp, err := client.Get("http://169.254.169.254/latest/user-data")
    40  	if err != nil {
    41  		return nil, err
    42  	}
    43  	data, err := ioutil.ReadAll(resp.Body)
    44  	if err != nil {
    45  		return nil, err
    46  	}
    47  	defer resp.Body.Close()
    48  	var env map[string]string
    49  	if err := json.Unmarshal(data, &env); err != nil {
    50  		return nil, err
    51  	}
    52  	return env, nil
    53  }