packer-cn/provisioner/ansible/provisioner.go

563 lines
14 KiB
Go
Raw Normal View History

2015-03-10 00:11:57 -04:00
package ansible
import (
"bufio"
"bytes"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
2015-03-10 00:11:57 -04:00
"errors"
"fmt"
"io"
"io/ioutil"
"log"
"net"
"os"
"os/exec"
"os/user"
2015-03-10 00:11:57 -04:00
"path/filepath"
"regexp"
2015-03-10 00:11:57 -04:00
"strconv"
"strings"
"sync"
"unicode"
2015-03-10 00:11:57 -04:00
"golang.org/x/crypto/ssh"
2017-04-04 16:39:01 -04:00
"github.com/hashicorp/packer/common"
2019-02-12 02:10:57 -05:00
"github.com/hashicorp/packer/common/adapter"
commonhelper "github.com/hashicorp/packer/helper/common"
2017-04-04 16:39:01 -04:00
"github.com/hashicorp/packer/helper/config"
"github.com/hashicorp/packer/packer"
Add tmp package that offers Dir & File funcs this regroups the calls of tmp func calls into one package. the tmp pkg allows to store tmp files under a common directory for easier managment Squashed commit of the following: commit 74b674c01560c6b547e9cab5e8afb486f0fe7d6c Merge: fc94b5714 66001525d Author: Matthew Patton <mpatton@enquizit.com> Date: Fri Nov 2 02:02:38 2018 -0400 Merge branch 'remove_TMPDIR_docs' of github.com:tb3088/packer into remove_TMPDIR_docs commit fc94b571428447aaf2e5171967c95cdf9e5c73ff Author: Matthew Patton <mpatton@enquizit.com> Date: Fri Nov 2 01:42:38 2018 -0400 update tests to honor configured temporary directory commit 5a562359f4937af506607dd96ed1c46426093f52 Author: Matthew Patton <mpatton@enquizit.com> Date: Thu Nov 1 18:52:38 2018 -0400 sync straggler to refactor. implement tests at packer/configfile instead of buried in docker. commit 9d5a4a0935bfd049e2f8f50ad73e4455b42c9410 Author: Matthew Patton <mpatton@enquizit.com> Date: Thu Nov 1 15:39:46 2018 -0400 insert URL to GoLang API for os.TempDir() commit fbae4c2e051898aecd8705e9d8a20353430ede23 Author: Matthew Patton <mpatton@enquizit.com> Date: Thu Nov 1 07:41:29 2018 -0400 revise documentation to match code commit 3590fae8bd0afa92a161a49ed794ee32e357d583 Author: Matthew Patton <mpatton@enquizit.com> Date: Thu Nov 1 07:21:59 2018 -0400 refacter config_file. replace all hard-coded os.TempDir with wrapper commit d5c5306a97b648ded06a8eb76ce728f07c9924f0 Author: Matthew Patton <mpatton@enquizit.com> Date: Wed Oct 31 20:11:36 2018 -0400 close massive file overwrite hole with TempDir commit 0a72297da86089fbd07e4f7d9472a92fa4d1c733 Author: Matthew Patton <mpatton@enquizit.com> Date: Wed Oct 31 01:06:00 2018 -0400 adjust var declaration scope commit 20f68228b6c372d984ea5b055cfc8bda9b110ac5 Author: Matthew Patton <mpatton@enquizit.com> Date: Wed Oct 31 00:54:35 2018 -0400 use mktemp() equivalent to create temporary directory commit c73ebe3d8321664a2685a0baa8e441dd895b0db4 Author: Matthew Patton <mpatton@enquizit.com> Date: Tue Oct 30 20:40:58 2018 -0400 remove extraneous variable declaration, fix FOR loop commit 63549b8bd745a0090b15ed0b0ebf644162db27db Author: Matthew Patton <mpatton@enquizit.com> Date: Tue Oct 30 19:30:44 2018 -0400 match styistic convension with rest of docs commit 976101074942db36f10d3a686d6d29ddb7c01926 Author: Matthew Patton <mpatton@enquizit.com> Date: Tue Oct 30 19:08:39 2018 -0400 revert dangling config file change commit 95159afbc05eac96ed11c3183af5fb0abe2f2d5c Author: Matthew Patton <matthew.patton@itgfirm.com> Date: Fri Dec 29 23:53:43 2017 -0500 replace invalid TMPDIR variable wth PACKER_TMP_DIR. update ConfigTmpDir() to try common temporary paths first and only write to configDir() as a last resort. commit 66001525d72de56a4cf9339b900c46f59bc6e91a Author: Matthew Patton <mpatton@enquizit.com> Date: Fri Nov 2 01:42:38 2018 -0400 update tests to honor configured temporary directory commit e9b6adefeae8c65eb8aa47fef38cbf0aa424338c Author: Matthew Patton <mpatton@enquizit.com> Date: Thu Nov 1 18:52:38 2018 -0400 sync straggler to refactor. implement tests at packer/configfile instead of buried in docker. commit 852113ed076e2d14e5dca6815ea680da1e2896bb Author: Matthew Patton <mpatton@enquizit.com> Date: Thu Nov 1 15:39:46 2018 -0400 insert URL to GoLang API for os.TempDir() commit 54add38d1d1c6e283cd444b367ed8bd49a5f3699 Author: Matthew Patton <mpatton@enquizit.com> Date: Thu Nov 1 07:41:29 2018 -0400 revise documentation to match code commit 6b5b8f6d4edad0e187ca13d64ac4118f34eee643 Author: Matthew Patton <mpatton@enquizit.com> Date: Thu Nov 1 07:21:59 2018 -0400 refacter config_file. replace all hard-coded os.TempDir with wrapper commit c22092c601c33484327674f322c7379fa41506d7 Author: Matthew Patton <mpatton@enquizit.com> Date: Wed Oct 31 20:11:36 2018 -0400 close massive file overwrite hole with TempDir commit 7a730450916bf8e5dbc2a741ec233a49466ab7cc Author: Matthew Patton <mpatton@enquizit.com> Date: Wed Oct 31 01:06:00 2018 -0400 adjust var declaration scope commit 0f2933adb6f6922dfeab78a95371a444ec8918ab Author: Matthew Patton <mpatton@enquizit.com> Date: Wed Oct 31 00:54:35 2018 -0400 use mktemp() equivalent to create temporary directory commit d74839ede05dacf712b55a7bb48aec19fe6b007f Author: Matthew Patton <mpatton@enquizit.com> Date: Tue Oct 30 20:40:58 2018 -0400 remove extraneous variable declaration, fix FOR loop commit eb65416619437e4a3dec90277770803dd5b2281c Author: Matthew Patton <mpatton@enquizit.com> Date: Tue Oct 30 19:30:44 2018 -0400 match styistic convension with rest of docs commit acaa2b31ed463219c4ef099f351eec72406e2989 Author: Matthew Patton <mpatton@enquizit.com> Date: Tue Oct 30 19:08:39 2018 -0400 revert dangling config file change commit e573fde668dcb418561e61535c1d68b2888f5b0f Author: Matthew Patton <matthew.patton@itgfirm.com> Date: Fri Dec 29 23:53:43 2017 -0500 replace invalid TMPDIR variable wth PACKER_TMP_DIR. update ConfigTmpDir() to try common temporary paths first and only write to configDir() as a last resort. commit 39a9874afc9dea71b36753375fb7feb61ffecf69 Merge: 8a413cfe8 3315812c2 Author: Matthew Patton <mpatton@enquizit.com> Date: Tue Oct 30 18:19:26 2018 -0400 Merge branch 'master' of https://github.com/hashicorp/packer into prestine commit 8a413cfe83b0a70dbd99c32d936334ca5788ca9b Merge: e07491de5 4e14710a6 Author: Matthew Patton <mpatton@enquizit.com> Date: Mon Oct 1 20:18:10 2018 -0400 Merge remote-tracking branch 'upstream/master' into prestine commit e07491de59cead0b337a7f57f4a6c625e1f560ab Merge: 42610a35d a1fa35dff Author: Matthew Patton <mpatton@enquizit.com> Date: Tue Aug 21 13:26:19 2018 -0400 Merge remote-tracking branch 'upstream/master' into prestine commit 42610a35d5ef65af8844a58ad70e2ec75262da6a Merge: 5298142da 0d63cf7bc Author: Matthew Patton <matthew.patton@itgfirm.com> Date: Tue Jun 19 22:45:05 2018 -0400 Merge remote-tracking branch 'upstream/master' into prestine commit 5298142da6da95354844f201deeeef3c599e48b2 Merge: 7bb110bc7 9d9736552 Author: Matthew Patton <mpatton@enquizit.com> Date: Mon Jun 11 15:10:09 2018 -0400 Merge remote-tracking branch 'upstream/master' into prestine commit 7bb110bc744c9797fcaec25a265d9b85a22d6d6b Merge: a61c869ca 6189d66e7 Author: Matthew Patton <matthew.patton@itgfirm.com> Date: Wed May 9 23:41:22 2018 -0400 Merge remote-tracking branch 'upstream/master' into prestine commit a61c869ca7268acf0e3b1e1fa7a8ee7feea65984 Merge: 098101dd9 4be5f072c Author: Matthew Patton <matthew.patton@itgfirm.com> Date: Fri May 4 10:13:04 2018 -0400 Merge remote-tracking branch 'upstream/master' into prestine commit 098101dd99f08b0ca110d33eff6904537c6d21de Merge: fefaf0fa6 554b2b4a5 Author: Matthew Patton <matthew.patton@itgfirm.com> Date: Tue May 1 20:52:30 2018 -0400 Merge branch 'EOL-handling' into prestine Co-Authored-By: Matthew Patton <pattonme@yahoo.com>
2018-12-12 09:45:00 -05:00
"github.com/hashicorp/packer/packer/tmp"
2017-04-04 16:39:01 -04:00
"github.com/hashicorp/packer/template/interpolate"
2015-03-10 00:11:57 -04:00
)
type Config struct {
common.PackerConfig `mapstructure:",squash"`
ctx interpolate.Context
// The command to run ansible
Command string
// Extra options to pass to the ansible command
ExtraArguments []string `mapstructure:"extra_arguments"`
AnsibleEnvVars []string `mapstructure:"ansible_env_vars"`
2015-03-10 00:11:57 -04:00
// The main playbook file to execute.
PlaybookFile string `mapstructure:"playbook_file"`
Groups []string `mapstructure:"groups"`
EmptyGroups []string `mapstructure:"empty_groups"`
HostAlias string `mapstructure:"host_alias"`
User string `mapstructure:"user"`
LocalPort uint `mapstructure:"local_port"`
SSHHostKeyFile string `mapstructure:"ssh_host_key_file"`
SSHAuthorizedKeyFile string `mapstructure:"ssh_authorized_key_file"`
SFTPCmd string `mapstructure:"sftp_command"`
2017-06-07 14:12:07 -04:00
SkipVersionCheck bool `mapstructure:"skip_version_check"`
UseSFTP bool `mapstructure:"use_sftp"`
InventoryDirectory string `mapstructure:"inventory_directory"`
2018-04-05 05:56:07 -04:00
InventoryFile string `mapstructure:"inventory_file"`
2015-03-10 00:11:57 -04:00
}
type Provisioner struct {
config Config
2019-02-12 02:10:57 -05:00
adapter *adapter.Adapter
done chan struct{}
ansibleVersion string
ansibleMajVersion uint
2015-03-10 00:11:57 -04:00
}
type PassthroughTemplate struct {
WinRMPassword string
}
2015-03-10 00:11:57 -04:00
func (p *Provisioner) Prepare(raws ...interface{}) error {
p.done = make(chan struct{})
// Create passthrough for winrm password so we can fill it in once we know
// it
p.config.ctx.Data = &PassthroughTemplate{
WinRMPassword: `{{.WinRMPassword}}`,
}
2015-03-10 00:11:57 -04:00
err := config.Decode(&p.config, &config.DecodeOpts{
Interpolate: true,
InterpolateContext: &p.config.ctx,
InterpolateFilter: &interpolate.RenderFilter{
Exclude: []string{},
},
}, raws...)
if err != nil {
return err
}
// Defaults
if p.config.Command == "" {
p.config.Command = "ansible-playbook"
}
if p.config.HostAlias == "" {
p.config.HostAlias = "default"
}
2015-03-10 00:11:57 -04:00
var errs *packer.MultiError
err = validateFileConfig(p.config.PlaybookFile, "playbook_file", true)
if err != nil {
errs = packer.MultiErrorAppend(errs, err)
}
// Check that the authorized key file exists
if len(p.config.SSHAuthorizedKeyFile) > 0 {
err = validateFileConfig(p.config.SSHAuthorizedKeyFile, "ssh_authorized_key_file", true)
if err != nil {
log.Println(p.config.SSHAuthorizedKeyFile, "does not exist")
errs = packer.MultiErrorAppend(errs, err)
}
2015-03-10 00:11:57 -04:00
}
if len(p.config.SSHHostKeyFile) > 0 {
err = validateFileConfig(p.config.SSHHostKeyFile, "ssh_host_key_file", true)
if err != nil {
log.Println(p.config.SSHHostKeyFile, "does not exist")
errs = packer.MultiErrorAppend(errs, err)
}
} else {
p.config.AnsibleEnvVars = append(p.config.AnsibleEnvVars, "ANSIBLE_HOST_KEY_CHECKING=False")
}
if !p.config.UseSFTP {
p.config.AnsibleEnvVars = append(p.config.AnsibleEnvVars, "ANSIBLE_SCP_IF_SSH=True")
2015-03-10 00:11:57 -04:00
}
if p.config.LocalPort > 65535 {
errs = packer.MultiErrorAppend(errs, fmt.Errorf("local_port: %d must be a valid port", p.config.LocalPort))
2015-03-10 00:11:57 -04:00
}
if len(p.config.InventoryDirectory) > 0 {
err = validateInventoryDirectoryConfig(p.config.InventoryDirectory)
if err != nil {
log.Println(p.config.InventoryDirectory, "does not exist")
errs = packer.MultiErrorAppend(errs, err)
}
}
2017-06-07 14:12:07 -04:00
if !p.config.SkipVersionCheck {
err = p.getVersion()
if err != nil {
errs = packer.MultiErrorAppend(errs, err)
}
}
if p.config.User == "" {
usr, err := user.Current()
if err != nil {
errs = packer.MultiErrorAppend(errs, err)
} else {
p.config.User = usr.Username
}
2016-02-26 16:16:22 -05:00
}
if p.config.User == "" {
errs = packer.MultiErrorAppend(errs, fmt.Errorf("user: could not determine current user from environment."))
}
2015-03-10 00:11:57 -04:00
if errs != nil && len(errs.Errors) > 0 {
return errs
}
return nil
}
func (p *Provisioner) getVersion() error {
out, err := exec.Command(p.config.Command, "--version").Output()
if err != nil {
return fmt.Errorf(
"Error running \"%s --version\": %s", p.config.Command, err.Error())
}
versionRe := regexp.MustCompile(`\w (\d+\.\d+[.\d+]*)`)
matches := versionRe.FindStringSubmatch(string(out))
if matches == nil {
return fmt.Errorf(
"Could not find %s version in output:\n%s", p.config.Command, string(out))
}
version := matches[1]
log.Printf("%s version: %s", p.config.Command, version)
p.ansibleVersion = version
majVer, err := strconv.ParseUint(strings.Split(version, ".")[0], 10, 0)
if err != nil {
return fmt.Errorf("Could not parse major version from \"%s\".", version)
}
p.ansibleMajVersion = uint(majVer)
return nil
}
2015-03-10 00:11:57 -04:00
func (p *Provisioner) Provision(ui packer.Ui, comm packer.Communicator) error {
ui.Say("Provisioning with Ansible...")
// Interpolate env vars to check for .WinRMPassword
p.config.ctx.Data = &PassthroughTemplate{
WinRMPassword: getWinRMPassword(p.config.PackerBuildName),
}
for i, envVar := range p.config.AnsibleEnvVars {
envVar, err := interpolate.Render(envVar, &p.config.ctx)
if err != nil {
return fmt.Errorf("Could not interpolate ansible env vars: %s", err)
}
p.config.AnsibleEnvVars[i] = envVar
}
// Interpolate extra vars to check for .WinRMPassword
for i, arg := range p.config.ExtraArguments {
arg, err := interpolate.Render(arg, &p.config.ctx)
if err != nil {
return fmt.Errorf("Could not interpolate ansible env vars: %s", err)
}
p.config.ExtraArguments[i] = arg
}
k, err := newUserKey(p.config.SSHAuthorizedKeyFile)
2015-03-10 00:11:57 -04:00
if err != nil {
return err
}
hostSigner, err := newSigner(p.config.SSHHostKeyFile)
// Remove the private key file
if len(k.privKeyFile) > 0 {
defer os.Remove(k.privKeyFile)
2015-03-10 00:11:57 -04:00
}
keyChecker := ssh.CertChecker{
UserKeyFallback: func(conn ssh.ConnMetadata, pubKey ssh.PublicKey) (*ssh.Permissions, error) {
if user := conn.User(); user != p.config.User {
return nil, errors.New(fmt.Sprintf("authentication failed: %s is not a valid user", user))
2015-03-10 00:11:57 -04:00
}
if !bytes.Equal(k.Marshal(), pubKey.Marshal()) {
return nil, errors.New("authentication failed: unauthorized key")
2015-03-10 00:11:57 -04:00
}
return nil, nil
},
}
2016-02-08 20:34:06 -05:00
2015-03-10 00:11:57 -04:00
config := &ssh.ServerConfig{
AuthLogCallback: func(conn ssh.ConnMetadata, method string, err error) {
log.Printf("authentication attempt from %s to %s as %s using %s", conn.RemoteAddr(), conn.LocalAddr(), conn.User(), method)
2015-03-10 00:11:57 -04:00
},
PublicKeyCallback: keyChecker.Authenticate,
//NoClientAuth: true,
}
config.AddHostKey(hostSigner)
2015-03-10 00:11:57 -04:00
localListener, err := func() (net.Listener, error) {
port := p.config.LocalPort
tries := 1
if port != 0 {
tries = 10
}
for i := 0; i < tries; i++ {
2015-03-10 00:11:57 -04:00
l, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", port))
port++
if err != nil {
ui.Say(err.Error())
continue
2015-03-10 00:11:57 -04:00
}
_, portStr, err := net.SplitHostPort(l.Addr().String())
if err != nil {
ui.Say(err.Error())
continue
}
portUint64, err := strconv.ParseUint(portStr, 10, 0)
if err != nil {
ui.Say(err.Error())
continue
}
p.config.LocalPort = uint(portUint64)
return l, nil
2015-03-10 00:11:57 -04:00
}
return nil, errors.New("Error setting up SSH proxy connection")
}()
if err != nil {
return err
}
ui = &packer.SafeUi{
Sem: make(chan int, 1),
Ui: ui,
}
2019-02-12 02:10:57 -05:00
p.adapter = adapter.NewAdapter(p.done, localListener, config, p.config.SFTPCmd, ui, comm)
2015-03-10 00:11:57 -04:00
defer func() {
log.Print("shutting down the SSH proxy")
2015-03-10 00:11:57 -04:00
close(p.done)
p.adapter.Shutdown()
}()
go p.adapter.Serve()
2018-04-05 05:56:07 -04:00
if len(p.config.InventoryFile) == 0 {
tf, err := ioutil.TempFile(p.config.InventoryDirectory, "packer-provisioner-ansible")
2015-03-10 00:11:57 -04:00
if err != nil {
return fmt.Errorf("Error preparing inventory file: %s", err)
}
defer os.Remove(tf.Name())
host := fmt.Sprintf("%s ansible_host=127.0.0.1 ansible_user=%s ansible_port=%d\n",
p.config.HostAlias, p.config.User, p.config.LocalPort)
if p.ansibleMajVersion < 2 {
host = fmt.Sprintf("%s ansible_ssh_host=127.0.0.1 ansible_ssh_user=%s ansible_ssh_port=%d\n",
p.config.HostAlias, p.config.User, p.config.LocalPort)
}
w := bufio.NewWriter(tf)
w.WriteString(host)
for _, group := range p.config.Groups {
fmt.Fprintf(w, "[%s]\n%s", group, host)
}
for _, group := range p.config.EmptyGroups {
fmt.Fprintf(w, "[%s]\n", group)
}
if err := w.Flush(); err != nil {
2015-03-10 00:11:57 -04:00
tf.Close()
return fmt.Errorf("Error preparing inventory file: %s", err)
}
tf.Close()
2018-04-05 05:56:07 -04:00
p.config.InventoryFile = tf.Name()
2015-03-10 00:11:57 -04:00
defer func() {
2018-04-05 05:56:07 -04:00
p.config.InventoryFile = ""
2015-03-10 00:11:57 -04:00
}()
}
if err := p.executeAnsible(ui, comm, k.privKeyFile); err != nil {
2015-03-10 00:11:57 -04:00
return fmt.Errorf("Error executing Ansible: %s", err)
}
return nil
}
func (p *Provisioner) Cancel() {
if p.done != nil {
close(p.done)
}
if p.adapter != nil {
p.adapter.Shutdown()
}
os.Exit(0)
}
func (p *Provisioner) executeAnsible(ui packer.Ui, comm packer.Communicator, privKeyFile string) error {
2015-03-10 00:11:57 -04:00
playbook, _ := filepath.Abs(p.config.PlaybookFile)
2018-04-05 05:56:07 -04:00
inventory := p.config.InventoryFile
var envvars []string
2015-03-10 00:11:57 -04:00
args := []string{"--extra-vars", fmt.Sprintf("packer_build_name=%s packer_builder_type=%s -o IdentitiesOnly=yes",
p.config.PackerBuildName, p.config.PackerBuilderType),
"-i", inventory, playbook}
if len(privKeyFile) > 0 {
2018-02-07 22:47:01 -05:00
// Changed this from using --private-key to supplying -e ansible_ssh_private_key_file as the latter
2018-02-07 22:41:01 -05:00
// is treated as a highest priority variable, and thus prevents overriding by dynamic variables
// as seen in #5852
// args = append(args, "--private-key", privKeyFile)
args = append(args, "-e", fmt.Sprintf("ansible_ssh_private_key_file=%s", privKeyFile))
}
// expose packer_http_addr extra variable
httpAddr := common.GetHTTPAddr()
if httpAddr != "" {
args = append(args, "--extra-vars", fmt.Sprintf("packer_http_addr=%s", httpAddr))
}
2015-03-10 00:11:57 -04:00
args = append(args, p.config.ExtraArguments...)
if len(p.config.AnsibleEnvVars) > 0 {
envvars = append(envvars, p.config.AnsibleEnvVars...)
}
2016-02-08 20:34:06 -05:00
2015-03-10 00:11:57 -04:00
cmd := exec.Command(p.config.Command, args...)
cmd.Env = os.Environ()
if len(envvars) > 0 {
cmd.Env = append(cmd.Env, envvars...)
}
2015-03-10 00:11:57 -04:00
stdout, err := cmd.StdoutPipe()
if err != nil {
return err
}
stderr, err := cmd.StderrPipe()
if err != nil {
return err
}
wg := sync.WaitGroup{}
repeat := func(r io.ReadCloser) {
reader := bufio.NewReader(r)
for {
line, err := reader.ReadString('\n')
if line != "" {
line = strings.TrimRightFunc(line, unicode.IsSpace)
ui.Message(line)
}
if err != nil {
if err == io.EOF {
break
} else {
ui.Error(err.Error())
break
}
}
2015-03-10 00:11:57 -04:00
}
wg.Done()
}
wg.Add(2)
go repeat(stdout)
go repeat(stderr)
// remove winrm password from command, if it's been added
flattenedCmd := strings.Join(cmd.Args, " ")
sanitized := flattenedCmd
if len(getWinRMPassword(p.config.PackerBuildName)) > 0 {
sanitized = strings.Replace(sanitized,
getWinRMPassword(p.config.PackerBuildName), "*****", -1)
}
ui.Say(fmt.Sprintf("Executing Ansible: %s", sanitized))
2017-03-29 16:38:31 -04:00
if err := cmd.Start(); err != nil {
return err
}
2015-03-10 00:11:57 -04:00
wg.Wait()
err = cmd.Wait()
if err != nil {
return fmt.Errorf("Non-zero exit status: %s", err)
}
return nil
}
func validateFileConfig(name string, config string, req bool) error {
if req {
if name == "" {
return fmt.Errorf("%s must be specified.", config)
}
}
info, err := os.Stat(name)
if err != nil {
return fmt.Errorf("%s: %s is invalid: %s", config, name, err)
} else if info.IsDir() {
return fmt.Errorf("%s: %s must point to a file", config, name)
}
return nil
}
func validateInventoryDirectoryConfig(name string) error {
info, err := os.Stat(name)
if err != nil {
return fmt.Errorf("inventory_directory: %s is invalid: %s", name, err)
} else if !info.IsDir() {
return fmt.Errorf("inventory_directory: %s must point to a directory", name)
}
return nil
}
type userKey struct {
ssh.PublicKey
privKeyFile string
}
func newUserKey(pubKeyFile string) (*userKey, error) {
userKey := new(userKey)
if len(pubKeyFile) > 0 {
pubKeyBytes, err := ioutil.ReadFile(pubKeyFile)
if err != nil {
return nil, errors.New("Failed to read public key")
}
userKey.PublicKey, _, _, _, err = ssh.ParseAuthorizedKey(pubKeyBytes)
if err != nil {
return nil, errors.New("Failed to parse authorized key")
}
return userKey, nil
}
key, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return nil, errors.New("Failed to generate key pair")
}
userKey.PublicKey, err = ssh.NewPublicKey(key.Public())
if err != nil {
return nil, errors.New("Failed to extract public key from generated key pair")
}
// To support Ansible calling back to us we need to write
// this file down
privateKeyDer := x509.MarshalPKCS1PrivateKey(key)
privateKeyBlock := pem.Block{
Type: "RSA PRIVATE KEY",
Headers: nil,
Bytes: privateKeyDer,
}
Add tmp package that offers Dir & File funcs this regroups the calls of tmp func calls into one package. the tmp pkg allows to store tmp files under a common directory for easier managment Squashed commit of the following: commit 74b674c01560c6b547e9cab5e8afb486f0fe7d6c Merge: fc94b5714 66001525d Author: Matthew Patton <mpatton@enquizit.com> Date: Fri Nov 2 02:02:38 2018 -0400 Merge branch 'remove_TMPDIR_docs' of github.com:tb3088/packer into remove_TMPDIR_docs commit fc94b571428447aaf2e5171967c95cdf9e5c73ff Author: Matthew Patton <mpatton@enquizit.com> Date: Fri Nov 2 01:42:38 2018 -0400 update tests to honor configured temporary directory commit 5a562359f4937af506607dd96ed1c46426093f52 Author: Matthew Patton <mpatton@enquizit.com> Date: Thu Nov 1 18:52:38 2018 -0400 sync straggler to refactor. implement tests at packer/configfile instead of buried in docker. commit 9d5a4a0935bfd049e2f8f50ad73e4455b42c9410 Author: Matthew Patton <mpatton@enquizit.com> Date: Thu Nov 1 15:39:46 2018 -0400 insert URL to GoLang API for os.TempDir() commit fbae4c2e051898aecd8705e9d8a20353430ede23 Author: Matthew Patton <mpatton@enquizit.com> Date: Thu Nov 1 07:41:29 2018 -0400 revise documentation to match code commit 3590fae8bd0afa92a161a49ed794ee32e357d583 Author: Matthew Patton <mpatton@enquizit.com> Date: Thu Nov 1 07:21:59 2018 -0400 refacter config_file. replace all hard-coded os.TempDir with wrapper commit d5c5306a97b648ded06a8eb76ce728f07c9924f0 Author: Matthew Patton <mpatton@enquizit.com> Date: Wed Oct 31 20:11:36 2018 -0400 close massive file overwrite hole with TempDir commit 0a72297da86089fbd07e4f7d9472a92fa4d1c733 Author: Matthew Patton <mpatton@enquizit.com> Date: Wed Oct 31 01:06:00 2018 -0400 adjust var declaration scope commit 20f68228b6c372d984ea5b055cfc8bda9b110ac5 Author: Matthew Patton <mpatton@enquizit.com> Date: Wed Oct 31 00:54:35 2018 -0400 use mktemp() equivalent to create temporary directory commit c73ebe3d8321664a2685a0baa8e441dd895b0db4 Author: Matthew Patton <mpatton@enquizit.com> Date: Tue Oct 30 20:40:58 2018 -0400 remove extraneous variable declaration, fix FOR loop commit 63549b8bd745a0090b15ed0b0ebf644162db27db Author: Matthew Patton <mpatton@enquizit.com> Date: Tue Oct 30 19:30:44 2018 -0400 match styistic convension with rest of docs commit 976101074942db36f10d3a686d6d29ddb7c01926 Author: Matthew Patton <mpatton@enquizit.com> Date: Tue Oct 30 19:08:39 2018 -0400 revert dangling config file change commit 95159afbc05eac96ed11c3183af5fb0abe2f2d5c Author: Matthew Patton <matthew.patton@itgfirm.com> Date: Fri Dec 29 23:53:43 2017 -0500 replace invalid TMPDIR variable wth PACKER_TMP_DIR. update ConfigTmpDir() to try common temporary paths first and only write to configDir() as a last resort. commit 66001525d72de56a4cf9339b900c46f59bc6e91a Author: Matthew Patton <mpatton@enquizit.com> Date: Fri Nov 2 01:42:38 2018 -0400 update tests to honor configured temporary directory commit e9b6adefeae8c65eb8aa47fef38cbf0aa424338c Author: Matthew Patton <mpatton@enquizit.com> Date: Thu Nov 1 18:52:38 2018 -0400 sync straggler to refactor. implement tests at packer/configfile instead of buried in docker. commit 852113ed076e2d14e5dca6815ea680da1e2896bb Author: Matthew Patton <mpatton@enquizit.com> Date: Thu Nov 1 15:39:46 2018 -0400 insert URL to GoLang API for os.TempDir() commit 54add38d1d1c6e283cd444b367ed8bd49a5f3699 Author: Matthew Patton <mpatton@enquizit.com> Date: Thu Nov 1 07:41:29 2018 -0400 revise documentation to match code commit 6b5b8f6d4edad0e187ca13d64ac4118f34eee643 Author: Matthew Patton <mpatton@enquizit.com> Date: Thu Nov 1 07:21:59 2018 -0400 refacter config_file. replace all hard-coded os.TempDir with wrapper commit c22092c601c33484327674f322c7379fa41506d7 Author: Matthew Patton <mpatton@enquizit.com> Date: Wed Oct 31 20:11:36 2018 -0400 close massive file overwrite hole with TempDir commit 7a730450916bf8e5dbc2a741ec233a49466ab7cc Author: Matthew Patton <mpatton@enquizit.com> Date: Wed Oct 31 01:06:00 2018 -0400 adjust var declaration scope commit 0f2933adb6f6922dfeab78a95371a444ec8918ab Author: Matthew Patton <mpatton@enquizit.com> Date: Wed Oct 31 00:54:35 2018 -0400 use mktemp() equivalent to create temporary directory commit d74839ede05dacf712b55a7bb48aec19fe6b007f Author: Matthew Patton <mpatton@enquizit.com> Date: Tue Oct 30 20:40:58 2018 -0400 remove extraneous variable declaration, fix FOR loop commit eb65416619437e4a3dec90277770803dd5b2281c Author: Matthew Patton <mpatton@enquizit.com> Date: Tue Oct 30 19:30:44 2018 -0400 match styistic convension with rest of docs commit acaa2b31ed463219c4ef099f351eec72406e2989 Author: Matthew Patton <mpatton@enquizit.com> Date: Tue Oct 30 19:08:39 2018 -0400 revert dangling config file change commit e573fde668dcb418561e61535c1d68b2888f5b0f Author: Matthew Patton <matthew.patton@itgfirm.com> Date: Fri Dec 29 23:53:43 2017 -0500 replace invalid TMPDIR variable wth PACKER_TMP_DIR. update ConfigTmpDir() to try common temporary paths first and only write to configDir() as a last resort. commit 39a9874afc9dea71b36753375fb7feb61ffecf69 Merge: 8a413cfe8 3315812c2 Author: Matthew Patton <mpatton@enquizit.com> Date: Tue Oct 30 18:19:26 2018 -0400 Merge branch 'master' of https://github.com/hashicorp/packer into prestine commit 8a413cfe83b0a70dbd99c32d936334ca5788ca9b Merge: e07491de5 4e14710a6 Author: Matthew Patton <mpatton@enquizit.com> Date: Mon Oct 1 20:18:10 2018 -0400 Merge remote-tracking branch 'upstream/master' into prestine commit e07491de59cead0b337a7f57f4a6c625e1f560ab Merge: 42610a35d a1fa35dff Author: Matthew Patton <mpatton@enquizit.com> Date: Tue Aug 21 13:26:19 2018 -0400 Merge remote-tracking branch 'upstream/master' into prestine commit 42610a35d5ef65af8844a58ad70e2ec75262da6a Merge: 5298142da 0d63cf7bc Author: Matthew Patton <matthew.patton@itgfirm.com> Date: Tue Jun 19 22:45:05 2018 -0400 Merge remote-tracking branch 'upstream/master' into prestine commit 5298142da6da95354844f201deeeef3c599e48b2 Merge: 7bb110bc7 9d9736552 Author: Matthew Patton <mpatton@enquizit.com> Date: Mon Jun 11 15:10:09 2018 -0400 Merge remote-tracking branch 'upstream/master' into prestine commit 7bb110bc744c9797fcaec25a265d9b85a22d6d6b Merge: a61c869ca 6189d66e7 Author: Matthew Patton <matthew.patton@itgfirm.com> Date: Wed May 9 23:41:22 2018 -0400 Merge remote-tracking branch 'upstream/master' into prestine commit a61c869ca7268acf0e3b1e1fa7a8ee7feea65984 Merge: 098101dd9 4be5f072c Author: Matthew Patton <matthew.patton@itgfirm.com> Date: Fri May 4 10:13:04 2018 -0400 Merge remote-tracking branch 'upstream/master' into prestine commit 098101dd99f08b0ca110d33eff6904537c6d21de Merge: fefaf0fa6 554b2b4a5 Author: Matthew Patton <matthew.patton@itgfirm.com> Date: Tue May 1 20:52:30 2018 -0400 Merge branch 'EOL-handling' into prestine Co-Authored-By: Matthew Patton <pattonme@yahoo.com>
2018-12-12 09:45:00 -05:00
tf, err := tmp.File("ansible-key")
if err != nil {
return nil, errors.New("failed to create temp file for generated key")
}
_, err = tf.Write(pem.EncodeToMemory(&privateKeyBlock))
if err != nil {
return nil, errors.New("failed to write private key to temp file")
}
err = tf.Close()
if err != nil {
return nil, errors.New("failed to close private key temp file")
}
userKey.privKeyFile = tf.Name()
return userKey, nil
}
type signer struct {
ssh.Signer
}
func newSigner(privKeyFile string) (*signer, error) {
signer := new(signer)
if len(privKeyFile) > 0 {
privateBytes, err := ioutil.ReadFile(privKeyFile)
if err != nil {
return nil, errors.New("Failed to load private host key")
}
signer.Signer, err = ssh.ParsePrivateKey(privateBytes)
if err != nil {
return nil, errors.New("Failed to parse private host key")
}
return signer, nil
}
key, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return nil, errors.New("Failed to generate server key pair")
}
signer.Signer, err = ssh.NewSignerFromKey(key)
if err != nil {
return nil, errors.New("Failed to extract private key from generated key pair")
}
return signer, nil
}
func getWinRMPassword(buildName string) string {
winRMPass, _ := commonhelper.RetrieveSharedState("winrm_password", buildName)
packer.LogSecretFilter.Set(winRMPass)
return winRMPass
}