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