Skip to content

Documentation

Function recipes

Complete, copy-paste examples of functions on rules. Each recipe gives the function's function.json and code, the secrets to set, and the hook settings for the rule, both as the console shows them and as JSON. Recipes that change hosts also give the rule's remediation or actions.

All recipes use only the Python standard library and the SDK (lib/lea_function.py), so they work on air-gapped servers with nothing to install.

Before you start

  • Read What functions are and do Your first function once. This guide assumes you know how to upload, test and attach a function.
  • Every example address (servicedesk.example.internal, ntp1.corp.example, ...) is a placeholder. Replace it with yours.
  • Your internal systems' APIs differ from the ones shown. Each recipe says which lines to adapt.

How to use a recipe

  1. Open Settings → Functions and click New function.

  2. In Name, type the recipe's function name exactly (for example open_ticket). In Starter, pick python (or shell for the shell recipe).

  3. Click Download starter (.zip) and unzip it on your computer.

  4. Replace function.json and main.py (or main.sh) with the recipe's files. Keep lib/lea_function.py.

  5. Optional: run it locally (see Writing function code):

    python3 lib/lea_function.py run . --event sample_event.json --secret NAME=test-value
    

    The starter's sample_event.json is about a certificate rule. For a realistic run, copy the Event sent from a test run on the server into a file and use that.

  6. Pack the folder: tar czf open_ticket.tgz open_ticket (or a .zip), then in Settings → Functions click Upload, Choose .tgz or .zip, Validate, and Upload and activate.

  7. Set the recipe's secrets on the function's card (pencil icon next to each NOT SET).

  8. Click Test run on the card and run it on a real result.

  9. Attach it to the rule with the hook settings given (rule editor → Functions → Add function), and save.

Starters you can build on

Some recipes are also ready-made starters. In New function, pick one under Starter and click Download starter (.zip): you get the working code, a README.md that explains it, the SDK and, where the recipe changes hosts, a rule.json with the matching rule. Starters come with every LEA Platform installation and never run by themselves: nothing happens until you upload a function made from one and attach it to a rule.

StarterWhat it showsRecipe
pythonThe smallest function: records why a rule failsYour first function
shellThe same in POSIX shellYour first function
chat_alertSecrets and a call to an HTTPS servicePost a message to a chat webhook
host_reportAn argument, a returned file and an action that saves it on the hostnone: see its README.md
choose_actionReading the output and choosing between two fixesLet the function choose an action
mtls_caA complete certificate flow with an internal CAIssue host certificates from an internal CA

With the command line: lea functions init ./my_alert --template chat_alert.

Create the matching rule

A starter that changes hosts (host_report, choose_action, mtls_ca) needs a rule with the actions it returns. You do not have to unzip anything to see it:

  • New function: when you pick such a starter, Matching rule shows its rule.json with a copy button.
  • Function card in Settings → Functions: Matching rule shows the rule.json of the uploaded function. Create rule opens the rule editor with it filled in; review it and click Save rule. This works for your own functions too: put a rule.json next to function.json before you upload.
  • Test run: when a run fails, Matching rule opens the same view.

To use the function in a rule you already have, add it there (rule editor → Functions → Add function). When the rule lacks an action the function returns, the editor warns you; Add from rule.json adds the missing actions and the hook settings from the matching rule. Review them and save.

Calling internal HTTPS services

Several recipes call an internal HTTPS API. They follow the same safe pattern:

  • The address and token are secrets, never hard-coded.
  • Only https:// addresses are accepted, and certificate checks stay on.
  • If your service uses a certificate from your own CA, paste that CA certificate (PEM text) into an optional ..._CA_BUNDLE secret.
  • A proxy is used only if your operator set one on the LEA server and the function lists HTTPS_PROXY in env. The recipes list HTTPS_PROXY and NO_PROXY. If your site has no proxy, they are simply empty.

Open a ticket when a rule fails

What it does: when a rule fails on a host, opens a ticket in your internal service desk and records the ticket number on the result. Then on the host: Record only. Nothing changes on hosts.

When to use it: failures that a person must handle, for rules without a safe automatic fix.

The function runs once per distinct failure: while the host sends the same output, the earlier ticket number is reused and no new ticket is opened. If the output changes (for example, it contains a time), a new run starts, at most 12 per hour. The ticket carries a correlation_id (host and rule) so your service desk can merge duplicates.

function.json

{
  "name": "open_ticket",
  "description": "Opens a ticket in the internal service desk when a rule fails",
  "entrypoint": ["python3", "main.py"],
  "timeout": 30,
  "args": [
    {"name": "queue", "type": "string", "default": "SECOPS", "description": "Service desk queue"},
    {"name": "dry_run", "type": "boolean", "default": false, "description": "Show the ticket without creating it"}
  ],
  "secrets": ["TICKET_API_URL", "TICKET_API_TOKEN", "TICKET_CA_BUNDLE"],
  "env": ["HTTPS_PROXY", "NO_PROXY"],
  "ai_settings": false
}

main.py

import json
import os
import ssl
import sys
import urllib.error
import urllib.request

sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), 'lib'))
import lea_function as lea

MAX_OUTPUT = 4000


def post_json(url, token, body, ca_bundle):
    if not url.startswith('https://'):
        lea.fail('TICKET_API_URL must start with https://')
    context = ssl.create_default_context(cadata=ca_bundle) if ca_bundle else ssl.create_default_context()
    request = urllib.request.Request(url, data=json.dumps(body).encode('utf-8'), method='POST', headers={
        'Authorization': f'Bearer {token}', 'Content-Type': 'application/json', 'Accept': 'application/json'})
    try:
        with urllib.request.urlopen(request, timeout=15, context=context) as response:
            raw = response.read(1024 * 1024).decode('utf-8', 'replace')
    except urllib.error.HTTPError as e:
        lea.fail(f'the service desk refused the ticket: HTTP {e.code} {e.read(300).decode("utf-8", "replace")}')
    except (urllib.error.URLError, OSError) as e:
        lea.fail(f'the service desk is not reachable: {e}')
    try:
        reply = json.loads(raw) if raw.strip() else {}
    except ValueError:
        reply = {}
    return reply if isinstance(reply, dict) else {}


ev = lea.event()
if not ev.failed:
    lea.nothing(f'{ev.rule.name} does not fail on {ev.client.hostname}; no ticket')

output = str(ev.result.stdout or '')[:MAX_OUTPUT]
ticket = {
    'queue': str(ev.args.get('queue') or 'SECOPS'),
    'title': f'[LEA] {ev.rule.name} fails on {ev.client.hostname}'[:200],
    'description': (
        f'Rule: {ev.rule.name}\nHost: {ev.client.hostname}\nSeverity: {ev.rule.severity}\n'
        f'Reason: {ev.result.expect_err or "-"}\n\nOutput (first {MAX_OUTPUT} characters):\n{output}'
    ),
    'priority': {'critical': 1, 'high': 2, 'medium': 3}.get(ev.rule.severity, 4),
    'correlation_id': f'lea-{ev.client.uuid}-{ev.rule.id}',
}

if ev.args.get('dry_run'):
    lea.ok(f'Dry run: would open a ticket in {ticket["queue"]}', ticket=ticket)

url = lea.secret('TICKET_API_URL')
token = lea.secret('TICKET_API_TOKEN')
if not url or not token:
    lea.fail('set TICKET_API_URL and TICKET_API_TOKEN under Settings → Functions')

reply = post_json(url, token, ticket, lea.secret('TICKET_CA_BUNDLE'))
number = str(reply.get('id') or reply.get('number') or 'unknown')
link = reply.get('url')
lea.ok(f'Ticket {number} opened for {ev.client.hostname}',
       ticket=number, queue=ticket['queue'],
       markdown=f'[Open ticket {number}]({link})' if link else f'Ticket **{number}** in queue {ticket["queue"]}')

Adapt: the fields of ticket to what your service desk expects, and the line that reads id, number and url from its answer.

Secrets

SecretValue
TICKET_API_URLThe address that creates a ticket, for example https://servicedesk.example.internal/api/tickets
TICKET_API_TOKENAn API token of a service account that may create tickets
TICKET_CA_BUNDLEOptional: your internal CA certificate (PEM), if the service desk uses one

Attach it to the rule

Field in the consoleValue
Functionopen_ticket
Run whenVerdict fails
for results ofvalidations
Only when the output matchesno conditions
queueSECOPS (or another queue)
dry_runoff
Then on the hostRecord only
"functions": [
  {"function": "open_ticket", "when": "fail", "on": ["validation"], "match": [], "args": {"queue": "SECOPS"}, "deliver": "none"}
]

Important: A test run executes the real code. Turn on dry_run in the test run's Arguments so that testing does not open real tickets.

Post a message to a chat webhook

What it does: posts a message to an internal chat channel (Mattermost, Rocket.Chat or any chat with incoming webhooks) when a rule fails, and records that it did. Then on the host: Record only.

When to use it: to alert a team quickly about one specific, serious failure. This example alerts only when SSH root login is explicitly turned on, using a condition on the output.

Tip: This recipe is the chat_alert starter. Pick it in New function instead of copying the files below.

function.json

{
  "name": "chat_alert",
  "description": "Posts a message to the team chat when a rule fails",
  "entrypoint": ["python3", "main.py"],
  "timeout": 20,
  "args": [],
  "secrets": ["CHAT_WEBHOOK_URL", "CHAT_CA_BUNDLE"],
  "env": ["HTTPS_PROXY", "NO_PROXY"],
  "ai_settings": false
}

main.py

import json
import os
import ssl
import sys
import urllib.error
import urllib.request

sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), 'lib'))
import lea_function as lea

ev = lea.event()
url = lea.secret('CHAT_WEBHOOK_URL')
if not url:
    lea.fail('set CHAT_WEBHOOK_URL under Settings → Functions')
if not url.startswith('https://'):
    lea.fail('CHAT_WEBHOOK_URL must start with https://')

state = 'FAILS' if ev.failed else 'PASSES' if ev.passed else 'reported'
text = f'LEA Platform: {ev.rule.name} {state} on {ev.client.hostname} (severity {ev.rule.severity})'
if ev.failed and ev.result.expect_err:
    text += f'\nReason: {ev.result.expect_err}'

ca_bundle = lea.secret('CHAT_CA_BUNDLE')
context = ssl.create_default_context(cadata=ca_bundle) if ca_bundle else ssl.create_default_context()
request = urllib.request.Request(url, data=json.dumps({'text': text}).encode('utf-8'), method='POST',
                                 headers={'Content-Type': 'application/json'})
try:
    with urllib.request.urlopen(request, timeout=10, context=context) as response:
        response.read(1000)
except urllib.error.HTTPError as e:
    lea.fail(f'the chat server refused the message: HTTP {e.code}')
except (urllib.error.URLError, OSError) as e:
    lea.fail(f'the chat server is not reachable: {e}')

lea.ok(f'Posted to chat: {ev.rule.name} {state} on {ev.client.hostname}', message=text)

Adapt: the message body {'text': text} if your chat system expects another format.

Secrets

SecretValue
CHAT_WEBHOOK_URLThe incoming webhook address of the channel. It usually contains a secret token, which is why it is a secret
CHAT_CA_BUNDLEOptional: your internal CA certificate (PEM)

Attach it to the rule

On the rule "SSH Root Login Disabled":

Field in the consoleValue
Functionchat_alert
Run whenVerdict fails
for results ofvalidations
Only when the output matchescontains (regex), stdout, (?mi)^[ \t]*PermitRootLogin[ \t]+yes
Then on the hostRecord only
"functions": [
  {"function": "chat_alert", "when": "fail", "on": ["validation"],
   "match": [{"re": {"stdout": "(?mi)^[ \\t]*PermitRootLogin[ \\t]+yes"}}], "args": {}, "deliver": "none"}
]

In JSON every backslash is written twice (\\t). In the console field you type it once (\t).

Tip: To also post when the host is fixed, remove the condition and set Run when to Every result. Because a function does not run again for identical output, it posts once per change, not on every check.

Add the host owner from the CMDB

What it does: when a rule fails, looks up the host in your CMDB and adds the owner, team and contact to the result, so whoever reads the failure knows whom to call. Then on the host: Record only.

When to use it: on any rule whose failures are handled by the host's owner. It works next to other Record only functions on the same rule, such as open_ticket.

function.json

{
  "name": "cmdb_owner",
  "description": "Adds the host owner from the CMDB to failing results",
  "entrypoint": ["python3", "main.py"],
  "timeout": 20,
  "args": [],
  "secrets": ["CMDB_URL", "CMDB_TOKEN", "CMDB_CA_BUNDLE"],
  "env": ["HTTPS_PROXY", "NO_PROXY"],
  "ai_settings": false
}

main.py

import json
import os
import re
import ssl
import sys
import urllib.error
import urllib.parse
import urllib.request

sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), 'lib'))
import lea_function as lea

HOSTNAME_RE = re.compile(r'^[A-Za-z0-9.-]{1,253}$')

ev = lea.event()
host = str(ev.client.hostname or '')
if not HOSTNAME_RE.match(host):
    lea.fail(f'unexpected host name {host[:80]!r}, not looked up')

base = lea.secret('CMDB_URL')
token = lea.secret('CMDB_TOKEN')
if not base or not token:
    lea.fail('set CMDB_URL and CMDB_TOKEN under Settings → Functions')
if not base.startswith('https://'):
    lea.fail('CMDB_URL must start with https://')

ca_bundle = lea.secret('CMDB_CA_BUNDLE')
context = ssl.create_default_context(cadata=ca_bundle) if ca_bundle else ssl.create_default_context()
url = f'{base.rstrip("/")}/hosts/{urllib.parse.quote(host)}'
request = urllib.request.Request(url, headers={'Authorization': f'Bearer {token}', 'Accept': 'application/json'})
try:
    with urllib.request.urlopen(request, timeout=10, context=context) as response:
        record = json.loads(response.read(1024 * 1024).decode('utf-8', 'replace'))
except urllib.error.HTTPError as e:
    if e.code == 404:
        lea.ok(f'{host} is not in the CMDB', owner=None)
    lea.fail(f'the CMDB answered HTTP {e.code}')
except (urllib.error.URLError, OSError, ValueError) as e:
    lea.fail(f'the CMDB lookup failed: {e}')

record = record if isinstance(record, dict) else {}
owner = str(record.get('owner') or 'unknown')[:200]
team = str(record.get('team') or 'unknown')[:200]
contact = str(record.get('contact') or '-')[:200]
lea.ok(f'Owner of {host}: {owner} ({team})', owner=owner, team=team, contact=contact,
       markdown=f'| Owner | Team | Contact |\n|---|---|---|\n| {owner} | {team} | {contact} |')

Adapt: the address /hosts/NAME and the field names owner, team and contact to your CMDB.

Secrets

SecretValue
CMDB_URLThe CMDB API base address, for example https://cmdb.example.internal/api
CMDB_TOKENA read-only API token
CMDB_CA_BUNDLEOptional: your internal CA certificate (PEM)

Attach it to the rule

Field in the consoleValue
Functioncmdb_owner
Run whenVerdict fails
for results ofvalidations
Only when the output matchesno conditions
Then on the hostRecord only
"functions": [
  {"function": "cmdb_owner", "when": "fail", "on": ["validation"], "match": [], "args": {}, "deliver": "none"}
]

The result shows only the artifact of the first function attached to the rule. The others are listed on their function cards under Recent runs.

Send a host-specific fix with the remediation

What it does: the rule checks the SSH login banner. When it is missing, the function writes a banner with the host's own name and site, and the rule's remediation installs it. Then on the host: Run the remediation with the output.

When to use it: the fix is the same command on every host, but the content differs per host (site, owner, server addresses, limits).

How the data reaches the host: the function returns the file issue.net in files. On the host's next check-in, the remediation runs with issue.net and lea_artifact.json in its working folder.

function.json

{
  "name": "login_banner",
  "description": "Writes a login banner with the host's name and site for the remediation",
  "entrypoint": ["python3", "main.py"],
  "timeout": 10,
  "args": [
    {"name": "organization", "type": "string", "default": "Example Corp", "description": "Organization name in the banner"},
    {"name": "contact", "type": "string", "default": "security@example.internal", "description": "Where users report problems"}
  ],
  "secrets": [],
  "env": [],
  "ai_settings": false
}

main.py

import os
import re
import sys

sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), 'lib'))
import lea_function as lea

HOSTNAME_RE = re.compile(r'^[A-Za-z0-9.-]{1,253}$')
SITES = {'fra': 'Frankfurt data center', 'nyc': 'New York office'}

ev = lea.event()
host = str(ev.client.hostname or '')
if not HOSTNAME_RE.match(host):
    lea.fail(f'unexpected host name {host[:80]!r}')

site = SITES.get(host[:3].lower(), 'unknown site')
organization = str(ev.args.get('organization') or '')[:100]
contact = str(ev.args.get('contact') or '')[:100]
banner = (
    f'Authorized use only. {organization}\n'
    f'Host: {host} ({site})\n'
    f'Activity on this system is monitored. Report problems to {contact}.\n'
)
lea.ok(f'Banner prepared for {host} ({site})', site=site, files={'issue.net': banner})

Adapt: the SITES table (here the site is the first three letters of the host name), or look the site up in your CMDB as in the previous recipe.

Secrets

None.

The rule's validation and remediation

In the rule editor: Validations reads the banner, Expectations expects the text, Remediations installs the file the function sent.

"cmd": {
  "validation": [{"command": "cat /etc/issue.net", "system": ["Linux"]}],
  "expect": [{"re": {"stdout": "Authorized use only"}, "err": "the login banner is missing"}],
  "remedy": [{"command": "[ -s issue.net ] && install -m 644 issue.net /etc/issue.net", "system": ["Linux"]}]
}

The remediation starts with [ -s issue.net ]: if the function failed, the file is missing, so the remediation stops without touching the host and is reported as failed.

Attach it to the rule

Field in the consoleValue
Functionlogin_banner
Run whenVerdict fails
for results ofvalidations only
Only when the output matchesno conditions
organization, contactyour values
Then on the hostRun the remediation with the output
"functions": [
  {"function": "login_banner", "when": "fail", "on": ["validation"], "match": [],
   "args": {"organization": "Example Corp", "contact": "security@example.internal"}, "deliver": "remedy"}
]

Warning: The remediation is sent even when the function failed (then lea_artifact.json contains the error and the function's files are missing). Always check that the file exists before you use it, as above. Try the rule on a test group of hosts first.

What you see: the result shows the Artifact with "Banner prepared for ...". The host's next result is a remediation result; on the result page, Last remedy shows REMEDIATED and the banner in its output.

Let the function choose an action

What it does: the rule checks that the time service chronyd runs and uses your site's time server. The function reads the output and picks the right fix: install a new configuration when the server is wrong, or only restart the service when the configuration is fine but the service is not running. Then on the host: Let the function pick an action.

When to use it: there is more than one possible fix, and the right one depends on what the host reports.

Tip: This recipe is the choose_action starter, including the rule as rule.json. Pick it in New function instead of copying the files below.

function.json

{
  "name": "chrony_fix",
  "description": "Picks the right fix for chrony: new configuration or restart",
  "entrypoint": ["python3", "main.py"],
  "timeout": 10,
  "args": [
    {"name": "server", "type": "string", "default": "ntp1.corp.example", "description": "Site time server"}
  ],
  "secrets": [],
  "env": [],
  "ai_settings": false
}

main.py

import os
import re
import sys

sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), 'lib'))
import lea_function as lea

SERVER_RE = re.compile(r'^[A-Za-z0-9.-]{1,253}$')
MARKER = '--- chrony.conf ---'
CONFIG = """# Managed by LEA Platform (function chrony_fix)
server {server} iburst
driftfile /var/lib/chrony/drift
makestep 1.0 3
rtcsync
"""

ev = lea.event()
server = str(ev.args.get('server') or '')
if not SERVER_RE.match(server):
    lea.fail(f'the server argument {server[:80]!r} is not a host name')
missing = {'install_config', 'restart_chrony'} - set(ev.rule.actions or [])
if missing:
    lea.fail(f'the rule needs the actions {", ".join(sorted(missing))}')

output = str(ev.result.stdout or '')
processes, marker, config = output.partition(MARKER)
if not marker:
    lea.fail('unexpected output: the chrony.conf marker is missing')

if not re.search(rf'(?m)^(server|pool)[ \t]+{re.escape(server)}\b', config):
    lea.action('install_config', files={'chrony.conf': CONFIG.format(server=server)},
               summary=f'{ev.client.hostname}: installing chrony.conf with {server}')
if not re.search(r'(?m)^chronyd$', processes):
    lea.action('restart_chrony', summary=f'{ev.client.hostname}: chronyd is not running, restarting it')
lea.nothing(f'{ev.client.hostname}: nothing to fix')

Adapt: the CONFIG text to your standard chrony configuration.

Secrets

None.

The rule's validation and actions

The validation prints the running process names, a marker line, and the configuration. The actions are defined in the rule editor under Remediations → Actions (Add action, then set Action name and its command).

"cmd": {
  "validation": [{"command": "cat /proc/*/comm 2>/dev/null; echo '--- chrony.conf ---'; cat /etc/chrony/chrony.conf /etc/chrony.conf 2>/dev/null; true", "system": ["Linux"]}],
  "expect": [
    {"re": {"stdout": "(?m)^chronyd$"}, "err": "chronyd is not running"},
    {"re": {"stdout": "(?m)^(server|pool)[ \\t]+ntp1\\.corp\\.example\\b"}, "err": "chrony does not use the site time server"}
  ],
  "actions": {
    "install_config": [{"command": "if [ -d /etc/chrony ]; then dest=/etc/chrony/chrony.conf; else dest=/etc/chrony.conf; fi; cp -p \"$dest\" \"$dest.lea-backup\" 2>/dev/null; install -m 644 chrony.conf \"$dest\" && { systemctl restart chronyd 2>/dev/null || systemctl restart chrony; }", "system": ["Linux"]}],
    "restart_chrony": [{"command": "systemctl restart chronyd 2>/dev/null || systemctl restart chrony", "system": ["Linux"]}]
  }
}

The time server name appears twice: in the rule's expectation and in the hook's server argument. Keep them the same.

Attach it to the rule

Field in the consoleValue
Functionchrony_fix
Run whenVerdict fails
for results ofvalidations only
Only when the output matchesno conditions
serverntp1.corp.example
Then on the hostLet the function pick an action
"functions": [
  {"function": "chrony_fix", "when": "fail", "on": ["validation"], "match": [], "args": {"server": "ntp1.corp.example"}, "deliver": "action"}
]

What happens: the check fails → the function picks install_config or restart_chrony → on its next check-in the host runs that action, then the validation again, and reports both as one remediation result. Because only validations is ticked, the action's own result does not start the function again. If the host still fails, the next scheduled check starts over.

On the function card, the Delivered column shows action install_config or action restart_chrony.

Warning: install_config replaces the whole chrony configuration (a backup is kept as .lea-backup). Try the rule on a test group first.

Issue host certificates from an internal CA

What it does: gives every host a client certificate (for mutual TLS) from your internal CA, which only the LEA server can reach. The private key never leaves the host. The certificate is bound to the host's LEA identity and renewed 30 days before it expires. Then on the host: Let the function pick an action, in two steps.

This is a ready-made starter, mtls_ca. You do not write the code; you adapt the call to your CA.

Steps

  1. In Settings → Functions, click New function. Name: mtls_issue. Starter: mtls_ca. The wizard fills in the secrets CA_URL, CA_API_TOKEN, CA_BUNDLE and the argument days.

  2. Click Download starter (.zip) and unzip it. It contains main.py, rule.json (the matching rule) and a README.md that describes the CA call.

  3. Adapt main.py to your CA's API if needed. As shipped, it sends POST {"csr", "common_name", "days"} with Authorization: Bearer and the token, and accepts a PEM certificate or {"certificate": "PEM"} as the answer.

  4. Upload the folder (Upload), then set the secrets on the card:

    SecretValue
    CA_URLThe CA's signing address (https://...)
    CA_API_TOKENThe CA API token
    CA_BUNDLEOptional: the CA certificate (PEM) to trust for the CA's own HTTPS
  5. Create the rule: on the function card, click Matching rule → Create rule (see Create the matching rule). Check the Functions section: the hook is already set. Click Save rule.

  6. Add the rule to a test group of hosts (see Groups).

The starter uses the Python package cryptography, which is installed on the LEA server (check Runtime). The hosts need openssl.

Hook settings (already in rule.json)

Field in the consoleValue
Functionmtls_issue
Run whenVerdict fails
for results ofvalidations and remediations and actions
days30
Then on the hostLet the function pick an action
"functions": [
  {"function": "mtls_issue", "when": "fail", "on": ["validation", "remedy"], "deliver": "action"}
]

What happens

  1. The check fails (no certificate, or it expires within 30 days). The function sees no certificate request and picks the action request_csr.
  2. On its next check-in the host creates a private key (kept on the host) and a certificate request, and prints it.
  3. That action result starts the function again (this is why remediations and actions is ticked). It checks that the request is for this host's LEA identity, sends it to your CA, and picks the action install_cert with the certificate as the file host.crt.
  4. On the next check-in the host installs the certificate. The check passes.

On the function card, Delivered shows action request_csr, then action install_cert. The full technical description is in the Functions reference.

Record inventory when a rule passes

What it does: records the kernel version of every host and, if you want, sends it to your CMDB. It runs only when the value changes, so each run is a change record. Then on the host: Record only.

When to use it: to keep an inventory value current in another system, using a rule that passes normally.

function.json

{
  "name": "kernel_inventory",
  "description": "Records the kernel release and sends it to the CMDB when it changes",
  "entrypoint": ["python3", "main.py"],
  "timeout": 20,
  "args": [],
  "secrets": ["CMDB_URL", "CMDB_TOKEN", "CMDB_CA_BUNDLE"],
  "env": ["HTTPS_PROXY", "NO_PROXY"],
  "ai_settings": false
}

main.py

import json
import os
import re
import ssl
import sys
import urllib.error
import urllib.parse
import urllib.request

sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), 'lib'))
import lea_function as lea

HOSTNAME_RE = re.compile(r'^[A-Za-z0-9.-]{1,253}$')
RELEASE_RE = re.compile(r'^[0-9][0-9A-Za-z.+_~-]{0,99}$')

ev = lea.event()
host = str(ev.client.hostname or '')
lines = str(ev.result.stdout or '').strip().splitlines()
release = lines[0].strip() if lines else ''
if not HOSTNAME_RE.match(host) or not RELEASE_RE.match(release):
    lea.fail(f'unexpected host name or kernel release: {host[:80]!r} {release[:80]!r}')

base = lea.secret('CMDB_URL')
token = lea.secret('CMDB_TOKEN')
if not base or not token:
    lea.ok(f'{host} runs kernel {release}', kernel=release, cmdb='not configured')
if not base.startswith('https://'):
    lea.fail('CMDB_URL must start with https://')

ca_bundle = lea.secret('CMDB_CA_BUNDLE')
context = ssl.create_default_context(cadata=ca_bundle) if ca_bundle else ssl.create_default_context()
body = json.dumps({'kernel': release, 'seen': ev.result.ts, 'lea_uuid': ev.client.uuid}).encode('utf-8')
request = urllib.request.Request(f'{base.rstrip("/")}/hosts/{urllib.parse.quote(host)}/kernel', data=body, method='PUT',
                                 headers={'Authorization': f'Bearer {token}', 'Content-Type': 'application/json'})
try:
    with urllib.request.urlopen(request, timeout=10, context=context) as response:
        response.read(1000)
except urllib.error.HTTPError as e:
    lea.fail(f'the CMDB refused the update: HTTP {e.code}')
except (urllib.error.URLError, OSError) as e:
    lea.fail(f'the CMDB is not reachable: {e}')

lea.ok(f'{host} runs kernel {release}', kernel=release, cmdb='updated')

Adapt: the CMDB address and body. Without the CMDB_URL and CMDB_TOKEN secrets it only records the value in LEA Platform.

Secrets

SecretValue
CMDB_URLOptional: the CMDB API base address
CMDB_TOKENOptional: an API token that may update hosts
CMDB_CA_BUNDLEOptional: your internal CA certificate (PEM)

The rule

"cmd": {
  "validation": [{"command": "cat /proc/sys/kernel/osrelease", "system": ["Linux"]}],
  "expect": [{"re": {"stdout": "\\d+\\.\\d+"}, "err": "the kernel release could not be read"}]
}

The rule needs an expectation, so that its results are PASS. A rule without expectations has no verdict, and Verdict passes would never match (use Every result for such rules).

Attach it to the rule

Field in the consoleValue
Functionkernel_inventory
Run whenVerdict passes
for results ofvalidations
Only when the output matchesno conditions
Then on the hostRecord only
"functions": [
  {"function": "kernel_inventory", "when": "pass", "on": ["validation"], "match": [], "args": {}, "deliver": "none"}
]

To see the history of changes for one host, open the result and the Run history tab, then click a run to expand it: the runs where the kernel changed show the artifact.

A shell function

What it does: reports every result of a rule to an internal monitoring system with curl, as a shell script. Then on the host: Record only.

When to use it: your team prefers shell, or you call a simple HTTP endpoint. The server has sh, bash, curl, wget, openssl and python3, but no jq. The SDK reads event fields for you.

function.json

{
  "name": "monitor_report",
  "description": "Reports rule results to the internal monitoring system",
  "entrypoint": ["sh", "main.sh"],
  "timeout": 30,
  "args": [],
  "secrets": ["MONITOR_URL", "MONITOR_TOKEN", "MONITOR_CA_BUNDLE"],
  "env": ["HTTPS_PROXY", "NO_PROXY"],
  "ai_settings": false
}

The entrypoint starts the script through sh. This matters: uploads from a browser folder lose the "executable" permission.

main.sh

#!/bin/sh
set -eu

LEA="python3 lib/lea_function.py"
EVENT=$(cat)
field() { printf '%s' "$EVENT" | $LEA field "$1"; }

host=$(field client.hostname)
rule=$(field rule.name)
verdict=$(field verdict)
severity=$(field rule.severity)

if [ -z "${MONITOR_URL:-}" ] || [ -z "${MONITOR_TOKEN:-}" ]; then
    $LEA fail "set MONITOR_URL and MONITOR_TOKEN under Settings → Functions"
fi
case "$MONITOR_URL" in
    https://*) ;;
    *) $LEA fail "MONITOR_URL must start with https://" ;;
esac

ca_option=""
if [ -n "${MONITOR_CA_BUNDLE:-}" ]; then
    printf '%s\n' "$MONITOR_CA_BUNDLE" > "$TMPDIR/ca.pem"
    ca_option="--cacert $TMPDIR/ca.pem"
fi

curl -fsS --max-time 15 $ca_option -o /dev/null -G \
    -H "Authorization: Bearer $MONITOR_TOKEN" \
    --data-urlencode "host=$host" \
    --data-urlencode "check=$rule" \
    --data-urlencode "state=${verdict:-unknown}" \
    --data-urlencode "severity=$severity" \
    "$MONITOR_URL"

$LEA ok "Reported $rule (${verdict:-unknown}) on $host to monitoring" host="$host" state="${verdict:-unknown}"

Notes:

  • -o /dev/null keeps curl's answer out of the function's output. Only the last line may print to standard output.
  • --data-urlencode encodes the host and rule names safely; never paste host data into a URL by hand.
  • set -e stops the script at the first failing command, so a failing curl is recorded as an error with its message.
  • Temporary files go to $TMPDIR, which is deleted after the run.

Secrets

SecretValue
MONITOR_URLThe monitoring endpoint, for example https://monitor.example.internal/api/lea
MONITOR_TOKENIts API token
MONITOR_CA_BUNDLEOptional: your internal CA certificate (PEM)

Attach it to the rule

Field in the consoleValue
Functionmonitor_report
Run whenEvery result
for results ofvalidations
Only when the output matchesno conditions
Then on the hostRecord only
"functions": [
  {"function": "monitor_report", "when": "always", "on": ["validation"], "match": [], "args": {}, "deliver": "none"}
]

Because a function does not run again for identical output, the monitoring system hears about changes, not every check.

If something goes wrong

  • The test run shows ERROR with set ... under Settings → Functions: the secret is NOT SET, or you are testing a staged upload (those run without secrets).
  • CERTIFICATE_VERIFY_FAILED or curl: (60): set the ..._CA_BUNDLE secret to your internal CA certificate.
  • is not reachable or a timeout: the LEA server cannot reach the address. Check the address, the firewall, and the proxy settings with your operator.
  • The host did nothing after Let the function pick an action: see When a function does not work.