Ansible provisioner: check if inventory directory exists during prepare

This commit is contained in:
Dan Fuchs 2017-04-04 22:49:24 -05:00
parent 492bff474b
commit 3fc809c05b
2 changed files with 69 additions and 6 deletions

View File

@ -124,6 +124,14 @@ func (p *Provisioner) Prepare(raws ...interface{}) error {
p.config.LocalPort = "0"
}
if len(p.config.InventoryDirectory) > 0 {
err = validateDirectoryConfig(p.config.InventoryDirectory, "inventory_directory", true)
if err != nil {
log.Println(p.config.InventoryDirectory, "does not exist")
errs = packer.MultiErrorAppend(errs, err)
}
}
err = p.getVersion()
if err != nil {
errs = packer.MultiErrorAppend(errs, err)
@ -383,6 +391,21 @@ func validateFileConfig(name string, config string, req bool) error {
return nil
}
func validateDirectoryConfig(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 directory", config, name)
}
return nil
}
type userKey struct {
ssh.PublicKey
privKeyFile string

View File

@ -76,12 +76,6 @@ func TestProvisionerPrepare_Defaults(t *testing.T) {
if err != nil {
t.Fatalf("err: %s", err)
}
config["inventory_directory"] = "some_directory"
err = p.Prepare(config)
if err != nil {
t.Fatalf("err: %s", err)
}
}
func TestProvisionerPrepare_PlaybookFile(t *testing.T) {
@ -252,6 +246,52 @@ func TestProvisionerPrepare_LocalPort(t *testing.T) {
}
}
func TestProvisionerPrepare_InventoryDirectory(t *testing.T) {
var p Provisioner
config := testConfig(t)
defer os.Remove(config["command"].(string))
hostkey_file, err := ioutil.TempFile("", "hostkey")
if err != nil {
t.Fatalf("err: %s", err)
}
defer os.Remove(hostkey_file.Name())
publickey_file, err := ioutil.TempFile("", "publickey")
if err != nil {
t.Fatalf("err: %s", err)
}
defer os.Remove(publickey_file.Name())
playbook_file, err := ioutil.TempFile("", "playbook")
if err != nil {
t.Fatalf("err: %s", err)
}
defer os.Remove(playbook_file.Name())
config["ssh_host_key_file"] = hostkey_file.Name()
config["ssh_authorized_key_file"] = publickey_file.Name()
config["playbook_file"] = playbook_file.Name()
config["inventory_directory"] = "doesnotexist"
err = p.Prepare(config)
if err == nil {
t.Errorf("should error if inventory_directory does not exist")
}
inventoryDirectory, err := ioutil.TempDir("", "some_inventory_dir")
if err != nil {
t.Fatalf("err: %s", err)
}
defer os.Remove(inventoryDirectory)
config["inventory_directory"] = inventoryDirectory
err = p.Prepare(config)
if err != nil {
t.Fatalf("err: %s", err)
}
}
func TestAnsibleGetVersion(t *testing.T) {
if os.Getenv("PACKER_ACC") == "" {
t.Skip("This test is only run with PACKER_ACC=1 and it requires Ansible to be installed")