2020-03-12 22:26:38 -04:00
|
|
|
package common
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
2020-04-24 09:05:13 -04:00
|
|
|
"context"
|
2020-03-12 22:26:38 -04:00
|
|
|
"fmt"
|
|
|
|
"log"
|
|
|
|
"os/exec"
|
|
|
|
|
|
|
|
"github.com/hashicorp/packer/packer"
|
|
|
|
)
|
|
|
|
|
2020-04-22 07:52:47 -04:00
|
|
|
const SessionManagerPluginName string = "session-manager-plugin"
|
2020-03-12 22:26:38 -04:00
|
|
|
|
2020-04-22 07:52:47 -04:00
|
|
|
type SSMDriver struct {
|
2020-04-24 09:05:13 -04:00
|
|
|
Ui packer.Ui
|
|
|
|
Ctx context.Context
|
2020-04-22 07:52:47 -04:00
|
|
|
// Provided for testing purposes; if not specified it defaults to SessionManagerPluginName
|
|
|
|
PluginName string
|
2020-03-12 22:26:38 -04:00
|
|
|
}
|
|
|
|
|
2020-04-22 07:52:47 -04:00
|
|
|
// StartSession starts an interactive Systems Manager session with a remote instance via the AWS session-manager-plugin
|
2020-03-12 22:26:38 -04:00
|
|
|
func (s *SSMDriver) StartSession(sessionData, region, profile, params, endpoint string) error {
|
|
|
|
var stdout bytes.Buffer
|
|
|
|
var stderr bytes.Buffer
|
|
|
|
|
|
|
|
args := []string{
|
|
|
|
sessionData,
|
|
|
|
region,
|
|
|
|
"StartSession",
|
|
|
|
profile,
|
|
|
|
params,
|
|
|
|
endpoint,
|
|
|
|
}
|
|
|
|
|
2020-04-22 07:52:47 -04:00
|
|
|
if s.PluginName == "" {
|
|
|
|
s.PluginName = SessionManagerPluginName
|
|
|
|
}
|
|
|
|
|
|
|
|
if _, err := exec.LookPath(s.PluginName); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2020-03-12 22:26:38 -04:00
|
|
|
log.Printf("Attempting to start session with the following args: %v", args)
|
2020-04-24 09:05:13 -04:00
|
|
|
cmd := exec.CommandContext(s.Ctx, s.PluginName, args...)
|
2020-03-12 22:26:38 -04:00
|
|
|
cmd.Stdout = &stdout
|
|
|
|
cmd.Stderr = &stderr
|
|
|
|
|
|
|
|
if err := cmd.Start(); err != nil {
|
2020-04-22 07:52:47 -04:00
|
|
|
err = fmt.Errorf("error encountered when calling %s: %s\nStderr: %s", s.PluginName, err, stderr.String())
|
2020-03-12 22:26:38 -04:00
|
|
|
s.Ui.Error(err.Error())
|
|
|
|
return err
|
|
|
|
}
|
2020-04-22 07:52:47 -04:00
|
|
|
// TODO capture logging for testing
|
2020-03-12 22:26:38 -04:00
|
|
|
log.Println(stdout.String())
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|