2019-10-14 10:43:59 -04:00
|
|
|
//go:generate mapstructure-to-hcl2 -type Config
|
|
|
|
|
2015-03-10 00:11:57 -04:00
|
|
|
package ansible
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bufio"
|
|
|
|
"bytes"
|
2019-03-19 13:11:19 -04:00
|
|
|
"context"
|
2016-02-04 21:40:17 -05:00
|
|
|
"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"
|
2018-01-03 02:33:32 -05:00
|
|
|
"os/user"
|
2015-03-10 00:11:57 -04:00
|
|
|
"path/filepath"
|
2016-03-01 13:35:48 -05:00
|
|
|
"regexp"
|
2015-03-10 00:11:57 -04:00
|
|
|
"strconv"
|
|
|
|
"strings"
|
|
|
|
"sync"
|
2016-02-27 01:20:54 -05:00
|
|
|
"unicode"
|
2015-03-10 00:11:57 -04:00
|
|
|
|
|
|
|
"golang.org/x/crypto/ssh"
|
|
|
|
|
2019-12-17 05:25:56 -05:00
|
|
|
"github.com/hashicorp/hcl/v2/hcldec"
|
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"
|
2017-04-04 16:39:01 -04:00
|
|
|
"github.com/hashicorp/packer/helper/config"
|
|
|
|
"github.com/hashicorp/packer/packer"
|
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"`
|
|
|
|
|
2016-02-14 19:07:02 -05:00
|
|
|
AnsibleEnvVars []string `mapstructure:"ansible_env_vars"`
|
|
|
|
|
2015-03-10 00:11:57 -04:00
|
|
|
// The main playbook file to execute.
|
2016-02-11 01:24:12 -05:00
|
|
|
PlaybookFile string `mapstructure:"playbook_file"`
|
|
|
|
Groups []string `mapstructure:"groups"`
|
2016-02-19 17:43:29 -05:00
|
|
|
EmptyGroups []string `mapstructure:"empty_groups"`
|
2016-02-11 01:24:12 -05:00
|
|
|
HostAlias string `mapstructure:"host_alias"`
|
2016-02-26 15:50:50 -05:00
|
|
|
User string `mapstructure:"user"`
|
2019-03-19 09:47:21 -04:00
|
|
|
LocalPort int `mapstructure:"local_port"`
|
2016-02-11 01:24:12 -05:00
|
|
|
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"`
|
2016-09-12 02:29:24 -04:00
|
|
|
UseSFTP bool `mapstructure:"use_sftp"`
|
2017-04-04 17:43:46 -04:00
|
|
|
InventoryDirectory string `mapstructure:"inventory_directory"`
|
2018-04-05 05:56:07 -04:00
|
|
|
InventoryFile string `mapstructure:"inventory_file"`
|
2020-03-31 15:54:20 -04:00
|
|
|
KeepInventoryFile bool `mapstructure:"keep_inventory_file"`
|
2019-07-26 12:44:40 -04:00
|
|
|
GalaxyFile string `mapstructure:"galaxy_file"`
|
|
|
|
GalaxyCommand string `mapstructure:"galaxy_command"`
|
|
|
|
GalaxyForceInstall bool `mapstructure:"galaxy_force_install"`
|
2019-07-27 07:56:14 -04:00
|
|
|
RolesPath string `mapstructure:"roles_path"`
|
2020-02-04 13:42:55 -05:00
|
|
|
//TODO: change default to false in v1.6.0.
|
|
|
|
UseProxy config.Trilean `mapstructure:"use_proxy"`
|
|
|
|
userWasEmpty bool
|
2015-03-10 00:11:57 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
type Provisioner struct {
|
2016-03-01 13:35:48 -05:00
|
|
|
config Config
|
2019-02-12 02:10:57 -05:00
|
|
|
adapter *adapter.Adapter
|
2016-03-01 13:35:48 -05:00
|
|
|
done chan struct{}
|
|
|
|
ansibleVersion string
|
|
|
|
ansibleMajVersion uint
|
2019-12-12 19:42:53 -05:00
|
|
|
generatedData map[string]interface{}
|
2020-02-04 13:42:55 -05:00
|
|
|
|
|
|
|
setupAdapterFunc func(ui packer.Ui, comm packer.Communicator) (string, error)
|
|
|
|
executeAnsibleFunc func(ui packer.Ui, comm packer.Communicator, privKeyFile string) error
|
2018-07-17 15:52:32 -04:00
|
|
|
}
|
|
|
|
|
2019-12-17 05:25:56 -05:00
|
|
|
func (p *Provisioner) ConfigSpec() hcldec.ObjectSpec { return p.config.FlatMapstructure().HCL2Spec() }
|
|
|
|
|
2015-03-10 00:11:57 -04:00
|
|
|
func (p *Provisioner) Prepare(raws ...interface{}) error {
|
|
|
|
p.done = make(chan struct{})
|
|
|
|
|
|
|
|
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"
|
|
|
|
}
|
|
|
|
|
2019-07-26 12:44:40 -04:00
|
|
|
if p.config.GalaxyCommand == "" {
|
|
|
|
p.config.GalaxyCommand = "ansible-galaxy"
|
|
|
|
}
|
|
|
|
|
2016-02-11 01:24:12 -05:00
|
|
|
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)
|
|
|
|
}
|
|
|
|
|
2019-07-26 12:44:40 -04:00
|
|
|
// Check that the galaxy file exists, if configured
|
|
|
|
if len(p.config.GalaxyFile) > 0 {
|
|
|
|
err = validateFileConfig(p.config.GalaxyFile, "galaxy_file", true)
|
|
|
|
if err != nil {
|
|
|
|
errs = packer.MultiErrorAppend(errs, err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-02-06 21:09:15 -05:00
|
|
|
// Check that the authorized key file exists
|
2016-02-04 21:40:17 -05:00
|
|
|
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)
|
|
|
|
}
|
2016-09-12 02:29:24 -04:00
|
|
|
} 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
|
|
|
}
|
|
|
|
|
2019-02-04 12:47:42 -05: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
|
|
|
}
|
|
|
|
|
2017-04-04 23:49:24 -04:00
|
|
|
if len(p.config.InventoryDirectory) > 0 {
|
2017-04-06 15:50:02 -04:00
|
|
|
err = validateInventoryDirectoryConfig(p.config.InventoryDirectory)
|
2017-04-04 23:49:24 -04:00
|
|
|
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)
|
|
|
|
}
|
2016-03-01 13:35:48 -05:00
|
|
|
}
|
|
|
|
|
2016-02-26 15:50:50 -05:00
|
|
|
if p.config.User == "" {
|
2020-02-04 13:42:55 -05:00
|
|
|
p.config.userWasEmpty = true
|
2018-01-03 02:33:32 -05:00
|
|
|
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."))
|
2016-02-26 15:50:50 -05:00
|
|
|
}
|
|
|
|
|
2020-02-04 13:42:55 -05:00
|
|
|
// These fields exist so that we can replace the functions for testing
|
|
|
|
// logic inside of the Provision func; in actual use, these don't ever
|
|
|
|
// need to get set.
|
|
|
|
if p.setupAdapterFunc == nil {
|
|
|
|
p.setupAdapterFunc = p.setupAdapter
|
|
|
|
}
|
|
|
|
if p.executeAnsibleFunc == nil {
|
|
|
|
p.executeAnsibleFunc = p.executeAnsible
|
|
|
|
}
|
|
|
|
|
2015-03-10 00:11:57 -04:00
|
|
|
if errs != nil && len(errs.Errors) > 0 {
|
|
|
|
return errs
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2016-03-01 13:35:48 -05:00
|
|
|
func (p *Provisioner) getVersion() error {
|
|
|
|
out, err := exec.Command(p.config.Command, "--version").Output()
|
|
|
|
if err != nil {
|
2017-03-21 23:26:41 -04:00
|
|
|
return fmt.Errorf(
|
|
|
|
"Error running \"%s --version\": %s", p.config.Command, err.Error())
|
2016-03-01 13:35:48 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
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
|
|
|
|
}
|
|
|
|
|
2020-02-04 13:42:55 -05:00
|
|
|
func (p *Provisioner) setupAdapter(ui packer.Ui, comm packer.Communicator) (string, error) {
|
|
|
|
ui.Message("Setting up proxy adapter for Ansible....")
|
2018-07-02 20:42:21 -04:00
|
|
|
|
2016-02-06 21:09:15 -05:00
|
|
|
k, err := newUserKey(p.config.SSHAuthorizedKeyFile)
|
2015-03-10 00:11:57 -04:00
|
|
|
if err != nil {
|
2020-02-04 13:42:55 -05:00
|
|
|
return "", err
|
2016-02-04 21:40:17 -05:00
|
|
|
}
|
|
|
|
|
2016-02-06 21:09:15 -05:00
|
|
|
hostSigner, err := newSigner(p.config.SSHHostKeyFile)
|
2019-08-27 19:52:52 -04:00
|
|
|
if err != nil {
|
2020-02-04 13:42:55 -05:00
|
|
|
return "", fmt.Errorf("error creating host signer: %s", err)
|
2015-03-10 00:11:57 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
keyChecker := ssh.CertChecker{
|
|
|
|
UserKeyFallback: func(conn ssh.ConnMetadata, pubKey ssh.PublicKey) (*ssh.Permissions, error) {
|
2016-02-26 15:50:50 -05:00
|
|
|
if user := conn.User(); user != p.config.User {
|
2016-11-05 09:25:45 -04:00
|
|
|
return nil, errors.New(fmt.Sprintf("authentication failed: %s is not a valid user", user))
|
2015-03-10 00:11:57 -04:00
|
|
|
}
|
|
|
|
|
2016-02-06 21:09:15 -05:00
|
|
|
if !bytes.Equal(k.Marshal(), pubKey.Marshal()) {
|
2016-11-05 09:25:45 -04:00
|
|
|
return nil, errors.New("authentication failed: unauthorized key")
|
2015-03-10 00:11:57 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
return nil, nil
|
|
|
|
},
|
2019-06-11 16:22:03 -04:00
|
|
|
IsUserAuthority: func(k ssh.PublicKey) bool { return true },
|
2015-03-10 00:11:57 -04:00
|
|
|
}
|
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) {
|
2016-11-05 09:25:45 -04:00
|
|
|
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,
|
|
|
|
}
|
|
|
|
|
2016-02-06 21:09:15 -05:00
|
|
|
config.AddHostKey(hostSigner)
|
2015-03-10 00:11:57 -04:00
|
|
|
|
|
|
|
localListener, err := func() (net.Listener, error) {
|
2016-01-29 01:22:12 -05:00
|
|
|
|
2019-02-04 12:47:42 -05:00
|
|
|
port := p.config.LocalPort
|
2016-01-29 01:22:12 -05:00
|
|
|
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))
|
2016-01-29 01:22:12 -05:00
|
|
|
port++
|
|
|
|
if err != nil {
|
|
|
|
ui.Say(err.Error())
|
|
|
|
continue
|
2015-03-10 00:11:57 -04:00
|
|
|
}
|
2019-02-04 12:47:42 -05:00
|
|
|
_, portStr, err := net.SplitHostPort(l.Addr().String())
|
|
|
|
if err != nil {
|
|
|
|
ui.Say(err.Error())
|
|
|
|
continue
|
|
|
|
}
|
2019-03-19 09:47:21 -04:00
|
|
|
p.config.LocalPort, err = strconv.Atoi(portStr)
|
2016-01-29 01:22:12 -05:00
|
|
|
if err != nil {
|
|
|
|
ui.Say(err.Error())
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
return l, nil
|
2015-03-10 00:11:57 -04:00
|
|
|
}
|
|
|
|
return nil, errors.New("Error setting up SSH proxy connection")
|
|
|
|
}()
|
|
|
|
|
|
|
|
if err != nil {
|
2020-02-04 13:42:55 -05:00
|
|
|
return "", err
|
2015-03-10 00:11:57 -04:00
|
|
|
}
|
|
|
|
|
2019-02-13 16:01:50 -05:00
|
|
|
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
|
|
|
|
2020-02-04 13:42:55 -05:00
|
|
|
return k.privKeyFile, nil
|
|
|
|
}
|
|
|
|
|
2020-03-31 15:54:20 -04:00
|
|
|
// ansible_user: LocalUsername
|
|
|
|
// ansible_password: Password
|
|
|
|
// ansible_connection: winrm
|
|
|
|
// ansible_winrm_transport: basic
|
|
|
|
|
2020-03-27 19:44:41 -04:00
|
|
|
const DefaultSSHInventoryFilev2 = "{{ .HostAlias }} ansible_host={{ .Host }} ansible_user={{ .User }} ansible_port={{ .Port }}\n"
|
|
|
|
const DefaultSSHInventoryFilev1 = "{{ .HostAlias }} ansible_ssh_host={{ .Host }} ansible_ssh_user={{ .User }} ansible_ssh_port={{ .Port }}\n"
|
2020-03-31 15:54:20 -04:00
|
|
|
const DefaultWinRMInventoryFilev2 = "{{ .HostAlias}} ansible_host={{ .Host }} ansible_connection=winrm ansible_winrm_transport=basic ansible_shell_type=powershell ansible_user={{ .User}} ansible_port={{ .Port }}\n"
|
2020-03-27 18:59:14 -04:00
|
|
|
|
|
|
|
func (p *Provisioner) createInventoryFile() error {
|
2020-02-04 13:42:55 -05:00
|
|
|
log.Printf("Creating inventory file for Ansible run...")
|
|
|
|
tf, err := ioutil.TempFile(p.config.InventoryDirectory, "packer-provisioner-ansible")
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("Error preparing inventory file: %s", err)
|
|
|
|
}
|
2020-03-27 18:59:14 -04:00
|
|
|
|
|
|
|
// figure out which inventory line template to use
|
|
|
|
hostTemplate := DefaultSSHInventoryFilev2
|
2020-02-04 13:42:55 -05:00
|
|
|
if p.ansibleMajVersion < 2 {
|
2020-03-27 18:59:14 -04:00
|
|
|
hostTemplate = DefaultSSHInventoryFilev1
|
|
|
|
}
|
|
|
|
if p.config.UseProxy.False() && p.generatedData["ConnType"] == "winrm" {
|
|
|
|
hostTemplate = DefaultWinRMInventoryFilev2
|
|
|
|
}
|
|
|
|
|
|
|
|
// interpolate template to generate host with necessary vars.
|
|
|
|
ctxData := p.generatedData
|
|
|
|
ctxData["HostAlias"] = p.config.HostAlias
|
|
|
|
ctxData["User"] = p.config.User
|
|
|
|
if !p.config.UseProxy.False() {
|
|
|
|
ctxData["Host"] = "127.0.0.1"
|
|
|
|
ctxData["Port"] = p.config.LocalPort
|
|
|
|
}
|
|
|
|
p.config.ctx.Data = ctxData
|
|
|
|
|
|
|
|
host, err := interpolate.Render(hostTemplate, &p.config.ctx)
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("Error generating inventory file from template: %s", err)
|
2020-02-04 13:42:55 -05:00
|
|
|
}
|
2015-03-10 00:11:57 -04:00
|
|
|
|
2020-02-04 13:42:55 -05:00
|
|
|
w := bufio.NewWriter(tf)
|
|
|
|
w.WriteString(host)
|
2015-03-10 00:11:57 -04:00
|
|
|
|
2020-02-04 13:42:55 -05:00
|
|
|
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 {
|
|
|
|
tf.Close()
|
|
|
|
os.Remove(tf.Name())
|
|
|
|
return fmt.Errorf("Error preparing inventory file: %s", err)
|
|
|
|
}
|
|
|
|
tf.Close()
|
|
|
|
p.config.InventoryFile = tf.Name()
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (p *Provisioner) Provision(ctx context.Context, ui packer.Ui, comm packer.Communicator, generatedData map[string]interface{}) error {
|
|
|
|
ui.Say("Provisioning with Ansible...")
|
|
|
|
// Interpolate env vars to check for generated values like password and port
|
|
|
|
p.generatedData = generatedData
|
|
|
|
p.config.ctx.Data = generatedData
|
|
|
|
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 generated values like password and port
|
|
|
|
for i, arg := range p.config.ExtraArguments {
|
|
|
|
arg, err := interpolate.Render(arg, &p.config.ctx)
|
2015-03-10 00:11:57 -04:00
|
|
|
if err != nil {
|
2020-02-04 13:42:55 -05:00
|
|
|
return fmt.Errorf("Could not interpolate ansible env vars: %s", err)
|
2015-03-10 00:11:57 -04:00
|
|
|
}
|
2020-02-04 13:42:55 -05:00
|
|
|
p.config.ExtraArguments[i] = arg
|
|
|
|
}
|
|
|
|
|
2020-03-27 18:59:14 -04:00
|
|
|
// Set up proxy if host IP is missing or communicator type is wrong.
|
|
|
|
if p.config.UseProxy.False() {
|
|
|
|
hostIP := generatedData["Host"].(string)
|
|
|
|
if hostIP == "" {
|
|
|
|
ui.Error("Warning: use_proxy is false, but instance does" +
|
|
|
|
" not have an IP address to give to Ansible. Falling back" +
|
|
|
|
" to use localhost proxy.")
|
|
|
|
p.config.UseProxy = config.TriTrue
|
|
|
|
}
|
|
|
|
connType := generatedData["ConnType"]
|
|
|
|
if connType != "ssh" && connType != "winrm" {
|
|
|
|
ui.Error("Warning: use_proxy is false, but communicator is " +
|
|
|
|
"neither ssh nor winrm, so without the proxy ansible will not" +
|
|
|
|
" function. Falling back to localhost proxy.")
|
|
|
|
p.config.UseProxy = config.TriTrue
|
|
|
|
}
|
2020-02-04 13:42:55 -05:00
|
|
|
}
|
2016-02-11 01:24:12 -05:00
|
|
|
|
2020-02-04 13:42:55 -05:00
|
|
|
privKeyFile := ""
|
|
|
|
if !p.config.UseProxy.False() {
|
|
|
|
// We set up the proxy if useProxy is either true or unset.
|
|
|
|
pkf, err := p.setupAdapterFunc(ui, comm)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
2016-03-01 13:35:48 -05:00
|
|
|
}
|
2020-02-04 13:42:55 -05:00
|
|
|
// This is necessary to avoid accidentally redeclaring
|
|
|
|
// privKeyFile in the scope of this if statement.
|
|
|
|
privKeyFile = pkf
|
|
|
|
|
|
|
|
defer func() {
|
|
|
|
log.Print("shutting down the SSH proxy")
|
|
|
|
close(p.done)
|
|
|
|
p.adapter.Shutdown()
|
|
|
|
}()
|
|
|
|
|
|
|
|
go p.adapter.Serve()
|
2016-02-11 01:24:12 -05:00
|
|
|
|
2020-02-04 13:42:55 -05:00
|
|
|
// Remove the private key file
|
|
|
|
if len(privKeyFile) > 0 {
|
|
|
|
defer os.Remove(privKeyFile)
|
2016-02-11 01:24:12 -05:00
|
|
|
}
|
2020-02-04 13:42:55 -05:00
|
|
|
} else {
|
2020-03-27 18:59:14 -04:00
|
|
|
connType := generatedData["ConnType"].(string)
|
|
|
|
switch connType {
|
|
|
|
case "ssh":
|
|
|
|
ui.Message("Not using Proxy adapter for Ansible run:\n" +
|
|
|
|
"\tUsing ssh keys from Packer communicator...")
|
|
|
|
// In this situation, we need to make sure we have the
|
|
|
|
// private key we actually use to access the instance.
|
|
|
|
SSHPrivateKeyFile := generatedData["SSHPrivateKeyFile"].(string)
|
|
|
|
if SSHPrivateKeyFile != "" {
|
|
|
|
privKeyFile = SSHPrivateKeyFile
|
|
|
|
} else {
|
|
|
|
// See if we can get a private key and write that to a tmpfile
|
2020-03-27 19:44:41 -04:00
|
|
|
SSHPrivateKey := generatedData["SSHPrivateKey"].(string)
|
2020-03-27 18:59:14 -04:00
|
|
|
tmpSSHPrivateKey, err := tmp.File("ansible-key")
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("Error writing private key to temp file for"+
|
|
|
|
"ansible connection: %v", err)
|
|
|
|
}
|
2020-03-27 19:44:41 -04:00
|
|
|
_, err = tmpSSHPrivateKey.WriteString(SSHPrivateKey)
|
2020-03-27 18:59:14 -04:00
|
|
|
if err != nil {
|
|
|
|
return errors.New("failed to write private key to temp file")
|
|
|
|
}
|
|
|
|
err = tmpSSHPrivateKey.Close()
|
|
|
|
if err != nil {
|
|
|
|
return errors.New("failed to close private key temp file")
|
|
|
|
}
|
|
|
|
privKeyFile = tmpSSHPrivateKey.Name()
|
2020-02-04 13:42:55 -05:00
|
|
|
}
|
|
|
|
|
2020-03-27 18:59:14 -04:00
|
|
|
// Also make sure that the username matches the SSH keys given.
|
|
|
|
if p.config.userWasEmpty {
|
|
|
|
p.config.User = generatedData["User"].(string)
|
|
|
|
}
|
|
|
|
case "winrm":
|
|
|
|
ui.Message("Not using Proxy adapter for Ansible run:\n" +
|
|
|
|
"\tUsing WinRM Password from Packer communicator...")
|
2020-02-04 13:42:55 -05:00
|
|
|
}
|
|
|
|
}
|
2016-02-11 01:24:12 -05:00
|
|
|
|
2020-02-04 13:42:55 -05:00
|
|
|
if len(p.config.InventoryFile) == 0 {
|
|
|
|
// Create the inventory file
|
2020-03-27 18:59:14 -04:00
|
|
|
err := p.createInventoryFile()
|
2020-02-04 13:42:55 -05:00
|
|
|
if err != nil {
|
|
|
|
return err
|
2015-03-10 00:11:57 -04:00
|
|
|
}
|
2020-03-31 15:54:20 -04:00
|
|
|
if !p.config.KeepInventoryFile {
|
|
|
|
// Delete the generated inventory file
|
|
|
|
defer func() {
|
|
|
|
os.Remove(p.config.InventoryFile)
|
|
|
|
p.config.InventoryFile = ""
|
|
|
|
}()
|
|
|
|
}
|
2015-03-10 00:11:57 -04:00
|
|
|
}
|
|
|
|
|
2020-02-04 13:42:55 -05:00
|
|
|
if err := p.executeAnsibleFunc(ui, comm, privKeyFile); err != nil {
|
2015-03-10 00:11:57 -04:00
|
|
|
return fmt.Errorf("Error executing Ansible: %s", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2019-07-26 12:44:40 -04:00
|
|
|
func (p *Provisioner) executeGalaxy(ui packer.Ui, comm packer.Communicator) error {
|
|
|
|
galaxyFile := filepath.ToSlash(p.config.GalaxyFile)
|
|
|
|
|
2019-07-27 07:56:14 -04:00
|
|
|
// ansible-galaxy install -r requirements.yml
|
|
|
|
args := []string{"install", "-r", galaxyFile}
|
2019-07-26 12:44:40 -04:00
|
|
|
// Add force to arguments
|
|
|
|
if p.config.GalaxyForceInstall {
|
|
|
|
args = append(args, "-f")
|
|
|
|
}
|
2019-07-27 07:56:14 -04:00
|
|
|
// Add roles_path argument if specified
|
|
|
|
if p.config.RolesPath != "" {
|
|
|
|
args = append(args, "-p", filepath.ToSlash(p.config.RolesPath))
|
|
|
|
}
|
2019-07-26 12:44:40 -04:00
|
|
|
|
|
|
|
ui.Message(fmt.Sprintf("Executing Ansible Galaxy"))
|
|
|
|
cmd := exec.Command(p.config.GalaxyCommand, args...)
|
|
|
|
|
|
|
|
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
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
wg.Done()
|
|
|
|
}
|
|
|
|
wg.Add(2)
|
|
|
|
go repeat(stdout)
|
|
|
|
go repeat(stderr)
|
|
|
|
|
|
|
|
if err := cmd.Start(); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
wg.Wait()
|
|
|
|
err = cmd.Wait()
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("Non-zero exit status: %s", err)
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2016-09-12 02:29:24 -04:00
|
|
|
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
|
2018-12-03 19:08:47 -05:00
|
|
|
|
2016-02-14 19:07:02 -05:00
|
|
|
var envvars []string
|
2015-03-10 00:11:57 -04:00
|
|
|
|
2019-07-26 12:44:40 -04:00
|
|
|
// Fetch external dependencies
|
|
|
|
if len(p.config.GalaxyFile) > 0 {
|
|
|
|
if err := p.executeGalaxy(ui, comm); err != nil {
|
|
|
|
return fmt.Errorf("Error executing Ansible Galaxy: %s", err)
|
|
|
|
}
|
|
|
|
}
|
2020-03-31 15:54:20 -04:00
|
|
|
|
2020-03-31 16:13:01 -04:00
|
|
|
args := []string{"-e", fmt.Sprintf("packer_build_name=%s", p.config.PackerBuildName), "-e", fmt.Sprintf("packer_builder_type=%s", p.config.PackerBuilderType)}
|
2016-02-06 21:09:15 -05:00
|
|
|
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))
|
2016-02-04 21:40:17 -05:00
|
|
|
}
|
2018-07-17 10:03:05 -04:00
|
|
|
|
|
|
|
// expose packer_http_addr extra variable
|
|
|
|
httpAddr := common.GetHTTPAddr()
|
|
|
|
if httpAddr != "" {
|
2020-03-31 15:54:20 -04:00
|
|
|
args = append(args, "-e", fmt.Sprintf(" packer_http_addr=%s", httpAddr))
|
2018-07-17 10:03:05 -04:00
|
|
|
}
|
|
|
|
|
2020-03-31 15:54:20 -04:00
|
|
|
// Add password to ansible call.
|
|
|
|
if p.config.UseProxy.False() && p.generatedData["ConnType"] == "winrm" {
|
|
|
|
args = append(args, "-e", fmt.Sprintf(" ansible_password=%s", p.generatedData["Password"]))
|
|
|
|
}
|
|
|
|
|
2020-03-31 16:13:01 -04:00
|
|
|
if p.generatedData["ConnType"] == "ssh" {
|
|
|
|
// Add ssh extra args to set IdentitiesOnly
|
|
|
|
args = append(args, "--ssh-extra-args", "-o IdentitiesOnly=yes")
|
|
|
|
}
|
|
|
|
|
2020-03-31 15:54:20 -04:00
|
|
|
args = append(args, "-i", inventory, playbook)
|
|
|
|
|
2015-03-10 00:11:57 -04:00
|
|
|
args = append(args, p.config.ExtraArguments...)
|
2016-02-14 19:07:02 -05:00
|
|
|
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...)
|
2020-03-31 15:54:20 -04:00
|
|
|
log.Printf("Megan cmd is %#v", cmd)
|
2015-03-10 00:11:57 -04:00
|
|
|
|
2016-02-26 14:49:37 -05:00
|
|
|
cmd.Env = os.Environ()
|
2016-02-14 19:07:02 -05:00
|
|
|
if len(envvars) > 0 {
|
|
|
|
cmd.Env = append(cmd.Env, envvars...)
|
2016-05-24 18:34:51 -04:00
|
|
|
}
|
|
|
|
|
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) {
|
2016-02-27 01:20:54 -05:00
|
|
|
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)
|
|
|
|
|
2018-07-17 15:52:32 -04:00
|
|
|
// remove winrm password from command, if it's been added
|
|
|
|
flattenedCmd := strings.Join(cmd.Args, " ")
|
2018-09-10 19:48:42 -04:00
|
|
|
sanitized := flattenedCmd
|
2020-03-31 15:54:20 -04:00
|
|
|
// winRMPass, ok := p.generatedData["WinRMPassword"]
|
|
|
|
// if ok && winRMPass != "" {
|
|
|
|
// sanitized = strings.Replace(sanitized,
|
|
|
|
// winRMPass.(string), "*****", -1)
|
|
|
|
// }
|
2018-09-10 19:48:42 -04:00
|
|
|
ui.Say(fmt.Sprintf("Executing Ansible: %s", sanitized))
|
2018-07-17 15:52:32 -04:00
|
|
|
|
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
|
|
|
|
}
|
2015-12-19 16:05:59 -05:00
|
|
|
|
2017-04-06 15:50:02 -04:00
|
|
|
func validateInventoryDirectoryConfig(name string) error {
|
2017-04-04 23:49:24 -04:00
|
|
|
info, err := os.Stat(name)
|
|
|
|
if err != nil {
|
2017-04-06 15:50:02 -04:00
|
|
|
return fmt.Errorf("inventory_directory: %s is invalid: %s", name, err)
|
2017-04-04 23:49:24 -04:00
|
|
|
} else if !info.IsDir() {
|
2017-04-06 15:50:02 -04:00
|
|
|
return fmt.Errorf("inventory_directory: %s must point to a directory", name)
|
2017-04-04 23:49:24 -04:00
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2016-02-06 21:09:15 -05:00
|
|
|
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,
|
|
|
|
}
|
2018-12-12 09:45:00 -05:00
|
|
|
tf, err := tmp.File("ansible-key")
|
2016-02-06 21:09:15 -05:00
|
|
|
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
|
|
|
|
}
|