0
0
mirror of https://github.com/thegeeklab/wp-ansible.git synced 2024-12-01 07:10:34 +00:00
wp-ansible/plugin/impl.go

102 lines
1.9 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"
"github.com/thegeeklab/wp-plugin-go/trace"
"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-22 09:10:39 +00:00
if p.Settings.PythonRequirements != "" {
commands = append(commands, p.pythonRequirementsCommand())
}
2023-12-22 09:10:39 +00:00
if p.Settings.GalaxyRequirements != "" {
commands = append(commands, p.galaxyRequirementsCommand())
}
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(cmd)
if err := cmd.Run(); err != nil {
return err
}
}
return nil
}