Everything you've automated in Aurora Store starts because someone decides to run it: you in the terminal, CI when it receives a commit, AWX at 06:00, the update.py tool from the previous lesson. But many operations tasks are responses to something that happens: a web server that stops responding at three in the morning, a monitoring alert, a message in a queue. Waiting for a person to read the alert, log in on their laptop and launch the right playbook costs minutes or hours of store downtime. Event-Driven Ansible (EDA) closes that gap: a process listens to event sources, evaluates rules and, when a condition is met, runs an action, usually a playbook or an AWX template. In this lesson you'll learn its concepts and its tool, ansible-rulebook; you'll install the ansible.eda collection; you'll write a rulebook for Aurora that restarts nginx when a web server stops responding and restarts the catalog API container when an alert arrives in Alertmanager format; and, above all, you'll learn the precautions that separate a useful automatic remediation from one that makes incidents worse.
Contents
- From launching automation to reacting
- Concepts: sources, events, rules, conditions and actions
ansible-rulebookand its requirements- Installation on the control computer
- The
ansible.edacollection - A first rulebook
- Aurora's remediations: two playbooks
- The
watch-store.ymlrulebook - Running it and triggering the incidents
run_playbookorrun_job_template- EDA on the platform: EDA controller
- Best practices: making sure the remediation doesn't make the incident worse
- From launching automation to reacting
flowchart LR
subgraph Before["Until now"]
A1[Alert or symptom] --> P1[A person sees it]
P1 --> D1[Decides what to do]
D1 --> L1[Launches the playbook]
end
subgraph EDA["With Event-Driven Ansible"]
A2[Event] --> R2[ansible-rulebook<br/>evaluates the rules]
R2 -->|condition met| L2[Runs the action]
L2 --> N2[Notifies people]
end
EDA doesn't replace people: it automates the first response to known, repetitive problems with a safe fix, and leaves to people whatever requires judgment. Typical examples:
| Event | Reasonable automatic response |
|---|---|
| A service stops responding | Check again and restart it once |
| Disk almost full | Clean up temporary files and rotated logs |
| Alert about a certificate about to expire | Renew it |
| A commit on a branch | Launch a check (what CI does today) |
| A new server in the cloud inventory | Apply the base configuration to it |
| A "create a user" ticket | Create the account with the common role |
And examples of what you shouldn't automate: restoring a database, failing over to another data center or any irreversible or high-impact action, unless there's a human approval in between (section 12).
- Concepts: sources, events, rules, conditions and actions
| Concept | What it is | Example in Aurora |
|---|---|---|
| Source | A plugin that produces events: it listens on a port, polls a URL, reads a queue… | ansible.eda.url_check against web1 and web2 |
| Event | A dictionary of data emitted by the source | {"url_check": {"url": "http://192.168.56.11/", "status": "down"}} |
| Rule | A condition and an action, with a name | "Restart nginx on the web server that isn't responding" |
| Condition | An expression over the event (and accumulated facts) | event.url_check.status == "down" |
| Action | What's done when the condition is met | run_playbook: playbooks/remediate-web.yml |
| Ruleset | Sources + rules + the hosts it acts on | "Watch the Aurora Store web servers" |
| Rulebook | A YAML file with one or more rulesets | rulebooks/watch-store.yml |
A rulebook looks like a playbook in form (YAML, a list of blocks with name and hosts), but not in substance:
| Playbook | Rulebook | |
|---|---|---|
| When it runs | Once, from start to finish | Indefinitely, while it listens |
| Unit | Tasks that run in order | Rules that are evaluated with every event |
| What it does | Configures hosts | Decides when to run playbooks (or other actions) |
| Tool | ansible-playbook |
ansible-rulebook |
ansible-rulebook and its requirements
ansible-rulebook and its requirementsansible-rulebook is EDA's command-line tool. Under the hood it combines:
- Python (
asyncio) to run the sources, which are asynchronous plugins from collections. - A rules engine based on Drools (Java), which it reaches from Python through the
drools_jpylibrary. It's what evaluates the conditions efficiently, even with many rules and events. ansible-runner(Lesson 10.4) to run the actions' playbooks.
Hence its requirements:
| Requirement | Detail |
|---|---|
| Java | A JDK 17 or later, with JAVA_HOME set (drools_jpy needs it at install time and at run time) |
| Python | A current version (the control computer's, 3.12 on Ubuntu 24.04, will do) |
ansible-core and ansible-runner |
For the run_playbook/run_module actions |
| Collections with sources | At least ansible.eda |
| The sources' libraries | For example, aiohttp for the HTTP sources (webhook, alertmanager, url_check) |
Versions. EDA evolves quickly. The syntax in this lesson (sources, conditions,
throttle,run_playbook,run_job_template) is the stable one inansible-rulebook1.x andansible.eda2.x, but some details (source options, which sources live in which collection, event fields) change between versions. Before trusting a rule, check the documentation for your version and, above all, run with--print-eventsto see the real events.
- Installation on the control computer
EDA has dependencies the rest of aurora-infra doesn't need (Java, Drools, aiohttp), so you'll install it in a separate virtual environment, .venv-eda, next to the project's .venv. First, Java:
sudo apt install -y openjdk-17-jdk
export JAVA_HOME=/usr/lib/jvm/java-17-openjdk-amd64 # on ARM: ...-arm64
java -versionAdd the export JAVA_HOME=... line to your ~/.bashrc. Next, the Python environment. Create rulebooks/requirements.txt in aurora-infra:
# Event-Driven Ansible (Lesson 10.5). Example versions: check the latest ones and pin them.
ansible-rulebook==1.1.7
ansible-core>=2.17,<2.18
ansible-runner==2.4.1
aiohttpcd ~/aurora-infra
python3 -m venv .venv-eda
.venv-eda/bin/pip install -r rulebooks/requirements.txt
.venv-eda/bin/ansible-rulebook --versionThe --version output also shows the Drools and Java versions it found: if it fails here, check JAVA_HOME. Add .venv-eda/ to .gitignore.
- The
ansible.eda collection
ansible.eda collectionSources, like modules, live in collections. ansible.eda is the base collection. Since only EDA needs it (not the playbooks, nor the aurora-ee EE), declare it separately, in rulebooks/requirements.yml:
---
# Event-Driven Ansible collections (Lesson 10.5). They don't go in collections/requirements.yml
# because the playbooks and aurora-ee don't need them.
collections:
# Example version: check the latest one on Galaxy and pin it after testing it.
- name: ansible.eda
version: "2.8.1"ansible-galaxy collection install -r rulebooks/requirements.yml
ansible-galaxy collection list ansible.edaIt's installed in collections/ansible_collections/ (the collections_path in ansible.cfg), alongside the others. Some of the sources in ansible.eda:
| Source | What it produces |
|---|---|
ansible.eda.range |
A sequence of numbers (for testing) |
ansible.eda.tick |
A periodic event (a "clock") |
ansible.eda.url_check |
Polls URLs periodically and emits their status (up/down) |
ansible.eda.webhook |
Opens an HTTP port and emits an event for each request received |
ansible.eda.alertmanager |
Receives Prometheus Alertmanager notifications and emits one event per alert |
ansible.eda.kafka |
Reads messages from a Kafka topic |
ansible.eda.file_watch |
Watches for changes to files |
ansible.eda.journald |
Reads the systemd journal |
ansible.eda.pg_listener |
Listens for PostgreSQL notifications (LISTEN/NOTIFY) |
ansible.eda.generic |
Emits events you give it (testing) |
There are sources in other collections (cloud, monitoring tools, ITSM…). Besides sources, ansible.eda includes event filters (ansible.eda.json_filter, ansible.eda.dashes_to_underscores…) that transform events before they're evaluated.
- A first rulebook
Before touching any servers, a rulebook that does nothing dangerous, to see how it works. Create /tmp/hello-rulebook.yml:
---
- name: First rulebook
hosts: all
sources:
- ansible.eda.range:
limit: 5
rules:
- name: Report when it reaches three
condition: event.i == 3
action:
debug:
msg: "Event {{ event.i }} has arrived"And run it:
cd ~/aurora-infra
export ANSIBLE_COLLECTIONS_PATH="$PWD/collections"
.venv-eda/bin/ansible-rulebook -r /tmp/hello-rulebook.yml -i "$PWD/inventories/lab" --print-eventssources:ansible.eda.rangewithlimit: 5emits five events,{"i": 0}…{"i": 4}, and ends.rules:conditionis evaluated with each event. Inside the condition, the event is calledevent, and it's written without{{ }}braces (likewhen:in playbooks).action: debugshows a message. Actions accept templates with{{ event... }}.-i: the inventory is mandatory, even though this rulebook doesn't use it; pass it with an absolute path.--print-eventsshows every event received: your best tool for writing conditions.ANSIBLE_COLLECTIONS_PATH: so thatansible-rulebookfindsansible.edaincollections/, as in Lesson 10.1.
The output shows the events {'i': 0} to {'i': 4} and, after the third one, the message "Event 3 has arrived". With -v or -vv you'll also see which rules are evaluated.
Conditions support more than equality:
| Condition | Meaning |
|---|---|
event.url_check.status == "down" |
Equality (also !=, <, >, <=, >=) |
event.alert.labels.severity in ["critical", "warning"] |
Membership of a list |
event.payload.message is search("error", ignorecase=true) |
Text search |
event.alert is defined |
The event has that field |
cond1 and cond2, cond1 or cond2, not cond |
Combinations |
condition: all: [cond1, cond2] |
Several conditions that can be met by different events (for example, "web1 down and web2 down") |
condition: any: [cond1, cond2] |
Any one of them |
- Aurora's remediations: two playbooks
A rule's action will usually be a playbook. Write them first, as normal aurora-infra playbooks, in playbooks/.
7.1. Not depending on the working directory
ansible-rulebook runs each playbook through ansible-runner, with its own temporary data directory. Don't count on the working directory being the root of the repository. In Aurora there's only one path relative to that directory: the known_hosts one in inventories/lab/group_vars/all/connection.yml (Lesson 9.2). Make it independent with the playbook_dir magic variable (the playbook's directory, playbooks/):
---
# Connection to the lab: verified host keys (Lesson 9.2).
# Absolute path based on playbook_dir, so that it works from any working directory
# (ansible-runner, ansible-rulebook). Ad hoc commands need --playbook-dir playbooks.
ansible_ssh_common_args: -o StrictHostKeyChecking=yes -o UserKnownHostsFile={{ playbook_dir }}/../ssh/known_hosts.labMake the same change for known_hosts.production in inventories/production/group_vars/all/connection.yml. In AWX, playbook_dir is the playbooks/ directory inside the synced project, so it works there too. Check that nothing has changed with ansible-playbook playbooks/site.yml --check (it should connect just the same) and an ad hoc command with --playbook-dir playbooks.
7.2. playbooks/remediate-web.yml
---
# Automatic remediation (Event-Driven Ansible, Lesson 10.5): restarts nginx on the
# web server that has stopped responding. Launched by rulebooks/watch-store.yml,
# which passes the event in the ansible_eda variable.
- name: Restart nginx on the web server that isn't responding
hosts: webservers
gather_facts: false
become: true
vars:
aurora_eda_url: "{{ ansible_eda.event.url_check.url | default('') }}"
tasks:
- name: Check that the playbook was launched by an event
ansible.builtin.assert:
that: aurora_eda_url | length > 0
fail_msg: "This playbook is launched by ansible-rulebook: ansible_eda.event.url_check.url is missing"
quiet: true
- name: Skip the unaffected web servers
ansible.builtin.meta: end_host
when: (aurora_eda_url | urlsplit('hostname')) != ansible_host
- name: Check the website again before acting
ansible.builtin.uri:
url: "http://localhost:{{ nginx_port }}/"
register: aurora_eda_before
failed_when: false
- name: Stop if the website has recovered by itself
ansible.builtin.meta: end_host
when: aurora_eda_before.status == 200
- name: Restart nginx
ansible.builtin.systemd_service:
name: nginx
state: restarted
- name: Wait for the website to respond again
ansible.builtin.uri:
url: "http://localhost:{{ nginx_port }}/"
register: aurora_eda_after
until: aurora_eda_after.status == 200
retries: 5
delay: 3Step by step:
ansible_eda: whenansible-rulebookruns a playbook, it passes it the extra variableansible_eda, with the event that triggered the rule inansible_eda.event(as well as the names of the ruleset and the rule). Here, the URL that failed.- The first task protects against accidental manual runs: without an event, the playbook stops.
- Picking the affected host from the event: the playbook targets
webservers, and each host checks whether it's the one in the URL.urlsplit('hostname')extracts192.168.56.11fromhttp://192.168.56.11/, and it's compared withansible_host(the address your computer reaches the web server through: the same one the source watches).meta: end_hostends the play for that host without an error. That way the playbook doesn't depend on howansible-rulebooknarrows down the hosts (that varies by version and by whether the event carries a list of hosts). - Checking again before acting: seconds may pass between the event and the run; if the website already responds (a momentary network glitch), nothing is touched.
failed_when: falsestops a connection error from making the task fail: we want the data, not the failure. - Restart (not reload): if nginx has stopped,
reloadedwon't start it. - Wait and verify: if the website doesn't respond after five attempts, the task fails. That's correct: the automatic remediation hasn't worked and a person is needed (for example, because the nginx configuration is broken and it won't start).
- Variables (
nginx_port) and secrets arrive as always:playbooks/group_vars/and the lab vault (that's whyANSIBLE_VAULT_IDENTITY_LISTwill be needed in theansible-rulebooksession).
7.3. playbooks/remediate-catalog.yml
The catalog API on api1 only listens on 127.0.0.1 (Lesson 9.2), so it can't be watched from outside with url_check. The natural thing is for the monitoring system to watch it (Prometheus, with the node_exporter agent the servers already have and, in the final project, whatever checks you add) and for Alertmanager to send the alert. By convention, Aurora's alert will be called AuroraCatalogDown and its instance label will be the server's name in the inventory (with or without a port).
---
# Automatic remediation (Event-Driven Ansible, Lesson 10.5): restarts the catalog API
# container when Alertmanager's AuroraCatalogDown alert arrives.
# Launched by rulebooks/watch-store.yml, which passes the event in the ansible_eda variable.
- name: Restart the catalog API that isn't responding
hosts: apiservers
gather_facts: false
become: true
vars:
aurora_eda_instance: "{{ ansible_eda.event.alert.labels.instance | default('') }}"
tasks:
- name: Check that the playbook was launched by an event
ansible.builtin.assert:
that: aurora_eda_instance | length > 0
fail_msg: "This playbook is launched by ansible-rulebook: ansible_eda.event.alert.labels.instance is missing"
quiet: true
- name: Skip the unaffected servers
ansible.builtin.meta: end_host
when: aurora_eda_instance.split(':')[0] != inventory_hostname
- name: Check the API again before acting
ansible.builtin.uri:
url: "http://127.0.0.1:{{ aurora_catalog_port }}/health"
register: aurora_eda_before
failed_when: false
- name: Stop if the API has recovered by itself
ansible.builtin.meta: end_host
when: aurora_eda_before.status == 200
- name: Restart the catalog API container
community.docker.docker_compose_v2:
project_src: "{{ aurora_catalog_dir | default('/opt/aurora-catalog') }}"
services:
- catalog
state: restarted
- name: Wait for the API to respond again
ansible.builtin.uri:
url: "http://127.0.0.1:{{ aurora_catalog_port }}/health"
register: aurora_eda_after
until: aurora_eda_after.status == 200
retries: 10
delay: 3- The structure is the same: a mandatory event, picking the host, checking again, acting, verifying.
split(':')[0]strips the port frominstanceif there is one (api1:9100→api1).docker_compose_v2withstate: restartedandservices: [catalog]restarts only the API service inside the Compose project deployed by theaurora_catalogrole (Lesson 8.1), without touching Redis. It also works if the container was stopped.aurora_catalog_dir | default(...): that variable is a role default, which isn't visible outside the role (Lesson 4.3); thedefaultrepeats its value.127.0.0.1is correct becauseuriruns onapi1.
- The
watch-store.yml rulebook
watch-store.yml rulebookCreate rulebooks/watch-store.yml:
---
# Event-Driven Ansible for Aurora Store (Lesson 10.5).
# Usage (from the root of aurora-infra, with .venv-eda and the variables from section 9):
# .venv-eda/bin/ansible-rulebook -r rulebooks/watch-store.yml -i "$PWD/inventories/lab" --verbose
- name: Watch the Aurora Store web servers
hosts: webservers
sources:
- name: Check the web servers every 30 seconds
ansible.eda.url_check:
urls:
- http://192.168.56.11/
- http://192.168.56.12/
delay: 30
rules:
- name: Restart nginx on the web server that isn't responding
condition: event.url_check.status == "down"
throttle:
once_within: 10 minutes
group_by_attributes:
- event.url_check.url
action:
run_playbook:
name: playbooks/remediate-web.yml
- name: Handle the monitoring alerts
hosts: apiservers
sources:
- name: Receive the Alertmanager notifications
ansible.eda.alertmanager:
host: 127.0.0.1
port: 5050
rules:
- name: Restart the catalog API that is down
condition: >-
event.alert.status == "firing" and
event.alert.labels.alertname == "AuroraCatalogDown"
throttle:
once_within: 15 minutes
group_by_attributes:
- event.alert.labels.instance
action:
run_playbook:
name: playbooks/remediate-catalog.yml
- name: Show the remaining alerts
condition: event.alert is defined
action:
print_event:
pretty: trueExplanation:
- Two rulesets in one rulebook: each with its own sources, rules and hosts. They run at the same time.
hosts: the inventory pattern the ruleset acts on, as in a play.- The
url_checksource: polls both URLs everydelayseconds and emits, for each one, an event withurl_check.url,url_check.status(upordown) and, depending on the case, the HTTP code or the error. The web servers are watched directly (not the load balancer) so we know which one fails: with one web server down, the load balancer would carry on serving with the other. throttle: the most important control in the rulebook. Without it, while the website stays down, each check (every 30 seconds) would launch the playbook again. Withonce_within: 10 minutesandgroup_by_attributes: [event.url_check.url], the action runs at most once every 10 minutes per URL: if web1 and web2 go down at the same time, both get remediated, but each only once per window. (There's alsoonce_after: act once after the time has passed, grouping the events.)- The
alertmanagersource: opens an HTTP server on127.0.0.1:5050that understands the format of Alertmanager's webhook notifications and emits one event per alert in the notification, with the alert inevent.alert(itslabels,annotationsandstatus). In the lab it only listens locally because there's no Alertmanager yet; when there is one (final project), it will be opened up to its address, with a firewall that only lets Alertmanager in. - A multi-line condition with
>-, like the long conditions in playbooks (Lesson 3.6). - Rule order matters: by default, when a rule is met, the following ones are not evaluated for that event. That's why the generic "Show the remaining alerts" rule goes last: it only sees the alerts the previous one hasn't handled.
print_event: another built-in action, useful for logging what arrives without acting.
- Running it and triggering the incidents
9.1. Starting ansible-rulebook
In a dedicated terminal:
cd ~/aurora-infra
export JAVA_HOME=/usr/lib/jvm/java-17-openjdk-amd64
export ANSIBLE_COLLECTIONS_PATH="$PWD/collections"
export ANSIBLE_CONFIG="$PWD/ansible.cfg"
# ANSIBLE_VAULT_IDENTITY_LIST is already in your ~/.bashrc (Lesson 9.1)
.venv-eda/bin/ansible-rulebook -r rulebooks/watch-store.yml -i "$PWD/inventories/lab" --verboseANSIBLE_CONFIGmakes sure the playbooks useaurora-infra'sansible.cfg(role and collection paths, user, key, pipelining, callbacks) even though they run from another directory.ansible-rulebookstays in the foreground, listening. Stop it withCtrl+C.
9.2. A web server down
In another terminal, stop nginx on web1 (it simulates a service failure):
In less than 30 seconds, the ansible-rulebook terminal shows the rule being met and the playbook running, with Ansible's usual output:
... Rule "Restart nginx on the web server that isn't responding" fired ...
PLAY [Restart nginx on the web server that isn't responding] *******************
TASK [Check that the playbook was launched by an event] ************************
ok: [web1]
ok: [web2]
TASK [Skip the unaffected web servers] *****************************************
...
TASK [Restart nginx] ***********************************************************
changed: [web1]
TASK [Wait for the website to respond again] ***********************************
ok: [web1]
PLAY RECAP *********************************************************************
web1 : ok=6 changed=1 ...
web2 : ok=2 changed=0 ...
...
AURORA STORE SUMMARY ***********************************************************
[aurora-infra] remediate-web.yml: SUCCEEDED in 9 s. Hosts: 2. With changes: web1. With failures: none.(The exact format of the ansible-rulebook lines depends on the version.) The last line is written by the aurora_store.infra.summary callback from Lesson 10.3, because the playbook uses the project's ansible.cfg: with AURORA_SUMMARY_WEBHOOK set, the Operations channel would have found out about the remediation. That's the essential complement to an automatic remediation: people need to know about it.
Check that the store responds (curl -s http://192.168.56.11/ | grep Version) and test the throttle: stop nginx on web1 again before 10 minutes have passed. This time, the rule does not fire again: the web server stays down (the load balancer keeps serving with web2) until the window has passed or a person steps in. Start it by hand with ssh web1 sudo systemctl start nginx.
9.3. An Alertmanager alert
Stop the API container on api1:
As long as there's no Alertmanager, simulate its notification with curl (it's Alertmanager's webhook format, simplified to the fields the rule uses):
curl -s -X POST http://127.0.0.1:5050/ -H 'Content-Type: application/json' -d '{
"version": "4",
"status": "firing",
"receiver": "eda",
"alerts": [
{
"status": "firing",
"labels": {"alertname": "AuroraCatalogDown", "instance": "api1:8080", "severity": "critical"},
"annotations": {"summary": "Catalog API not responding"},
"startsAt": "2026-11-26T03:12:00Z"
}
]
}'The "Restart the catalog API that is down" rule fires and remediate-catalog.yml restarts the container on api1. Check it with ssh api1 sudo docker ps (the container is healthy again). Send another alert with "alertname": "DiskAlmostFull": the generic rule shows it, without acting.
Stop ansible-rulebook with Ctrl+C when you're done. In the lab you don't leave it running as a permanent service; in the final project you'll decide where it lives (section 11).
9.4. Saving the work
.gitignore+.venv-eda/.README.md: an "Event-Driven Ansible" section (requirements, how to start it, which rules exist and what they do).CHANGELOG.md, under[Unreleased]: thewatch-store.ymlrulebook, the remediation playbooks, theknown_hostspath withplaybook_dir.
git switch -c eda
git add rulebooks/ playbooks/remediate-web.yml playbooks/remediate-catalog.yml \
inventories/lab/group_vars/all/connection.yml inventories/production/group_vars/all/connection.yml \
.gitignore README.md CHANGELOG.md
git commit -m "Event-Driven Ansible: watch-store rulebook and remediations for the website and the catalog API"
git push -u origin edaCI will check the style (ansible-lint recognizes rulebooks and validates their structure) and the syntax of the two new playbooks (--syntax-check doesn't need ansible_eda).
run_playbook or run_job_template
run_playbook or run_job_templaterun_playbook runs the playbook on the machine where ansible-rulebook runs, with its SSH and Vault credentials. It's the simplest way to start, but it repeats all the drawbacks AWX solved in Module 7. The alternative is for the rule to launch an AWX template:
action:
run_job_template:
name: "Aurora - Remediate web"
organization: "Aurora Store"
job_args:
extra_vars:
aurora_eda_url: "{{ event.url_check.url }}"ansible-rulebook connects to AWX with --controller-url and --controller-token (a token for a service user with Execute permission only on the remediation templates, like gitea-ci in Lesson 8.3). There's also run_workflow_template for launching a workflow.
run_playbook |
run_job_template |
|
|---|---|---|
| Where it runs | On the ansible-rulebook machine |
In AWX, with the aurora-ee EE |
| SSH and Vault credentials | On the ansible-rulebook machine |
In AWX (protected credentials) |
| Auditing | The ansible-rulebook output |
AWX job history |
| Permissions | Those of the account running it | AWX RBAC |
| Notifications | Whatever you program (the summary callback) |
AWX's |
| Human approval | No | Yes, with a workflow with an approval node |
| Getting started | Immediate | You have to create the templates |
In the lab you've used run_playbook to understand the mechanics. In a real environment, run_job_template is the recommended choice: the machine listening for events doesn't need to hold SSH keys or Vault passwords, and every remediation is recorded in AWX like any other job. The remediation templates (with the aurora_eda_url variable instead of ansible_eda, or accepting both) are part of the final project's design.
- EDA on the platform: EDA controller
ansible-rulebook in a terminal is fine for learning and testing. In production you need the same as with playbooks: an always-on service, with an interface, permissions and logging. That's the EDA controller (Event-Driven Ansible controller), part of Ansible Automation Platform since 2023 (and integrated into the unified AAP 2.5 interface), whose upstream project is eda-server. Its concepts will sound familiar:
| EDA controller concept | Equivalent you know |
|---|---|
| Project | A Git repository with rulebooks (like AWX projects) |
| Decision Environment | A container image with ansible-rulebook, Java and the source collections; it's built with ansible-builder, like an EE (Lesson 7.6) |
| Rulebook Activation | A permanently running rulebook, with its decision environment, its inventory and its variables |
| Credentials | Access to AWX (for run_job_template), to image registries, to Git |
| Event streams | Managed endpoints for receiving events over HTTP, with authentication |
| Log of fired rules | The history of which event triggered which action |
In AAP, the pattern is exactly the one from section 10: the EDA controller decides and the automation controller (AWX) executes. Setting up eda-server in the lab is beyond the scope of the course (it consumes resources awx1 doesn't have to spare); what matters is that the rulebooks you write are the same.
- Best practices: making sure the remediation doesn't make the incident worse
A badly designed automatic remediation can turn a small incident into a big one: restarting a service that can't start in a loop, restarting every server at once, or masking a real problem that nobody ever sees. Aurora's rules:
| Practice | Why | In Aurora |
|---|---|---|
Limit the frequency (throttle) |
It prevents loops: event → action → same event → action… | 10 and 15 minutes per URL/instance |
| Check again before acting | The event may be stale or a false positive | uri + meta: end_host |
| Verify afterwards and fail if it didn't work | A remediation that fixes nothing must escalate to a person | The "Wait for the ... to respond again" task |
| Always notify people | Automatic actions get reviewed too; a daily restart is a symptom | summary callback with a webhook; in AWX, notifications |
| Small, safe, idempotent actions | Restarting a service, yes; restoring a database, no | Only restarts of one service on one host |
| One host at a time | Don't cause a total outage trying to fix a partial one | The playbook only acts on the event's host |
| Human approval for anything risky | Some actions require judgment | run_workflow_template with an approval node (Lesson 7.5) |
| Don't fight with deployments | During a deployment, a web server may not respond for a moment | Web servers are never stopped in webservers.yml (only reload); for long maintenance windows, stop the rulebook or add a "maintenance" condition |
| Protected sources | Whoever can send events can trigger actions | alertmanager on 127.0.0.1; in production, firewall, TLS and a token (the webhook source supports a token) |
| Least privilege | The EDA machine is a valuable target | run_job_template with an AWX user that can only launch the remediation templates |
| Test the rules without servers | Conditions have bugs too | ansible.eda.generic/range, --print-events, curl with sample events |
Warning. Automatic remediation touches production systems without anyone approving it at the time. Before enabling it outside the lab, review every rule and every playbook with the team responsible for the service, define who receives the notifications and document how to disable it if there are problems.
Common Mistakes and Tips
ansible-rulebookwon't start because of Java:JAVA_HOMEisn't set or points to a JRE without the piecesdrools_jpyneeds. Install the JDK (openjdk-17-jdk) and checkansible-rulebook --version.- "Could not find source plugin" or similar: the
ansible.edacollection isn't in the pathsansible-rulebooklooks in. ExportANSIBLE_COLLECTIONS_PATHwith thecollections/path. - Conditions that are never met: almost always, the event doesn't have the shape you think it does. Run with
--print-eventsand copy the exact path (event.url_check.status, notevent.status). - Braces in conditions:
condition: "{{ event.i == 3 }}"is a mistake; conditions go without{{ }}, likewhen:. In action arguments, on the other hand, they are used. - Remediation loops: a rule without
throttleon a periodic source triggers the action on every check. Always add it. - The playbook can't find roles, collections or
known_hosts: it runs from a temporary directory. Use an absoluteANSIBLE_CONFIGand paths that don't depend on the working directory (section 7.1). - Missing Vault passwords: the
ansible-rulebooksession must haveANSIBLE_VAULT_IDENTITY_LIST; if you start it as a service, the service needs it too. Another reason forrun_job_template. - Remediating what you don't understand: if a web server goes down every day and the rulebook restarts it every day, the problem is still there. Review the notifications.
- Tip: start with rules that only notify (
print_event,debug, or a notification) for a few weeks; once you trust that they fire when they should, swap the action for the remediation.
Exercises
Exercise 1: only notify when both web servers are down
Add a rule to the first ruleset that, if web1 and web2 are down at the same time, doesn't try to remediate anything (it would be a bigger problem: network, load balancer, database) and just shows a "major incident" message. Hint: condition: all:.
Exercise 2: a webhook source for testing
Write a rulebook /tmp/webhook-test.yml with the ansible.eda.webhook source on 127.0.0.1:5000 that, when it receives a JSON document with {"action": "check", "host": "web2"}, checks the connection to that host (the ansible.builtin.ping module). Test it with curl. Is the run_module action better, or a small playbook with run_playbook?
Exercise 3: design
The team proposes a rule that, when the "PostgreSQL is not accepting connections" alert fires on db1, restarts PostgreSQL automatically. Analyze the risks and propose a safer design.
Solutions
Exercise 1. In the rules of "Watch the Aurora Store web servers", before the remediation rule (so it's evaluated first):
- name: Major incident if both web servers are down
condition:
all:
- event.url_check.url == "http://192.168.56.11/" and event.url_check.status == "down"
- event.url_check.url == "http://192.168.56.12/" and event.url_check.status == "down"
action:
debug:
msg: "MAJOR INCIDENT: web1 and web2 are not responding. No automatic remediation."With all:, the rules engine remembers events: the rule is met once it has received one event that meets the first condition and another that meets the second, even if they arrive separately (each url_check emits one event per URL). Watch out for the interaction with the remediation rule: the first down event doesn't yet complete the all: rule, so it triggers the remediation for that web server; the second completes all: and, since that rule comes first and only the first matching rule runs, the second web server is no longer remediated. The result depends on the order in which the events arrive. If you wanted a double outage to never trigger a remediation, you'd have to reorganize the rules (for example, delaying the individual remediation with throttle.once_after and checking the state of the other web server in the playbook). It's a good example of how rules involving several events need careful testing with --print-events.
Exercise 2. A temporary playbook, playbooks/check-on-demand.yml (in playbooks/, so that the known_hosts path based on playbook_dir works):
---
- name: Check a server on demand
hosts: "{{ ansible_eda.event.payload.host }}"
gather_facts: false
tasks:
- name: Check the connection
ansible.builtin.ping:And /tmp/webhook-test.yml:
---
- name: Test webhook
hosts: all
sources:
- ansible.eda.webhook:
host: 127.0.0.1
port: 5000
rules:
- name: Check a host on demand
condition: event.payload.action == "check" and event.payload.host is defined
action:
run_playbook:
name: playbooks/check-on-demand.yml.venv-eda/bin/ansible-rulebook -r /tmp/webhook-test.yml -i "$PWD/inventories/lab" --print-events
# In another terminal:
curl -s -X POST http://127.0.0.1:5000/ -H 'Content-Type: application/json' \
-d '{"action": "check", "host": "web2"}'The webhook source puts the request's JSON body in event.payload (and the headers and path in event.meta). The playbook uses the event data as the hosts pattern: if the name doesn't exist in the inventory, there are simply no hosts and nothing is done. The exercise suggested the run_module action, which runs a single module like an ad hoc command; but which hosts it targets depends on the ruleset's hosts and on the ansible-rulebook version, whereas with a playbook the target is explicit: it's the more predictable option. Notice the risk: anyone who can reach 127.0.0.1:5000 can trigger the action. In a real environment, the webhook source must use token (and TLS with certfile/keyfile), and the actions must validate the event data before using it (for example, that host is in a list of allowed servers). Delete the temporary playbook when you're done.
Exercise 3. Risks of restarting PostgreSQL automatically: if it isn't accepting connections because it's out of disk space, recovering after a crash or in the middle of a backup, restarting it can prolong or worsen the problem and even damage data; in addition, it would cut off all the store's connections, and it's a single service (no other replica to serve in the meantime). A safer design:
- The rule launches a read-only diagnosis (service status, disk space, the last lines of the PostgreSQL log) and sends it to the Operations channel.
- If remediating is considered worthwhile, the rule launches an AWX workflow with an approval node (Lesson 7.5): the diagnosis first, then approval by a person from Operations, and the restart only if someone approves it.
- A generous
throttle(for example, once an hour) and an immediate notification to the person on call.
It's the direct application of the rule from section 12: automate the first response, not the risky decision.
Conclusion
Event-Driven Ansible turns Ansible into a system that reacts: the sources in the ansible.eda collection produce events, rulebooks group into rulesets the rules that evaluate them with brace-free conditions, and actions run playbooks, modules or AWX templates. You've installed ansible-rulebook with its Java rules engine, you've written watch-store.yml to restart nginx when an Aurora web server stops responding and the catalog API when an Alertmanager alert arrives, and you've seen that what's decisive isn't the rule, but the precautions: limiting the frequency with throttle, checking again before acting, verifying afterwards, acting on a single host, always notifying people and reserving anything risky for workflows with approval, preferably with run_job_template and the EDA controller. With this you close Module 10: Aurora Store has its own modules and plugins in the aurora_store.infra collection, a staging inventory that discovers itself on AWS, tools that launch Ansible from Python and an automatic first response to incidents. You've gone through the whole Ansible automation cycle, from the first ping to event-driven remediation, but each piece has been built lesson by lesson and many have been noted as pending: staging and production in AWX, Terraform's remote state, monitoring with Prometheus and Alertmanager, backups, the ansible-core upgrade. In Module 11: Final Project you'll start with the lesson Final Project: Designing the Aurora Store Infrastructure, where you'll bring together everything you've learned to design, as a coherent whole, the complete Aurora Store infrastructure and the plan for taking it to production.
Ansible Course: From Beginner to Advanced
Module 1: Introduction to Ansible
- What Is Ansible?
- Installing Ansible
- Setting Up the Practice Lab
- Ansible Architecture
- Basic Ansible Commands
Module 2: Ansible Fundamentals
- Inventory Files
- Inventory Variables: group_vars and host_vars
- Configuring Ansible (ansible.cfg)
- Ad Hoc Commands
- Ansible Modules
- Collections and Fully Qualified Names (FQCN)
Module 3: Playbooks
- Introduction to Playbooks
- Essential YAML for Ansible
- Writing Your First Playbook
- Playbook Structure
- Variables and Facts
- Conditionals and Loops
- Registering Results and Debugging Playbooks
Module 4: Roles
- Introduction to Roles
- Creating Roles
- Role Directory Structure
- Using Roles in Playbooks
- Reusing Tasks: include and import
- Role Dependencies and Argument Validation
Module 5: Advanced Playbook Techniques
- Handlers
- Jinja2 Templates
- Filters and Lookups
- Ansible Vault
- Error Handling
- Tags and Selective Execution
- Rolling Deployments and Delegation
- Optimizing Playbooks
Module 6: Ansible Galaxy
- What Is Ansible Galaxy?
- Using Ansible Galaxy
- Managing Dependencies with requirements.yml
- Creating and Sharing Roles
- Creating Your Own Collections
Module 7: Ansible Tower, AWX and Automation Platform
- Introduction to Ansible Tower and AWX
- Installing AWX
- Using AWX: Job Templates and Jobs
- Managing Projects and Inventories
- Credentials, Permissions (RBAC) and Workflows
- Execution Environments and ansible-navigator
Module 8: Ansible for DevOps
- Ansible and Docker
- Ansible and Kubernetes
- CI/CD with Ansible
- Ansible in Cloud Environments
- Ansible and Terraform
Module 9: Ansible Best Practices
- Code Organization
- Security Best Practices
- Performance Tuning
- Code Quality: ansible-lint and yamllint
- Testing Ansible Code with Molecule
Module 10: Advanced Ansible Topics
- Custom Modules
- Dynamic Inventory
- Ansible Plugins
- The Ansible API and ansible-runner
- Event-Driven Ansible
