This tutorial contains notes about Ansible.

1. Ansible

Ansible is an open-source tool for automated software provisioning and application deployment.

Ansible allows to execute predefined tasks via SSH on remote or local machines. Ansible is simple to use and does not require a server/client architecture. You can execute it from your local machine while the remote machines do not need an Ansible installation.

You can execute ad-hoc commands via Ansible or write configuration scripts (playbooks) to automate configuration steps.

2. Installation and configuration of Ansible

2.1. Installation

Ansible is available for all major Linux distributions. You can install it with your package manager. Under Ubuntu you can enter this:

sudo apt install ansible
sudo apt install sshpass

The Ansible version available through the systems package manager might be outdated. To run the latest Ansible version you can install it through the Python package manager pip. At the time of this writing Ansible supports Python 2.x.

pip install ansible

If you decide to install Ansible through pip make sure to delete your system Ansible installation. Otherwise, you might run into some problems.

2.2. Configuration

For the usage of Ansible, you need to configure the machines to which you want to connect.

This can be done via a local file or a global file on the system.

If you want to configure a global configuration file, you would create a file named hosts in the /etc/ansible/ directory and place your server configuration there. Besides the global host file, you can reference other host files on the command line with -i /path. This has the advantage that you can put these files under version control and share them with others.

The following configuration would define a group named test with two hosts from a local network:

[test]
192.168.56.101
192.168.56.123

3. Executing ad-hoc commands

Executing ad-hoc commands via Ansible is an easy way to get started with it. To do this create a new directory and a file named hosts. This file should contain the IP address or hostname of your server.

[test]
your.host

Optionally you can also specific the SSH port to use:

[test]
your.host:22222

It is also possible to execute your Ansible commands on your local machine. This is useful for testing or in case you do not yet have access to a remote machine available.

For example, to execute the Unix uptime command via Ansible, you could use following commands.

# ansible -i <host file> <group> -m <module> -a <module arguments>
ansible -i hosts test -m shell -a "uptime"

# -u allows you to specify the user to connect to the machine
# ansible -u <user> -i <host file> <group> -m <module> -a <module arguments>
ansible -u root -i hosts test -m shell -a "uptime"

# output should look something like this:
your.host | SUCCESS | rc=0 >>
 21:56:49 up  3:04,  2 users,  load average: 0.00, 0.00, 0.00

# using localhost:
ansible localhost -m shell -a "uptime"

You can specify the user on the remote machine by passing in the --become-user <username> parameter. Otherwise, the user to connect to the server is used to execute the commands on the server. To gain administrator (sudo) rights for your command add --become. If the remote user needs a password for sudo access, additionally add --ask-become-password.

4. Using Ansible configuration files - Playbooks

Playbooks are Ansible configuration files that specify the tasks to be performed. These playbooks allows to describe the configuration steps which are executed and store these configuration for later usage.

Task can be performed synchronously or asynchronously. By default, tasks are executed synchronously and sequentially in the order they are defined in the Playbook.

It is possible to switch host groups between tasks.

Playbooks are written in YAML format. To do a syntax check on a Playbook without executing it, start it with the --syntax-check parameter:

ansible-playbook my_playbook.yml --syntax-check

Ansible comes with a sizable number of modules that we can use in our playbooks to do common tasks.

Here is an example playbook with three tasks:

- hosts: test (1)
  tasks:
    - name: Ensure sudo group exists
      group: (2)
        name: sudo (3)
        state: present (4)
    - name: Ensure test user exists
      user: (5)
        name: test
        state: present
    - name: Add test user to sudo group
      user: (6)
        name: test
        groups: sudo
        append: yes
1 we define the host group on which this playbook is executed
2 we use the Ansible group module to add a new user group
3 each module defines a specific set of variables by which it can be configured, here we specify the name of the group
4 check if user exists and create him if he is missing
5 we use the user module to create a new user
6 we add our new test user to the sudo group

It is possible to have multiple task blocks with different settings in one playbook. The next example works on multiple hosts:

- hosts: dbserver
  tasks:
    - name: fetch backup
      fetch:
        src: /backup/
        dest: /tmp/fetched
- hosts: storageserver
  tasks:
    - name: upload backup

4.1. Dry run

Many Ansible modules support a test run without persisting any actual changes. Such runs are called dry runs. To trigger a dry run execute with the --check parameter. To see the changes that would be made add --diff. This parameter can also be used in a regular run.

ansible-playbook my_playbook.yml --check --diff

5. Validating playbook changes with a harness

A harness lets an AI agent check its own Ansible changes: the agent edits a playbook, runs one command, reads the result and repeats until the command succeeds. The playbook runs against a disposable container, never against real servers. This example combines ansible-lint with Molecule, the common test framework for Ansible.

5.1. Creating the harness

Install the tools in the directory of your playbook. Podman runs containers rootless and without a daemon, so the agent does not need the root-equivalent access that the docker group grants.

sudo apt install podman python3-venv
python3 -m venv .venv
. .venv/bin/activate
pip install ansible-lint molecule "molecule-plugins[podman]"

Your playbook and these files belong in that directory and under version control:

my_playbook.yml
validate.sh
molecule/default/molecule.yml
molecule/default/converge.yml
molecule/default/verify.yml

molecule.yml describes the test machine:

driver:
  name: podman
platforms:
  - name: instance
    image: docker.io/library/python:3.13-slim (1)
    pre_build_image: true (2)
    groups:
      - test (3)
1 use a fully qualified image name, as a short name can make Podman ask for a registry; the image must contain Python, and testing services additionally requires an init system, which plain images lack
2 use the image as it is instead of building a new one
3 the host group that the playbook targets

converge.yml applies the playbook under test:

- name: Converge
  import_playbook: ../../my_playbook.yml

verify.yml checks the result, here of the three-task example playbook from the previous section, saved as my_playbook.yml:

- name: Verify
  hosts: test
  tasks:
    - name: Read the groups of the test user
      command: id -nG test
      register: user_groups
      changed_when: false
    - name: Check that the test user is in the sudo group
      assert:
        that: "'sudo' in user_groups.stdout.split()"

validate.sh is the single command for the agent. Make it executable with chmod +x validate.sh:

#!/bin/sh
set -e
cd "$(dirname "$0")"
. .venv/bin/activate
export NO_COLOR=1 (1)
grep -nE 'ignore_errors|failed_when: false|noqa|hosts: localhost|connection: local' my_playbook.yml && exit 1 (2)
grep -q assert molecule/default/verify.yml || { echo "verify.yml has no checks"; exit 1; } (3)
ansible-lint --profile min my_playbook.yml (4)
molecule test
1 removes most color codes from the output that the agent reads
2 rejects the usual ways of hiding a failure or leaving the container
3 Molecule passes without complaint if verify.yml is missing
4 min is the lowest profile, so raise it once your playbook is clean

The script exits with a non-zero code on lint errors, failing tasks, tasks that report changes on a second run and failing checks in verify.yml.

5.2. Using the harness

Tell the agent about the harness in the instruction file of your repository, for example AGENTS.md:

After every Ansible change, run `./validate.sh` and fix the reported problems until it exits with 0.
Add a check to `molecule/default/verify.yml` for every new behavior.
Never weaken or remove a check to get a passing run.
Never use `ignore_errors`, `failed_when: false`, `changed_when: false` or `# noqa` in the playbook under test just to get a passing run.
Never run a playbook against a real inventory.

Follow these rules to keep the result reliable:

  • Keep the harness non-interactive, because a Vault or sudo password prompt blocks the agent.

  • Keep production inventories, SSH keys and Vault passwords out of the environment of the agent.

  • Pin the versions of the tools and the image in real projects, so that a failure comes from the change and not from an update.

  • Run the install steps and validate.sh in your continuous integration build as well, so that a passing run does not depend on the agent.

To analyze a failure, keep the container and inspect it:

.venv/bin/molecule test --destroy=never
podman exec instance id -nG test
.venv/bin/molecule destroy

6. Ansible resources

Home Tutorials Training Consulting Books Company Contact us


Get more...