packer-cn/provisioner/ansible-local/provisioner.go

516 lines
16 KiB
Go
Raw Normal View History

//go:generate mapstructure-to-hcl2 -type Config
2013-09-29 16:38:37 -04:00
package ansiblelocal
import (
"context"
2013-09-29 16:38:37 -04:00
"fmt"
"os"
"path/filepath"
"strings"
2017-04-04 16:39:01 -04:00
"github.com/hashicorp/packer/common"
"github.com/hashicorp/packer/common/uuid"
"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"
2013-09-29 16:38:37 -04:00
)
const DefaultStagingDir = "/tmp/packer-provisioner-ansible-local"
2013-09-29 16:38:37 -04:00
type Config struct {
common.PackerConfig `mapstructure:",squash"`
ctx interpolate.Context
2013-09-29 16:38:37 -04:00
2014-02-21 18:27:39 -05:00
// The command to run ansible
Command string
// Extra options to pass to the ansible command
ExtraArguments []string `mapstructure:"extra_arguments"`
// Path to group_vars directory
GroupVars string `mapstructure:"group_vars"`
// Path to host_vars directory
HostVars string `mapstructure:"host_vars"`
// The playbook dir to upload.
PlaybookDir string `mapstructure:"playbook_dir"`
2014-07-17 15:33:09 -04:00
2013-09-29 16:38:37 -04:00
// The main playbook file to execute.
PlaybookFile string `mapstructure:"playbook_file"`
// The playbook files to execute.
PlaybookFiles []string `mapstructure:"playbook_files"`
2013-09-29 16:38:37 -04:00
// An array of local paths of playbook files to upload.
PlaybookPaths []string `mapstructure:"playbook_paths"`
// An array of local paths of roles to upload.
RolePaths []string `mapstructure:"role_paths"`
// The directory where files will be uploaded. Packer requires write
// permissions in this directory.
StagingDir string `mapstructure:"staging_directory"`
// If true, staging directory is removed after executing ansible.
CleanStagingDir bool `mapstructure:"clean_staging_directory"`
// The optional inventory file
InventoryFile string `mapstructure:"inventory_file"`
// The optional inventory groups
InventoryGroups []string `mapstructure:"inventory_groups"`
// The optional ansible-galaxy requirements file
GalaxyFile string `mapstructure:"galaxy_file"`
// The command to run ansible-galaxy
GalaxyCommand string
2013-09-29 16:38:37 -04:00
}
type Provisioner struct {
config Config
playbookFiles []string
2013-09-29 16:38:37 -04:00
}
func (p *Provisioner) Prepare(raws ...interface{}) error {
err := config.Decode(&p.config, &config.DecodeOpts{
Interpolate: true,
InterpolateContext: &p.config.ctx,
InterpolateFilter: &interpolate.RenderFilter{
Exclude: []string{},
},
}, raws...)
2013-09-29 16:38:37 -04:00
if err != nil {
return err
}
// Reset the state.
p.playbookFiles = make([]string, 0, len(p.config.PlaybookFiles))
// Defaults
if p.config.Command == "" {
p.config.Command = "ANSIBLE_FORCE_COLOR=1 PYTHONUNBUFFERED=1 ansible-playbook"
}
if p.config.GalaxyCommand == "" {
p.config.GalaxyCommand = "ansible-galaxy"
}
2014-02-21 18:27:39 -05:00
if p.config.StagingDir == "" {
p.config.StagingDir = filepath.ToSlash(filepath.Join(DefaultStagingDir, uuid.TimeOrderedUUID()))
2014-02-21 18:27:39 -05:00
}
2013-09-29 16:38:37 -04:00
// Validation
var errs *packer.MultiError
// Check that either playbook_file or playbook_files is specified
if len(p.config.PlaybookFiles) != 0 && p.config.PlaybookFile != "" {
errs = packer.MultiErrorAppend(errs, fmt.Errorf("Either playbook_file or playbook_files can be specified, not both"))
}
if len(p.config.PlaybookFiles) == 0 && p.config.PlaybookFile == "" {
errs = packer.MultiErrorAppend(errs, fmt.Errorf("Either playbook_file or playbook_files must be specified"))
}
if p.config.PlaybookFile != "" {
err = validateFileConfig(p.config.PlaybookFile, "playbook_file", true)
if err != nil {
errs = packer.MultiErrorAppend(errs, err)
}
}
for _, playbookFile := range p.config.PlaybookFiles {
if err := validateFileConfig(playbookFile, "playbook_files", true); err != nil {
errs = packer.MultiErrorAppend(errs, err)
} else {
playbookFile, err := filepath.Abs(playbookFile)
if err != nil {
errs = packer.MultiErrorAppend(errs, err)
} else {
p.playbookFiles = append(p.playbookFiles, playbookFile)
}
}
2013-09-29 16:38:37 -04:00
}
// Check that the inventory file exists, if configured
if len(p.config.InventoryFile) > 0 {
err = validateFileConfig(p.config.InventoryFile, "inventory_file", true)
if err != nil {
errs = packer.MultiErrorAppend(errs, err)
}
}
// 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)
}
}
// Check that the playbook_dir directory exists, if configured
if len(p.config.PlaybookDir) > 0 {
if err := validateDirConfig(p.config.PlaybookDir, "playbook_dir"); err != nil {
errs = packer.MultiErrorAppend(errs, err)
}
}
2014-07-17 15:33:09 -04:00
// Check that the group_vars directory exists, if configured
if len(p.config.GroupVars) > 0 {
if err := validateDirConfig(p.config.GroupVars, "group_vars"); err != nil {
errs = packer.MultiErrorAppend(errs, err)
}
}
// Check that the host_vars directory exists, if configured
if len(p.config.HostVars) > 0 {
if err := validateDirConfig(p.config.HostVars, "host_vars"); err != nil {
errs = packer.MultiErrorAppend(errs, err)
}
}
2014-02-21 18:27:39 -05:00
for _, path := range p.config.PlaybookPaths {
err := validateDirConfig(path, "playbook_paths")
if err != nil {
errs = packer.MultiErrorAppend(errs, err)
}
}
for _, path := range p.config.RolePaths {
if err := validateDirConfig(path, "role_paths"); err != nil {
errs = packer.MultiErrorAppend(errs, err)
}
}
2013-09-29 16:38:37 -04:00
if errs != nil && len(errs.Errors) > 0 {
return errs
}
return nil
}
func (p *Provisioner) Provision(ctx context.Context, ui packer.Ui, comm packer.Communicator) error {
2013-09-29 16:38:37 -04:00
ui.Say("Provisioning with Ansible...")
if len(p.config.PlaybookDir) > 0 {
ui.Message("Uploading Playbook directory to Ansible staging directory...")
if err := p.uploadDir(ui, comm, p.config.StagingDir, p.config.PlaybookDir); err != nil {
return fmt.Errorf("Error uploading playbook_dir directory: %s", err)
}
} else {
ui.Message("Creating Ansible staging directory...")
if err := p.createDir(ui, comm, p.config.StagingDir); err != nil {
return fmt.Errorf("Error creating staging directory: %s", err)
}
2013-09-29 16:38:37 -04:00
}
if p.config.PlaybookFile != "" {
ui.Message("Uploading main Playbook file...")
src := p.config.PlaybookFile
dst := filepath.ToSlash(filepath.Join(p.config.StagingDir, filepath.Base(src)))
if err := p.uploadFile(ui, comm, dst, src); err != nil {
return fmt.Errorf("Error uploading main playbook: %s", err)
}
} else if err := p.provisionPlaybookFiles(ui, comm); err != nil {
return err
2013-09-29 16:38:37 -04:00
}
if len(p.config.InventoryFile) == 0 {
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("packer-provisioner-ansible-local")
if err != nil {
return fmt.Errorf("Error preparing inventory file: %s", err)
}
defer os.Remove(tf.Name())
if len(p.config.InventoryGroups) != 0 {
content := ""
for _, group := range p.config.InventoryGroups {
content += fmt.Sprintf("[%s]\n127.0.0.1\n", group)
}
_, err = tf.Write([]byte(content))
} else {
_, err = tf.Write([]byte("127.0.0.1"))
}
if err != nil {
tf.Close()
return fmt.Errorf("Error preparing inventory file: %s", err)
}
tf.Close()
p.config.InventoryFile = tf.Name()
defer func() {
p.config.InventoryFile = ""
}()
}
if len(p.config.GalaxyFile) > 0 {
ui.Message("Uploading galaxy file...")
src := p.config.GalaxyFile
dst := filepath.ToSlash(filepath.Join(p.config.StagingDir, filepath.Base(src)))
if err := p.uploadFile(ui, comm, dst, src); err != nil {
return fmt.Errorf("Error uploading galaxy file: %s", err)
}
}
ui.Message("Uploading inventory file...")
src := p.config.InventoryFile
dst := filepath.ToSlash(filepath.Join(p.config.StagingDir, filepath.Base(src)))
if err := p.uploadFile(ui, comm, dst, src); err != nil {
return fmt.Errorf("Error uploading inventory file: %s", err)
}
if len(p.config.GroupVars) > 0 {
ui.Message("Uploading group_vars directory...")
src := p.config.GroupVars
dst := filepath.ToSlash(filepath.Join(p.config.StagingDir, "group_vars"))
if err := p.uploadDir(ui, comm, dst, src); err != nil {
return fmt.Errorf("Error uploading group_vars directory: %s", err)
}
}
if len(p.config.HostVars) > 0 {
ui.Message("Uploading host_vars directory...")
src := p.config.HostVars
dst := filepath.ToSlash(filepath.Join(p.config.StagingDir, "host_vars"))
if err := p.uploadDir(ui, comm, dst, src); err != nil {
return fmt.Errorf("Error uploading host_vars directory: %s", err)
}
}
2013-09-29 16:38:37 -04:00
if len(p.config.RolePaths) > 0 {
ui.Message("Uploading role directories...")
for _, src := range p.config.RolePaths {
dst := filepath.ToSlash(filepath.Join(p.config.StagingDir, "roles", filepath.Base(src)))
2013-09-29 16:38:37 -04:00
if err := p.uploadDir(ui, comm, dst, src); err != nil {
return fmt.Errorf("Error uploading roles: %s", err)
}
}
}
if len(p.config.PlaybookPaths) > 0 {
ui.Message("Uploading additional Playbooks...")
playbookDir := filepath.ToSlash(filepath.Join(p.config.StagingDir, "playbooks"))
if err := p.createDir(ui, comm, playbookDir); err != nil {
2013-09-29 16:38:37 -04:00
return fmt.Errorf("Error creating playbooks directory: %s", err)
}
for _, src := range p.config.PlaybookPaths {
dst := filepath.ToSlash(filepath.Join(playbookDir, filepath.Base(src)))
if err := p.uploadDir(ui, comm, dst, src); err != nil {
2013-09-29 16:38:37 -04:00
return fmt.Errorf("Error uploading playbooks: %s", err)
}
}
}
if err := p.executeAnsible(ui, comm); err != nil {
return fmt.Errorf("Error executing Ansible: %s", err)
}
if p.config.CleanStagingDir {
ui.Message("Removing staging directory...")
if err := p.removeDir(ui, comm, p.config.StagingDir); err != nil {
return fmt.Errorf("Error removing staging directory: %s", err)
}
}
2013-09-29 16:38:37 -04:00
return nil
}
func (p *Provisioner) provisionPlaybookFiles(ui packer.Ui, comm packer.Communicator) error {
var playbookDir string
if p.config.PlaybookDir != "" {
var err error
playbookDir, err = filepath.Abs(p.config.PlaybookDir)
if err != nil {
return err
}
}
for index, playbookFile := range p.playbookFiles {
if playbookDir != "" && strings.HasPrefix(playbookFile, playbookDir) {
p.playbookFiles[index] = strings.TrimPrefix(playbookFile, playbookDir)
continue
}
if err := p.provisionPlaybookFile(ui, comm, playbookFile); err != nil {
return err
}
}
return nil
}
func (p *Provisioner) provisionPlaybookFile(ui packer.Ui, comm packer.Communicator, playbookFile string) error {
ui.Message(fmt.Sprintf("Uploading playbook file: %s", playbookFile))
remoteDir := filepath.ToSlash(filepath.Join(p.config.StagingDir, filepath.Dir(playbookFile)))
remotePlaybookFile := filepath.ToSlash(filepath.Join(p.config.StagingDir, playbookFile))
if err := p.createDir(ui, comm, remoteDir); err != nil {
return fmt.Errorf("Error uploading playbook file: %s [%s]", playbookFile, err)
}
if err := p.uploadFile(ui, comm, remotePlaybookFile, playbookFile); err != nil {
return fmt.Errorf("Error uploading playbook: %s [%s]", playbookFile, err)
}
return nil
}
func (p *Provisioner) executeGalaxy(ui packer.Ui, comm packer.Communicator) error {
ctx := context.TODO()
rolesDir := filepath.ToSlash(filepath.Join(p.config.StagingDir, "roles"))
galaxyFile := filepath.ToSlash(filepath.Join(p.config.StagingDir, filepath.Base(p.config.GalaxyFile)))
// ansible-galaxy install -r requirements.yml -p roles/
command := fmt.Sprintf("cd %s && %s install -r %s -p %s",
p.config.StagingDir, p.config.GalaxyCommand, galaxyFile, rolesDir)
ui.Message(fmt.Sprintf("Executing Ansible Galaxy: %s", command))
cmd := &packer.RemoteCmd{
Command: command,
}
if err := cmd.RunWithUi(ctx, comm, ui); err != nil {
return err
}
if cmd.ExitStatus() != 0 {
// ansible-galaxy version 2.0.0.2 doesn't return exit codes on error..
return fmt.Errorf("Non-zero exit status: %d", cmd.ExitStatus())
}
return nil
}
2013-09-29 16:38:37 -04:00
func (p *Provisioner) executeAnsible(ui packer.Ui, comm packer.Communicator) error {
inventory := filepath.ToSlash(filepath.Join(p.config.StagingDir, filepath.Base(p.config.InventoryFile)))
extraArgs := fmt.Sprintf(" --extra-vars \"packer_build_name=%s packer_builder_type=%s packer_http_addr=%s -o IdentitiesOnly=yes\" ",
p.config.PackerBuildName, p.config.PackerBuilderType, common.GetHTTPAddr())
if len(p.config.ExtraArguments) > 0 {
extraArgs = extraArgs + strings.Join(p.config.ExtraArguments, " ")
}
2013-09-29 16:38:37 -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)
}
}
if p.config.PlaybookFile != "" {
playbookFile := filepath.ToSlash(filepath.Join(p.config.StagingDir, filepath.Base(p.config.PlaybookFile)))
if err := p.executeAnsiblePlaybook(ui, comm, playbookFile, extraArgs, inventory); err != nil {
return err
}
}
for _, playbookFile := range p.playbookFiles {
playbookFile = filepath.ToSlash(filepath.Join(p.config.StagingDir, playbookFile))
if err := p.executeAnsiblePlaybook(ui, comm, playbookFile, extraArgs, inventory); err != nil {
return err
}
}
return nil
}
func (p *Provisioner) executeAnsiblePlaybook(
ui packer.Ui, comm packer.Communicator, playbookFile, extraArgs, inventory string,
) error {
ctx := context.TODO()
command := fmt.Sprintf("cd %s && %s %s%s -c local -i %s",
p.config.StagingDir, p.config.Command, playbookFile, extraArgs, inventory,
)
2013-09-29 16:38:37 -04:00
ui.Message(fmt.Sprintf("Executing Ansible: %s", command))
cmd := &packer.RemoteCmd{
Command: command,
}
if err := cmd.RunWithUi(ctx, comm, ui); err != nil {
2013-09-29 16:38:37 -04:00
return err
}
if cmd.ExitStatus() != 0 {
if cmd.ExitStatus() == 127 {
2014-02-24 11:26:51 -05:00
return fmt.Errorf("%s could not be found. Verify that it is available on the\n"+
"PATH after connecting to the machine.",
p.config.Command)
}
return fmt.Errorf("Non-zero exit status: %d", cmd.ExitStatus())
2013-09-29 16:38:37 -04:00
}
return nil
}
func validateDirConfig(path string, config string) error {
info, err := os.Stat(path)
if err != nil {
return fmt.Errorf("%s: %s is invalid: %s", config, path, err)
} else if !info.IsDir() {
return fmt.Errorf("%s: %s must point to a directory", config, path)
}
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 (p *Provisioner) uploadFile(ui packer.Ui, comm packer.Communicator, dst, src string) error {
f, err := os.Open(src)
if err != nil {
return fmt.Errorf("Error opening: %s", err)
}
defer f.Close()
if err = comm.Upload(dst, f, nil); err != nil {
2013-09-29 16:38:37 -04:00
return fmt.Errorf("Error uploading %s: %s", src, err)
}
return nil
}
func (p *Provisioner) createDir(ui packer.Ui, comm packer.Communicator, dir string) error {
ctx := context.TODO()
2013-09-29 16:38:37 -04:00
cmd := &packer.RemoteCmd{
Command: fmt.Sprintf("mkdir -p '%s'", dir),
}
ui.Message(fmt.Sprintf("Creating directory: %s", dir))
if err := cmd.RunWithUi(ctx, comm, ui); err != nil {
return err
}
if cmd.ExitStatus() != 0 {
return fmt.Errorf("Non-zero exit status. See output above for more information.")
}
return nil
}
func (p *Provisioner) removeDir(ui packer.Ui, comm packer.Communicator, dir string) error {
ctx := context.TODO()
cmd := &packer.RemoteCmd{
Command: fmt.Sprintf("rm -rf '%s'", dir),
}
ui.Message(fmt.Sprintf("Removing directory: %s", dir))
if err := cmd.RunWithUi(ctx, comm, ui); err != nil {
2013-09-29 16:38:37 -04:00
return err
}
if cmd.ExitStatus() != 0 {
return fmt.Errorf("Non-zero exit status. See output above for more information.")
2013-09-29 16:38:37 -04:00
}
return nil
}
func (p *Provisioner) uploadDir(ui packer.Ui, comm packer.Communicator, dst, src string) error {
if err := p.createDir(ui, comm, dst); err != nil {
return err
}
// Make sure there is a trailing "/" so that the directory isn't
// created on the other side.
if src[len(src)-1] != '/' {
src = src + "/"
}
return comm.UploadDir(dst, src, nil)
}