0
0
mirror of https://github.com/thegeeklab/wp-ansible.git synced 2024-11-14 09:00:41 +00:00
wp-ansible/plugin/impl.go

101 lines
1.8 KiB
Go
Raw Normal View History

package plugin
import (
2023-12-19 08:19:23 +00:00
"context"
"errors"
2023-12-19 08:19:23 +00:00
"fmt"
"os"
"golang.org/x/sys/execabs"
)
var (
ErrPluginPlaybookNotSet = errors.New("playbook is required")
ErrPluginInventoryNotSet = errors.New("inventory is required")
)
2023-12-19 08:19:23 +00:00
//nolint:revive
func (p *Plugin) run(ctx context.Context) error {
if err := p.Validate(); err != nil {
return fmt.Errorf("validation failed: %w", err)
}
if err := p.Execute(); err != nil {
return fmt.Errorf("execution failed: %w", err)
}
return nil
}
// Validate handles the settings validation of the plugin.
func (p *Plugin) Validate() error {
2023-12-19 08:19:23 +00:00
if len(p.Settings.Playbooks.Value()) == 0 {
return ErrPluginPlaybookNotSet
}
2023-12-19 08:19:23 +00:00
if len(p.Settings.Inventories.Value()) == 0 {
return ErrPluginInventoryNotSet
}
return nil
}
// Execute provides the implementation of the plugin.
func (p *Plugin) Execute() error {
if err := p.playbooks(); err != nil {
return err
}
if err := p.ansibleConfig(); err != nil {
return err
}
2023-12-19 08:19:23 +00:00
if p.Settings.PrivateKey != "" {
if err := p.privateKey(); err != nil {
return err
}
2023-12-19 08:19:23 +00:00
defer os.Remove(p.Settings.PrivateKeyFile)
}
2023-12-19 08:19:23 +00:00
if p.Settings.VaultPassword != "" {
if err := p.vaultPass(); err != nil {
return err
}
2023-12-19 08:19:23 +00:00
defer os.Remove(p.Settings.VaultPasswordFile)
}
commands := []*execabs.Cmd{
p.versionCommand(),
}
2023-12-19 08:19:23 +00:00
if p.Settings.Requirements != "" {
commands = append(commands, p.requirementsCommand())
}
2023-12-19 08:19:23 +00:00
if p.Settings.Galaxy != "" {
commands = append(commands, p.galaxyCommand())
}
2023-12-19 08:19:23 +00:00
for _, inventory := range p.Settings.Inventories.Value() {
commands = append(commands, p.ansibleCommand(inventory))
}
for _, cmd := range commands {
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Env = os.Environ()
cmd.Env = append(cmd.Env, "ANSIBLE_FORCE_COLOR=1")
trace(cmd)
if err := cmd.Run(); err != nil {
return err
}
}
return nil
}