github.com/jerryclinesmith/packer@v0.3.7/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 host = i.PrivateIpAddress 24 } 25 26 if host != "" { 27 return fmt.Sprintf("%s:%d", host, port), nil 28 } 29 30 r, err := e.Instances([]string{i.InstanceId}, ec2.NewFilter()) 31 if err != nil { 32 return "", err 33 } 34 35 if len(r.Reservations) == 0 || len(r.Reservations[0].Instances) == 0 { 36 return "", fmt.Errorf("instance not found: %s", i.InstanceId) 37 } 38 39 state.Put("instance", &r.Reservations[0].Instances[0]) 40 time.Sleep(1 * time.Second) 41 } 42 43 return "", errors.New("couldn't determine IP address for instance") 44 } 45 } 46 47 // SSHConfig returns a function that can be used for the SSH communicator 48 // config for connecting to the instance created over SSH using the generated 49 // private key. 50 func SSHConfig(username string) func(multistep.StateBag) (*gossh.ClientConfig, error) { 51 return func(state multistep.StateBag) (*gossh.ClientConfig, error) { 52 privateKey := state.Get("privateKey").(string) 53 54 keyring := new(ssh.SimpleKeychain) 55 if err := keyring.AddPEMKey(privateKey); err != nil { 56 return nil, fmt.Errorf("Error setting up SSH config: %s", err) 57 } 58 59 return &gossh.ClientConfig{ 60 User: username, 61 Auth: []gossh.ClientAuth{ 62 gossh.ClientAuthKeyring(keyring), 63 }, 64 }, nil 65 } 66 }