ansibler

package module
v0.6.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 8, 2020 License: MIT Imports: 8 Imported by: 0

README

go-ansible-logo

go-ansible

Go-ansible is a package for running Ansible playbooks from Golang applications. It supports ansible-playbook command with the most of its options.

Table of Contents

Packages

Ansibler

To run an ansible-playbook command you could define four objects, depending on your needs:

  • AnsiblePlaybookCmd object is the main object which defines the ansible-playbook command and how to execute it. AnsiblePlaybookCmd definition is mandatory to run any ansible-playbook command. AnsiblePlaybookCmd has a parameter that defines the Executor to use, the worker who launches the execution. If no Executor is specified, is used DefaultExecutor. AnsiblePlaybookCmd also has an attribute to define the stdout callback method to use. Depending on that method, go-ansible manages the results in a specific way. Actually all stdout callback method's results are treated such the default method instead of json stdout callback, which parses the json an summerizes the stats per host. If no stdout callback method is specified, is used default stdout callback one.
  • AnsiblePlaybookOptions object has those parameters described on Options section within ansible-playbook's man page, and defines how should be the ansible-playbook execution behavior and where to find execution configuration.
  • AnsiblePlaybookConnectionOptions object has those parameters described on Connections Options section within ansible-playbook's man page, and defines how to connect to hosts.
  • PrivilegeEscalationOptions object has those parameters described on Escalation Options section within ansible-playbook's man page, and defines how to become a user.
Execute

Go-ansible package has its own and default executor implementation which runs the ansible-playbook command and prints its output with a prefix on each line. Whenever is required, you could write your own executor implementation and set it on AnsiblePlaybookCmd object, it will expect that the executor implements Executor interface.

type Executor interface {
	Execute(command string, args []string, prefix string) error
}

Its possible to define your own executor and set it on AnsiblePlaybookCmd.

type MyExecutor struct {}
func (e *MyExecutor) Execute(command string, args []string, prefix string) error {
    fmt.Println("I am doing nothing")

    return nil
}

playbook := &ansibler.AnsiblePlaybookCmd{
    Playbook:          "site.yml",
    ConnectionOptions: ansiblePlaybookConnectionOptions,
    Options:           ansiblePlaybookOptions,
    Exec:              &MyExecutor{},
}

When you run the playbook using your dummy executor, the output received is the next one.

$ go run myexecutor-ansibleplaybook.go
I am doing nothing
Stdout Callback

It is possible to define and specific stdout callback method on go-ansible. To do that is needed to set StdoutCallback attribute on AnsiblePlaybookCmd object. Depending on the used method, the results are managed by one function or another. The functions to manage ansible-playbook's output are defined on the package github.com/apenella/go-ansible/stdoutcallback/results and must be defined following the next signature:

// StdoutCallbackResultsFunc defines a function which manages ansible's stdout callbacks. The function expects and string for prefixing output lines, a reader that receives the data to be wrote and a writer that defines where to write the data comming from reader
type StdoutCallbackResultsFunc func(string, io.Reader, io.Writer) error
Results

Below are defined the methods to manage ansible playbooks outputs:

Default

By default, any stdout callback results is managed by DefaultStdoutCallbackResults results method, which writes to io.Writer ansible-playbook's output, without manipulates it.

JSON

When the stdout callback method is defined to be in json format, the output is managed by JSONStdoutCallbackResults results method. This method parses the output json received from ansible-playbook's output skipping the unrequired lines from the output, and writes result into io.Writer.

Ansible-playbook output skipped lines

Those lines from ansible-playbook's output which do not belong to json are skipped and are not wrote to io.Writer.

Skip lines matching regexp are:

  • "^[\s\t]*Playbook run took [0-9]+ days, [0-9]+ hours, [0-9]+ minutes, [0-9]+ seconds$",
Manage JSON output

JSONStdoutCallbackResults method writes to io.Writer parameter the json output. Results packages provides a JSONParser that returns an AnsiblePlaybookJSONResults, holding the unmarshalled json on it. You could manipulate AnsiblePlaybookJSONResults object to achieve and format the json output depending on your needs.

The json schema expected from ansible-playbook is the defined on https://github.com/ansible/ansible/blob/v2.9.11/lib/ansible/plugins/callback/json.py.

Example

Below you could find a simple example of how to use go-ansbile but on examples folder there are more examples.

When is needed to run an ansible-playbook from your Golang application using go-ansible package, you must define a AnsiblePlaybookCmd,AnsiblePlaybookOptions, AnsiblePlaybookConnectionOptions as its shown below.

AnsiblePlaybookConnectionOptions where is defined how to connect to hosts.

ansiblePlaybookConnectionOptions := &ansibler.AnsiblePlaybookConnectionOptions{
	Connection: "local",
}

AnsiblePlaybookOptions where is defined which should be the ansible-playbook execution behavior and where to find execution configuration.

ansiblePlaybookOptions := &ansibler.AnsiblePlaybookOptions{
    Inventory: "127.0.0.1,",
}

AnsiblePlaybookPrivilegeEscalationOptions where is defined wether to become another and how to do it.

privilegeEscalationOptions := &ansibler.AnsiblePlaybookPrivilegeEscalationOptions{
    Become:        true,
    BecomeMethod:  "sudo",
}

AnsiblePlaybookCmd where is defined the command execution.

playbook := &ansibler.AnsiblePlaybookCmd{
    Playbook:          "site.yml",
    ConnectionOptions: ansiblePlaybookConnectionOptions,
    Options:           ansiblePlaybookOptions,
    PrivilegeEscalationOptions: privilegeEscalationOptions,
    ExecPrefix:        "Go-ansible example",
}

Once the AnsiblePlaybookCmd is already defined it could be run it using the Run method.

err := playbook.Run()
if err != nil {
    panic(err)
}

The result of the ansible-playbook execution is shown below.

Go-ansible example =>
Go-ansible example =>  PLAY [all] *********************************************************************
Go-ansible example =>
Go-ansible example =>  TASK [Gathering Facts] *********************************************************
Go-ansible example =>  ok: [127.0.0.1]
Go-ansible example =>
Go-ansible example =>  TASK [simple-ansibleplaybook] **************************************************
Go-ansible example =>  ok: [127.0.0.1] =>
Go-ansible example =>    msg: Your are running 'simple-ansibleplaybook' example
Go-ansible example =>
Go-ansible example =>  PLAY RECAP *********************************************************************
Go-ansible example =>  127.0.0.1                  : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
Go-ansible example =>
Go-ansible example =>  Playbook run took 0 days, 0 hours, 0 minutes, 1 seconds
Duration: 1.816272213s

License

go-ansible is available under MIT license.

Documentation

Index

Constants

View Source
const (
	// AnsiblePlaybookBin is the ansible-playbook binary file value
	AnsiblePlaybookBin = "ansible-playbook"

	// AskBecomePassFlag is ansble-playbook's ask for become user password flag
	AskBecomePassFlag = "--ask-become-pass"

	// AskPassFlag is ansble-playbook's ask for connection password flag
	AskPassFlag = "--ask-pass"

	// BecomeFlag is ansble-playbook's become flag
	BecomeFlag = "--become"

	// BecomeMethodFlag is ansble-playbook's become method flag
	BecomeMethodFlag = "--become-method"

	// BecomeUserFlag is ansble-playbook's become user flag
	BecomeUserFlag = "--become-user"

	// ConnectionFlag is the connection flag for ansible-playbook
	ConnectionFlag = "--connection"

	// ExtraVarsFlag is the extra variables flag for ansible-playbook
	ExtraVarsFlag = "--extra-vars"

	// FlushCacheFlag is the flush cache flag for ansible-playbook
	FlushCacheFlag = "--flush-cache"

	// InventoryFlag is the inventory flag for ansible-playbook
	InventoryFlag = "--inventory"

	// LimitFlag is the limit flag for ansible-playbook
	LimitFlag = "--limit"

	// ListHostsFlag is the list hosts flag for ansible-playbook
	ListHostsFlag = "--list-hosts"

	// ListTagsFlag is the list tags flag for ansible-playbook
	ListTagsFlag = "--list-tags"

	// ListTasksFlag is the list tasks flag for ansible-playbook
	ListTasksFlag = "--list-tasks"

	// PrivateKeyFlag is the private key file flag for ansible-playbook
	PrivateKeyFlag = "--private-key"

	// TagsFlag is the tags flag for ansible-playbook
	TagsFlag = "--tags"

	// SyntaxCheckFlag is the syntax check flag for ansible-playbook
	SyntaxCheckFlag = "--syntax-check"

	// TimeoutFlag is the timeout flag for ansible-playbook
	TimeoutFlag = "--timeout"

	// UserFlag is the user flag for ansible-playbook
	UserFlag = "--user"

	// VaultPasswordFileFlag is the vault password file flag for ansible-playbook
	VaultPasswordFileFlag = "--vault-password-file"

	// AnsibleForceColorEnv is the environment variable which forces color mode
	AnsibleForceColorEnv = "ANSIBLE_FORCE_COLOR"

	// AnsibleHostKeyCheckingEnv
	AnsibleHostKeyCheckingEnv = "ANSIBLE_HOST_KEY_CHECKING"
)

Variables

This section is empty.

Functions

func AnsibleAvoidHostKeyChecking added in v0.5.0

func AnsibleAvoidHostKeyChecking()

AnsibleAvoidHostKeyChecking sets the hosts key checking to false

func AnsibleForceColor

func AnsibleForceColor()

AnsibleForceColor changes to a forced color mode

func AnsibleSetEnv added in v0.5.0

func AnsibleSetEnv(key, value string)

AnsibleSetEnv set any configuration by environment variables. Check ansible configuration at https://docs.ansible.com/ansible/latest/reference_appendices/config.html

Types

type AnsiblePlaybookCmd

type AnsiblePlaybookCmd struct {
	// Exec is the executor item
	Exec Executor
	// ExecPrefix is a text that is set at the beginning of each execution line
	ExecPrefix string
	// Playbook is the ansible's playbook name to be used
	Playbook string
	// Options are the ansible's playbook options
	Options *AnsiblePlaybookOptions
	// ConnectionOptions are the ansible's playbook specific options for connection
	ConnectionOptions *AnsiblePlaybookConnectionOptions
	// PrivilegeEscalationOptions are the ansible's playbook privilage escalation options
	PrivilegeEscalationOptions *AnsiblePlaybookPrivilegeEscalationOptions
	// StdoutCallback defines which is the stdout callback method. By default is used 'default' method. Supported stdout method by go-ansible are: debug, default, dense, json, minimal, null, oneline, stderr, timer, yaml
	StdoutCallback string
	// Writer manages the output
	Writer io.Writer
}

AnsiblePlaybookCmd object is the main object which defines the `ansible-playbook` command and how to execute it.

func (*AnsiblePlaybookCmd) Command

func (p *AnsiblePlaybookCmd) Command() ([]string, error)

Command generate the ansible-playbook command which will be executed

func (*AnsiblePlaybookCmd) Run

func (p *AnsiblePlaybookCmd) Run() error

Run method runs the ansible-playbook

func (*AnsiblePlaybookCmd) String added in v0.5.0

func (p *AnsiblePlaybookCmd) String() string

String returns AnsiblePlaybookCmd as string

type AnsiblePlaybookConnectionOptions

type AnsiblePlaybookConnectionOptions struct {
	// AskPass defines whether user's password should be asked to connect to host
	AskPass bool
	// Connection is the type of connection used by ansible-playbook
	Connection string
	// PrivateKey is the user's private key file used to connect to a host
	PrivateKey string
	// Timeout is the connection timeout on ansible-playbook. Take care because Timeout is defined ad string
	Timeout string
	// User is the user to use to connect to a host
	User string
}

AnsiblePlaybookConnectionOptions object has those parameters described on `Connections Options` section within ansible-playbook's man page, and which defines how to connect to hosts.

func (*AnsiblePlaybookConnectionOptions) GenerateCommandConnectionOptions

func (o *AnsiblePlaybookConnectionOptions) GenerateCommandConnectionOptions() ([]string, error)

GenerateCommandConnectionOptions return a list of connection options flags to be used on ansible-playbook execution

func (*AnsiblePlaybookConnectionOptions) String added in v0.5.0

String return a list of connection options flags to be used on ansible-playbook execution

type AnsiblePlaybookOptions

type AnsiblePlaybookOptions struct {
	// ExtraVars is a map of extra variables used on ansible-playbook execution
	ExtraVars map[string]interface{}
	// FlushCache clear the fact cache for every host in inventory
	FlushCache bool
	// Inventory specify inventory host path
	Inventory string
	// Limit is selected hosts additional pattern
	Limit string
	// ListHosts outputs a list of matching hosts
	ListHosts bool
	// ListTags list all available tags
	ListTags bool
	// ListTasks
	ListTasks bool
	// Tags list all tasks that would be executed
	Tags string
}

AnsiblePlaybookOptions object has those parameters described on `Options` section within ansible-playbook's man page, and which defines which should be the ansible-playbook execution behavior.

func (*AnsiblePlaybookOptions) AddExtraVar

func (o *AnsiblePlaybookOptions) AddExtraVar(name string, value interface{}) error

AddExtraVar registers a new extra variable on ansible-playbook options item

func (*AnsiblePlaybookOptions) GenerateCommandOptions

func (o *AnsiblePlaybookOptions) GenerateCommandOptions() ([]string, error)

GenerateCommandOptions return a list of options flags to be used on ansible-playbook execution

func (*AnsiblePlaybookOptions) String added in v0.5.0

func (o *AnsiblePlaybookOptions) String() string

String returns AnsiblePlaybookOptions as string

type AnsiblePlaybookPrivilegeEscalationOptions

type AnsiblePlaybookPrivilegeEscalationOptions struct {
	// Become
	Become bool
	// BecomeMethod
	BecomeMethod string
	// BecomeUser
	BecomeUser string
	// AskBecomePass
	AskBecomePass bool
}

AnsiblePlaybookPrivilegeEscalationOptions object has those parameters described on `Privilege Escalation Options` section within ansible-playbook's man page, and which controls how and which user you become as on target hosts.

func (*AnsiblePlaybookPrivilegeEscalationOptions) GenerateCommandPrivilegeEscalationOptions

func (o *AnsiblePlaybookPrivilegeEscalationOptions) GenerateCommandPrivilegeEscalationOptions() ([]string, error)

GenerateCommandPrivilegeEscalationOptions return a list of privilege escalation options flags to be used on ansible-playbook execution

func (*AnsiblePlaybookPrivilegeEscalationOptions) String added in v0.5.0

String return an string

type Executor

type Executor interface {
	Execute(command string, args []string, prefix string) error
}

Executor is and interface that should be implemented for those item which could run ansible playbooks

type MockExecute

type MockExecute struct {
	Write io.Writer
}

MockExecute defines a simple executor for testing purposal

func (*MockExecute) Execute

func (e *MockExecute) Execute(command string, args []string, prefix string) error

Execute takes a command and args and runs it, streaming output to stdout

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL