From 164f303da40cd505edef22c75986e420b694331a Mon Sep 17 00:00:00 2001 From: Tarrant Date: Sun, 15 Mar 2015 16:12:25 -0700 Subject: [PATCH] Add SSH Agent support --- .../remote-exec/resource_provisioner.go | 7 +++-- helper/ssh/provisioner.go | 26 ++++++++++++++++++- 2 files changed, 30 insertions(+), 3 deletions(-) diff --git a/builtin/provisioners/remote-exec/resource_provisioner.go b/builtin/provisioners/remote-exec/resource_provisioner.go index b3f0d0c0e9..d190250a21 100644 --- a/builtin/provisioners/remote-exec/resource_provisioner.go +++ b/builtin/provisioners/remote-exec/resource_provisioner.go @@ -178,10 +178,13 @@ func (p *ResourceProvisioner) runScripts( " Host: %s\n"+ " User: %s\n"+ " Password: %v\n"+ - " Private key: %v", + " Private key: %v"+ + " SSH Agent: %v", conf.Host, conf.User, conf.Password != "", - conf.KeyFile != "")) + conf.KeyFile != "", + conf.Agent, + )) // Wait and retry until we establish the SSH connection var comm *helper.SSHCommunicator diff --git a/helper/ssh/provisioner.go b/helper/ssh/provisioner.go index 2d60d89347..bf67d8a5be 100644 --- a/helper/ssh/provisioner.go +++ b/helper/ssh/provisioner.go @@ -5,12 +5,15 @@ import ( "fmt" "io/ioutil" "log" + "net" + "os" "time" - "golang.org/x/crypto/ssh" "github.com/hashicorp/terraform/terraform" "github.com/mitchellh/go-homedir" "github.com/mitchellh/mapstructure" + "golang.org/x/crypto/ssh" + "golang.org/x/crypto/ssh/agent" ) const ( @@ -37,6 +40,7 @@ type SSHConfig struct { KeyFile string `mapstructure:"key_file"` Host string Port int + Agent bool Timeout string ScriptPath string `mapstructure:"script_path"` TimeoutVal time.Duration `mapstructure:"-"` @@ -102,6 +106,26 @@ func PrepareConfig(conf *SSHConfig) (*Config, error) { sshConf := &ssh.ClientConfig{ User: conf.User, } + if conf.Agent { + sshAuthSock := os.Getenv("SSH_AUTH_SOCK") + + if sshAuthSock == "" { + return nil, fmt.Errorf("SSH Requested but SSH_AUTH_SOCK not-specified") + } + + conn, err := net.Dial("unix", sshAuthSock) + if err != nil { + return nil, fmt.Errorf("Error connecting to SSH_AUTH_SOCK: %v", err) + } + // I need to close this but, later after all connections have been made + // defer conn.Close() + signers, err := agent.NewClient(conn).Signers() + if err != nil { + return nil, fmt.Errorf("Error getting keys from ssh agent: %v", err) + } + + sshConf.Auth = append(sshConf.Auth, ssh.PublicKeys(signers...)) + } if conf.KeyFile != "" { fullPath, err := homedir.Expand(conf.KeyFile) if err != nil {