Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 29 ยท Projects

Project: Build a Mini Ansible in JavaScript

Build a tiny Ansible in JavaScript: parse an inventory and a playbook, register modules, support check mode, notify handlers and print a play recap. Runs in your browser.

The best way to understand a tool is to build a small version of it. In this project you will write a mini Ansible in about 150 lines of JavaScript. It reads an INI inventory, reads a playbook, runs tasks against pretend servers through a registry of modules, supports check mode, fires handlers once at the end of a play and prints a recap like the real ansible-playbook. Everything runs in your browser, so you can edit it and watch the behaviour change.

The program is a stand-in, not Ansible. It has no SSH, no Python modules, no facts and only a tiny slice of the playbook language. But the core design is the same, and after you have built it, lines such as changed: [web1] and ok=4 changed=4 failed=0 stop being magic. If you need a refresher first, read Modules and Idempotence and Handlers, Tags and Task Control.

Real Ansible cannot run on this site, so the inventory and playbook formats below are read-only descriptions of what the stand-in accepts. The runnable editors contain the whole stand-in and the pretend servers it manages. Nothing here touches a real machine.

The plan

A configuration tool is a pipeline with five small parts. Our mini version has the same five.

flowchart LR
  I["Inventory text"] --> PI["parseInventory<br/>hosts, groups, vars"]
  P["Playbook text"] --> PP["parsePlaybook<br/>plays, tasks, handlers"]
  PI --> R["Runner<br/>loop over hosts and tasks"]
  PP --> R
  R --> M["Module registry<br/>package, lineinfile, service"]
  M --> S["Server state<br/>(simulated)"]
  R --> O["Output and recap"]

Text goes in, parsers turn it into data, the runner asks modules to compare and change simulated servers, and the recap counts what happened.

The most important design decision is in the module box. A module does not simply "do a thing". It first compares the desired state with the current state and returns a small result: did anything differ, and if so, how to fix it. The runner decides whether to apply the fix. That split is what makes check mode possible: in check mode the runner asks every module for its result but never applies it.

Step 1: parse the inventory

Our inventory understands the three INI constructs you met in Inventory: Hosts and Groups: host lines with key=value pairs, [group:children] sections that nest groups, and [group:vars] sections.

INI
[web]
web1 ansible_host=10.0.0.11
web2 ansible_host=10.0.0.12

[db]
db1 ansible_host=10.0.0.21

[prod:children]
web
db

[web:vars]
http_port=8080

The parser walks the file line by line. A line like [prod:children] switches the mode: what the following lines mean. In hosts mode each line is a host name followed by variables, in children mode each line is a group name, and in vars mode each line is a key=value pair for the group. Resolving a group such as prod then means collecting its own hosts plus the hosts of every child, recursively, without duplicates.

Step 2: parse the playbook

Real playbooks are YAML, and writing a full YAML parser is a project of its own. Our stand-in accepts a strict subset that is still valid YAML for these shapes: a list of plays, each with name, hosts, tasks and optional handlers. Each task has a name, one module line written as module: key=value key=value, and optionally notify or when.

YAML
- name: Configure web servers
  hosts: web
  tasks:
    - name: Install nginx
      package: name=nginx state=present
    - name: Write the listen port
      lineinfile: path=/etc/nginx/port.conf line=listen {{ http_port }};
      notify: restart nginx
  handlers:
    - name: restart nginx
      service: name=nginx state=restarted

The parser decides what a line is from its indentation and from the key. A dash at the left margin starts a new play. A dash deeper in starts a new task or handler. Any key that is not name, notify or when is treated as the module name, and its value is split into arguments with a regular expression that understands key=value pairs whose values contain spaces. This is the same trick real Ansible uses for the old "free-form" key=value argument style, except that real Ansible has a proper YAML parser underneath.

Run the first stand-in to see both parsers at work. It prints what they understood, which is a good habit when debugging your own playbooks too.

JS Step 1 and 2: parse an inventory and a playbook

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The {{ http_port }} placeholder is still untouched in the parsed arguments. Variables are filled in later, per host, because the same task must produce 8080 on one host and perhaps 80 on another.

Step 3: modules that compare first

A module is a function that receives the pretend server and its arguments and returns a plan. If the server already matches, the plan says changed: false. If not, it says changed: true and includes an apply function that makes the server match.

JavaScript
const modules = {
  package(host, a) {
    const want = a.state !== "absent";
    if (host.packages.has(a.name) === want) return { changed: false };
    return { changed: true, apply: () => want ? host.packages.add(a.name) : host.packages.delete(a.name) };
  },
  // lineinfile and service follow the same shape
};

This is idempotence in its smallest form. Running the module a second time finds nothing to do. It also shows why the service module can fail in check mode when the package task before it only pretended to install the package: the module looks at the real (simulated) state, and the state has not changed. The real systemd module has the same behaviour for a unit that does not exist yet.

A module can also throw. When it does, the runner marks the host as failed and removes it from the rest of the play, exactly as Ansible does.

Step 4: the runner

The runner is a pair of loops: for each play, for each task, for each host that is still active. For every (task, host) pair it does the following.

  1. Merge variables: group variables first, then host variables, so the host wins.
  2. Evaluate when. A false condition counts as skipped and nothing else happens.
  3. Fill {{ name }} placeholders in the arguments.
  4. Call the module. If it reports a change and we are not in check mode, call apply.
  5. Count the result. If the task changed something and has notify, remember the handler name for this host.

When all tasks are done, the handlers run. A handler runs once per host, no matter how many tasks notified it, and only on hosts where at least one task actually changed something. Handlers run in the order they are defined in the play, not the order they were notified.

flowchart TD
  T["Task for one host"] --> W{"when is false?"}
  W -- yes --> SK["skipped"]
  W -- no --> C["module compares state"]
  C --> D{"differs?"}
  D -- no --> OK["ok"]
  D -- yes --> CH["changed<br/>(applied unless check mode)"]
  CH --> N{"has notify?"}
  N -- yes --> Q["remember handler for this host"]
  C -. "throws" .-> F["failed<br/>(host leaves the play)"]

Every task result ends as skipped, ok, changed or failed; a change can also queue a handler for the end of the play.

Running the whole project

Here is the complete stand-in. It contains a second play for the database host with a deliberate mistake: it starts postgres before installing it. Read the playbook, predict what happens, then press Run. The program performs three runs on the same pretend servers: a check run, a real run and a second real run.

JS The complete mini Ansible

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Compare the output with what you predicted.

  • Run 1 (check mode) changes nothing: web1 packages after check is an empty list. But the recap shows failed=1 for the web hosts too. In check mode the "Install nginx" task only predicted a change, so the next task, "Start nginx", finds no nginx and fails, and the host drops out before its handler. Real Ansible has the same trap with services that depend on a package from an earlier task, which is why some roles guard such tasks with when: not ansible_check_mode.
  • Run 2 (real) installs, writes the line, starts nginx and then runs the handler restart nginx once for each web host. db1 fails on the first task because postgres is not installed yet, so its second task never runs. The recap shows ok=4 changed=4 failed=0 skipped=1 for each web host. The handler counts as a fourth task, and the port-80 note is skipped because http_port is 8080.
  • Run 3 (real again) is the idempotence proof: changed=0 everywhere, and the handler does not run, because nothing notified it.

Try these edits to see the design react:

  1. Swap the two database tasks so the package comes first. db1 should now succeed.
  2. Add a second notify: restart nginx task and check that the handler still runs only once per host.
  3. Change http_port=8080 to http_port=80 in the inventory. The note task now runs, and the handler fires again.

What real Ansible adds

The stand-in captures the control flow. Real Ansible adds the parts that make it usable against actual machines.

  • SSH and connection plugins. Ansible logs in to each host (or uses WinRM, a network CLI or a local connection), copies a module, runs it and collects the result. Our servers are objects in memory.
  • Modules written in Python. The real package, lineinfile and service modules run on the managed node, usually as a short Python program that returns JSON. They handle dozens of platforms, edge cases and arguments.
  • Facts. Before the first task, Ansible gathers facts such as the operating system, addresses and memory, and offers them as variables. Our version has none.
  • A real YAML and Jinja2 engine. Real playbooks allow anchors, multiline strings, loops, filters, blocks, includes and roles, and when accepts any Jinja2 expression.
  • Parallelism. Ansible runs a task on many hosts at once (five by default, controlled by forks) and waits for the slowest. Our loop is sequential.
  • Strategies, tags, error handling and more. serial, free, block/rescue, any_errors_fatal, --limit, --diff and unreachable-host handling.

Keep this list in mind when something surprises you in real life. Most of the behaviour is the simple loop you just wrote. The difficulty is almost always in the modules and the network.

Extend the project

If you want to keep going, these are good next steps, each one a real feature you can recognise in Ansible.

  • Add a command module with a creates argument that is skipped when a marker file is already present.
  • Add changed_when: false and failed_when support to a task.
  • Add --limit support so only the hosts that match a pattern run. Ad-Hoc Commands shows the patterns.
  • Add flush_handlers as a special task that runs the pending handlers early.
  • Print a --diff view for lineinfile, showing the line before and after.
  • Run the hosts of a play in batches of two, as serial: 2 does, and stop the rollout when a batch fails.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does each module in the mini Ansible return a plan instead of changing the server immediately?

    Separating 'compare' from 'apply' lets the runner report what would change without changing anything. That is the idea behind check mode.
  2. 2. A handler is notified by three different tasks on the same host, and all three changed something. How often does the handler run on that host?

    Notifications are collected in a set per host, so duplicates merge. The handler runs once at the end of the play.
  3. 3. In run 3 the recap shows changed=0 and the handler does not run. What does this prove?

    A second run that changes nothing is the practical test of idempotence. No change means no notification, so the handler is not queued.
  4. 4. Which of these is something real Ansible provides that the mini version does not?

    The control flow is the same, but connections, Python modules on the managed nodes, facts and a full YAML and Jinja2 engine are what the stand-in leaves out.

Summary

  • A configuration tool is five parts: an inventory parser, a playbook parser, a module registry, a runner and a reporter.
  • Modules compare the current state with the desired state and return a plan; the runner applies it unless check mode is on.
  • A task ends as skipped, ok, changed or failed; a failed host leaves the play, and a change can notify a handler.
  • Handlers run once per host at the end of the play, only for hosts where something changed.
  • A second run with changed=0 is the practical proof of idempotence.
  • Real Ansible adds SSH, Python modules on the managed node, facts, a full YAML and Jinja2 engine and parallel execution.

Next: Exercises with Solutions