ansible

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Apr 12, 2025 License: MIT Imports: 8 Imported by: 2

README

GO Ansible

license GitHub go.mod Go version GitHub release Go Report Card

Overview

GO Ansible is a Go module designed to programmatically run Ansible playbooks on Linux systems. It supports:

  • Automated Playbook Resolution: Resolves file patterns (glob) and validates playbook existence.
  • Temporary File Management: Manages temporary files (SSH private keys and Vault passwords) securely.
  • Galaxy Integration: Installs roles and collections from Ansible Galaxy with extensive configuration.
  • Flexible Configuration: Customizes Ansible commands (inventories, extra vars, SSH/user options, verbosity).
  • Enhanced Environment Variables: Sets variables like ANSIBLE_CONFIG based on provided configurations.
  • Debug and Traceability: Provides detailed command tracing in debug mode for easier troubleshooting.

Features

Playbook Execution and Management
  • Playbook Resolution: Supports file names and glob patterns for playbook identification.
  • Temporary Files: Manages SSH keys and Vault passwords, cleaning them up automatically.
  • Inventory Management: Supports inline (localhost,) and file-based inventories.
Advanced Options
  • Command Building: Constructs commands with options (check/diff modes, user settings, forks).
  • Extra Vars Management: Passes multiple variables to playbooks with --extra-vars.
  • Verbose Logging: Offers configurable verbosity (up to -vvvv) for detailed logs.
Galaxy Integration
  • Roles and Collections: Installs Galaxy roles and collections using a configuration file.
  • Customization: API keys, server URLs, certificate ignoring, timeouts, dependencies handling.
  • Upgrades: Provides options to upgrade existing Galaxy collections.
Debugging and Error Handling
  • Command Tracing: Debug mode prints every executed command for tracing.
  • Context-Based Execution: Uses Go’s context.Context for command management and cancellation.
  • Error Reporting: Wraps errors with contextual information using github.com/pkg/errors.

Installation

Ensure you have Go (version 1.23 or higher) installed, then run:

go mod download

Usage

The module serves as a foundation for executing Ansible playbooks in applications. Example:

  1. Create and Configure a Playbook Instance:
package main

import (
  "context"
  "log"
  "github.com/arillso/go.ansible/ansible"
)

func main() {
  pb := ansible.NewPlaybook()
  pb.Config.Playbooks = []string{"site.yml"}
  pb.Config.Inventories = []string{"localhost,"}
  pb.Config.PrivateKey = "your ssh private key..."
  pb.Config.VaultPassword = "your vault password..."

  if err := pb.Exec(context.Background()); err != nil {
    log.Fatalf("Execution failed: %v", err)
  }
}
  1. Command Construction and Execution:

The module automatically constructs commands and manages dependencies (like Galaxy installations).

Testing

The repository includes tests covering functionalities such as playbook resolution, temporary files, and extra vars:

go test -v ./...

CI/CD and Linters

  • Continuous Integration: GitHub Actions automatically run tests on push and pull requests.
  • Code Quality: Makefile targets for formatting and linting ensure best practices.
  • Pre-commit Hooks: Automatically fix issues like trailing whitespace and line endings.

License

Licensed under the MIT License.

(c) 2022, Arillso

Documentation

Overview

Package ansible provides functionality to run Ansible playbooks with configurable options. It supports building command line parameters, handling temporary files, and context-based execution.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Config

type Config struct {
	// General options
	Become                                 bool
	BecomeMethod, BecomeUser               string
	User                                   string
	PrivateKey, PrivateKeyFile             string
	AskBecomePass, AskPass                 bool
	Check, Diff, FlushCache, ForceHandlers bool
	SyntaxCheck                            bool
	ListHosts, ListTags, ListTasks         bool
	Step                                   bool
	Connection                             string
	Timeout, Forks                         int

	// SSH options
	SSHCommonArgs, SSHExtraArgs string
	SCPExtraArgs, SFTPExtraArgs string
	SSHTransferMethod           string

	// Playbook options
	Inventories                 []string
	Playbooks                   []string
	Limit                       string
	ExtraVars                   []string
	StartAtTask, Tags, SkipTags string
	ModulePath                  []string
	ModuleName                  string
	Verbose                     int
	NoColor                     bool

	// Vault options
	VaultID, VaultPassword, VaultPasswordFile string
	AskVaultPass                              bool

	// Facts options
	FactPath           string
	InvalidateCache    bool
	FactCaching        string
	FactCachingTimeout int

	// Galaxy options
	GalaxyFile                        string
	GalaxyAPIKey, GalaxyAPIServerURL  string
	GalaxyCollectionsPath             string
	GalaxyDisableGPGVerify            bool
	GalaxyForce, GalaxyForceWithDeps  bool
	GalaxyNoDeps, GalaxyIgnoreCerts   bool
	GalaxyIgnoreSignatureStatusCodes  []string
	GalaxyKeyring                     string
	GalaxyOffline, GalaxyPre          bool
	GalaxyRequiredValidSignatureCount int
	GalaxyRequirementsFile            string
	GalaxySignature                   string
	GalaxyTimeout                     int
	GalaxyUpgrade                     bool

	// Other options
	CallbackWhitelist string
	PollInterval      int
	GatherSubset      string
	GatherTimeout     int
	StrategyPlugin    string
	MaxFailPercentage int
	AnyErrorsFatal    bool
	Requirements      string
	ModuleDefaults    map[string]string
	ConfigFile        string
	MetadataExport    string

	// Optional: directory for temporary files
	TempDir string
}

Config contains configuration options for running Ansible playbooks.

type Playbook added in v1.0.0

type Playbook struct {
	Config Config
	Debug  bool // Enables additional logging output
	// contains filtered or unexported fields
}

Playbook represents an execution of an Ansible playbook run.

func NewPlaybook added in v1.0.0

func NewPlaybook() *Playbook

NewPlaybook returns a new instance of Playbook with default values.

func (*Playbook) Exec added in v1.0.0

func (p *Playbook) Exec(ctx context.Context) error

Exec runs the configured Ansible playbooks using the provided context. It resolves playbook paths, prepares temporary files, builds and executes commands, and cleans up temporary files afterward.

Jump to

Keyboard shortcuts

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