github.com/phobos182/packer@v0.2.3-0.20130819023704-c84d2aeffc68/builder/amazon/common/ssh.go (about) 1 package common 2 3 import ( 4 gossh "code.google.com/p/go.crypto/ssh" 5 "errors" 6 "fmt" 7 "github.com/mitchellh/goamz/ec2" 8 "github.com/mitchellh/packer/communicator/ssh" 9 "time" 10 ) 11 12 // SSHAddress returns a function that can be given to the SSH communicator 13 // for determining the SSH address based on the instance DNS name. 14 func SSHAddress(e *ec2.EC2, port int) func(map[string]interface{}) (string, error) { 15 return func(state map[string]interface{}) (string, error) { 16 for j := 0; j < 2; j++ { 17 var host string 18 i := state["instance"].(*ec2.Instance) 19 if i.DNSName != "" { 20 host = i.DNSName 21 } else if i.VpcId != "" { 22 host = i.PrivateIpAddress 23 } 24 25 if host != "" { 26 return fmt.Sprintf("%s:%d", host, port), nil 27 } 28 29 r, err := e.Instances([]string{i.InstanceId}, ec2.NewFilter()) 30 if err != nil { 31 return "", err 32 } 33 34 if len(r.Reservations) == 0 || len(r.Reservations[0].Instances) == 0 { 35 return "", fmt.Errorf("instance not found: %s", i.InstanceId) 36 } 37 38 state["instance"] = &r.Reservations[0].Instances[0] 39 time.Sleep(1 * time.Second) 40 } 41 42 return "", errors.New("couldn't determine IP address for instance") 43 } 44 } 45 46 // SSHConfig returns a function that can be used for the SSH communicator 47 // config for connecting to the instance created over SSH using the generated 48 // private key. 49 func SSHConfig(username string) func(map[string]interface{}) (*gossh.ClientConfig, error) { 50 return func(state map[string]interface{}) (*gossh.ClientConfig, error) { 51 privateKey := state["privateKey"].(string) 52 53 keyring := new(ssh.SimpleKeychain) 54 if err := keyring.AddPEMKey(privateKey); err != nil { 55 return nil, fmt.Errorf("Error setting up SSH config: %s", err) 56 } 57 58 return &gossh.ClientConfig{ 59 User: username, 60 Auth: []gossh.ClientAuth{ 61 gossh.ClientAuthKeyring(keyring), 62 }, 63 }, nil 64 } 65 }