Relatively simple task, but finding the solution was more complicated than I feel it needs to be. SEO, please help find the next lost soul.
First, install Ansible. You can run:
pipx install --include-deps ansible
Please note that I strongly prefer not to use pip
or pipx
. Let's
use apt
instead:
sudo apt install ansible
For the purposes of this demonstration, whatever version of Ansible the Debian repo's give us is probably alright. Worked for me, plus, it makes more sense, right? (More on this at the official documentation: Installing Ansible on Debian - Ansible Community Docs.)
Next, create a file called playbook.yml
with the following content:
- hosts: all
become: false
gather_facts: false
tasks:
- name: Extract command output
shell:
cmd: "hostname"
register: result
- name: Display command output
debug:
msg: "{{ result.stdout_lines }}"
This playbook file is pretty self-explainatory and is easy to read and modify. It runs the
hostname
command on all hosts and displays the output from each. You can replace
hostname
with any command you want to run, and the output will be displayed in JSON format in the terminal from which
you ran the playbook.
Before we run the playbook, we need to create an inventory file. Create a file called hosts
with the following content:
[all]
localhost ansible_connection=local
To run the playbook, use the following command:
ansible-playbook -i hosts playbook.yml
This instructs the Ansible backend to run the playbook playbook.yml
using the inventory file
hosts
.
An example output would look like this:
That's not too bad.