MCPcopy Index your code
hub / github.com/apenella/go-ansible

github.com/apenella/go-ansible @v2.4.1

Chat with this repo
repository ↗ · DeepWiki ↗ · release v2.4.1 ↗ · + Follow
1,015 symbols 3,595 edges 144 files 800 documented · 79%
What it actually does AI analysis from the code graph — generated when you open this
loading…
README

go-ansible

License: MIT Test Go Report Card Go ReferenceStatic Badge

go-ansible-logo

Overview

Go-ansible is a Go library for executing Ansible commands (such as ansible-playbook, ansible-inventory, ansible-galaxy, and ansible) directly from Go applications. It acts as a wrapper around the Ansible CLI, enabling seamless integration of Ansible automation into Go projects.

Why go-ansible?

Go-ansible was created to address the challenge of managing complex Ansible playbooks that require a large number of extra variables. Rather than reimplementing Ansible’s logic, the library provides an abstraction layer over the existing Ansible commands, streamlining their execution from a Go application.

Originally, the library was a wrapper around the ansible-playbook command and was tightly coupled with the Stevedore project. However, thanks to the contributions, feedback, and advice from the community, it has evolved into a general-purpose solution. Today, go-ansible supports the execution of various commands, including ansible-playbook, ansible, and ansible-galaxy, and allows fine-grained control over settings and output management to accommodate diverse use cases.

Key Features

  • Ansible Command Execution: Execute Ansible commands, including ansible-playbook, ansible, ansible-galaxy, and ansible-inventory, directly from Go applications.
  • Workflow Orchestration: Chain multiple Ansible executions into a workflow, allowing you to run commands sequentially (e.g., installing roles/collections and executing playbooks) in a single workflow.
  • Flexible Configuration: Customise Ansible environment variables and settings through Go code, supporting advanced use cases and bespoke workflows.
  • Vault Integration: Manage Ansible Vault secrets, including encrypted variables, password files, and multiple password sources.
  • Versatile Output Management: Handle command output in various formats (plain text, JSON, JSONL), with built-in and custom output handlers and transformers.
  • Extensible Architecture: Extend with custom executors, output handlers, and transformers to support complex requirements, advanced execution flows, and error enrichment.

Additionally, the go-ansible library provides a set of examples that demonstrate how to use the library in distinct scenarios. It is recommended to review the examples section.

Table of Contents

Getting Started

The following section walks you through an example, showing how to set up and execute an Ansible playbook step by step using go-ansible. The same approach can be applied to other Ansible commands, such as ansible or ansible-inventory. If you want to see a complete example to run an Ansible playbook from Go, check out the ansibleplaybook-simple example.

Note Before proceeding, ensure you have installed the latest version of the go-ansible library. If not, please refer to the Installation section for instructions.

To create an application that launches the ansible-playbook command, you need to create an AnsiblePlaybookCmd struct. This struct generates the Ansible command to be run. Then, you need to execute the command using an executor. In this example, you will use the DefaultExecute executor provided by the go-ansible library.

Create the AnsiblePlaybookCmd struct

To execute ansible-playbook commands, first define the necessary connection, playbook, and privilege escalation options.

Start by creating the AnsiblePlaybookOptions struct:

ansiblePlaybookOptions := &playbook.AnsiblePlaybookOptions{
  Become:     true,
  Connection: "local",
  Inventory:  "127.0.0.1,",
}

Finally, create the AnsiblePlaybookCmd struct that generates the command to execute the playbook site.yml using the ansible-playbook command:

playbookCmd := playbook.NewAnsiblePlaybookCmd(
  playbook.WithPlaybooks("site.yml", "site2.yml"),
  playbook.WithPlaybookOptions(ansiblePlaybookOptions),
)

Once the AnsiblePlaybookCmd is defined, provide the command to an executor to run the command.

Create the DefaultExecute executor

We will use the DefaultExecute struct, provided by the go-ansible library, to execute the ansible-playbook command. It requires a Commander responsible for generating the command to be executed. In this example, you will use the AnsiblePlaybookCmd previously defined.

// PlaybookCmd is the Commander responsible for generating the command to execute
exec := execute.NewDefaultExecute(
  execute.WithCmd(playbookCmd),
  execute.WithErrorEnrich(playbook.NewAnsiblePlaybookErrorEnrich()),
)

Once you have defined the DefaultExecute, execute the Ansible command using the following code:

err := exec.Execute(context.Background())
if err != nil {
  // Manage the error
}

Manage the output of the command execution

By default, the DefaultExecute uses the DefaultResults struct to manage the output of the command execution. The DefaultResults struct handles the output as plain text.

 ──
 ── PLAY [all] *********************************************************************
 ──
 ── TASK [Gathering Facts] *********************************************************
 ── ok: [127.0.0.1]
 ──
 ── TASK [simple-ansibleplaybook] **************************************************
 ── ok: [127.0.0.1] => {
 ──     "msg": "Your are running 'simple-ansibleplaybook' example"
 ── }
 ──
 ── PLAY RECAP *********************************************************************
 ── 127.0.0.1                  : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
 ──
 ── Playbook run took 0 days, 0 hours, 0 minutes, 0 seconds

Installation

⚠️ Important:

  • The master branch may contain unreleased or pre-released features. It is recommended to use the stable releases available in the releases page.
  • Major version upgrades (e.g., 1.x to 2.x) introduce breaking changes. Please review the changelog and the relevant upgrade guides before upgrading:
  • Upgrade guide to 1.x
  • Upgrade guide to 2.x
  • Update your import paths to match the correct module version (e.g., github.com/apenella/go-ansible/v2 for version 2.x).

To install the release candidate version:

go get github.com/apenella/go-ansible/v2@v2.4.1

To install the previous stable version:

go get github.com/apenella/go-ansible

Upgrade Notes

Concepts

There are a few concepts that you need to understand before using the go-ansible library. These concepts are essential to effectively use the library and to understand the examples and usage references provided in this document.

Executor

An executor is a component that executes commands and handles the results from the execution output. The library includes the DefaultExecute executor, which is a ready-to-go implementation of an executor. If the DefaultExecute does not meet your requirements, you can also create a custom executor. To know more about the DefaultExecute, refer to that section.

Command Generator

A command generator or a commander is responsible for generating the command to be executed. The AnsiblePlaybookCmd and AnsibleAdhocCmd structs are examples of command generators. That concept has been introduced in the major version 2.0.0.

Results Handler

A results handler or a results outputer is responsible

Extension points exported contracts — how you extend this code

PasswordReader (Interface)
PasswordReader defines the implementation of a password reader [6 implementers]
pkg/vault/password/resolve/interface.go
Executor (Interface)
Executor interface to execute commands [20 implementers]
pkg/execute/interface.go
AnsiblePlaybookOptionsFunc (FuncType)
AnsiblePlaybookOptionsFunc is a function to set executor options
pkg/playbook/ansiblePlaybookCmd.go
AnsibleGalaxyCollectionInstallOptionsFunc (FuncType)
AnsibleGalaxyCollectionInstallOptionsFunc is a function to set executor options
pkg/galaxy/collection/install/ansibleGalaxyCollectionInstallCmd.go
AnsibleAdhocOptionsFunc (FuncType)
AnsibleAdhocOptionsFunc is a function to set executor options
pkg/adhoc/ansibleAdhocCmd.go
AnsibleInventoryOptionFunc (FuncType)
AnsibleInventoryOptionFunc is a function to set executor options
pkg/inventory/ansibleInventoryCmd.go
PasswordReader (Interface)
(no doc) [6 implementers]
pkg/vault/encrypt/instance.go
Commander (Interface)
Commander generates commands to be executed [6 implementers]
pkg/execute/interface.go

Core symbols most depended-on inside this repo

NewAnsibleWithConfigurationSettingsExecute
called by 256
pkg/execute/configuration/ansibleWithConfigurationSettingsExecute.go
Run
called by 107
pkg/execute/exec/interface.go
Error
called by 59
mocks/mockExitCodeErr.go
NewDefaultExecute
called by 50
pkg/execute/defaultExecute.go
WithCmd
called by 33
pkg/execute/defaultExecuteOptions.go
NewMockExecute
called by 31
pkg/execute/mockExecute.go
NewAnsiblePlaybookCmd
called by 23
pkg/playbook/ansiblePlaybookCmd.go
WithPlaybookOptions
called by 23
pkg/playbook/ansiblePlaybookCmd.go

Shape

Function 735
Method 178
Struct 69
FuncType 17
Interface 14
TypeAlias 2

Languages

Go100%

Modules by API surface

pkg/execute/configuration/ansibleWithConfigurationSettingsExecute.go240 symbols
pkg/execute/configuration/ansibleWithConfigurationSettingsExecute_test.go236 symbols
pkg/execute/result/json/ansiblePlaybookJSONResults.go16 symbols
pkg/execute/defaultExecute_test.go15 symbols
pkg/inventory/ansibleInventoryCmd.go12 symbols
pkg/execute/exec/cmd_mock.go12 symbols
pkg/execute/exec/cmd.go12 symbols
pkg/execute/exec/interface.go11 symbols
pkg/execute/defaultExecute.go11 symbols
examples/ansibleplaybook-posix-jsonl-stdout-persistence/ansibleplaybook-posix-jsonl-stdout-persistence.go11 symbols
utils/cmd/configGenerator.go10 symbols
pkg/execute/result/json/ansiblePlaybookJSONLEventResults_test.go10 symbols

For agents

$ claude mcp add go-ansible \
  -- python -m otcore.mcp_server <graph>

⬇ download graph artifact

Ask about this repo answers extend the page