github.com/StackPointCloud/packer@v0.10.2-0.20180716202532-b28098e0f79b/builder/triton/ssh.go (about) 1 package triton 2 3 import ( 4 "fmt" 5 6 "io/ioutil" 7 "log" 8 "net" 9 "os" 10 11 packerssh "github.com/hashicorp/packer/communicator/ssh" 12 "github.com/hashicorp/packer/helper/multistep" 13 "golang.org/x/crypto/ssh" 14 "golang.org/x/crypto/ssh/agent" 15 ) 16 17 func commHost(state multistep.StateBag) (string, error) { 18 driver := state.Get("driver").(Driver) 19 machineID := state.Get("machine").(string) 20 21 machine, err := driver.GetMachineIP(machineID) 22 if err != nil { 23 return "", err 24 } 25 26 return machine, nil 27 } 28 29 // SSHConfig returns a function that can be used for the SSH communicator 30 // config for connecting to the instance created over SSH using the private key 31 // or password. 32 func sshConfig(useAgent bool, username, privateKeyPath, password string) func(multistep.StateBag) (*ssh.ClientConfig, error) { 33 return func(state multistep.StateBag) (*ssh.ClientConfig, error) { 34 35 if useAgent { 36 log.Println("Configuring SSH agent.") 37 38 authSock := os.Getenv("SSH_AUTH_SOCK") 39 if authSock == "" { 40 return nil, fmt.Errorf("SSH_AUTH_SOCK is not set") 41 } 42 43 sshAgent, err := net.Dial("unix", authSock) 44 if err != nil { 45 return nil, fmt.Errorf("Cannot connect to SSH Agent socket %q: %s", authSock, err) 46 } 47 48 return &ssh.ClientConfig{ 49 User: username, 50 Auth: []ssh.AuthMethod{ 51 ssh.PublicKeysCallback(agent.NewClient(sshAgent).Signers), 52 }, 53 HostKeyCallback: ssh.InsecureIgnoreHostKey(), 54 }, nil 55 } 56 57 hasKey := privateKeyPath != "" 58 59 if hasKey { 60 log.Printf("Configuring SSH private key '%s'.", privateKeyPath) 61 62 privateKeyBytes, err := ioutil.ReadFile(privateKeyPath) 63 if err != nil { 64 return nil, fmt.Errorf("Unable to read SSH private key: %s", err) 65 } 66 67 signer, err := ssh.ParsePrivateKey(privateKeyBytes) 68 if err != nil { 69 return nil, fmt.Errorf("Error setting up SSH config: %s", err) 70 } 71 72 return &ssh.ClientConfig{ 73 User: username, 74 Auth: []ssh.AuthMethod{ 75 ssh.PublicKeys(signer), 76 }, 77 HostKeyCallback: ssh.InsecureIgnoreHostKey(), 78 }, nil 79 } else { 80 log.Println("Configuring SSH keyboard interactive.") 81 82 return &ssh.ClientConfig{ 83 User: username, 84 HostKeyCallback: ssh.InsecureIgnoreHostKey(), 85 Auth: []ssh.AuthMethod{ 86 ssh.Password(password), 87 ssh.KeyboardInteractive( 88 packerssh.PasswordKeyboardInteractive(password)), 89 }}, nil 90 } 91 } 92 }