Skip to content

Commit

Permalink
[8.8] [ResponseOps][docs] add docs for new mustache lambdas and asJSO…
Browse files Browse the repository at this point in the history
…N for array (elastic#155417) (elastic#157668)

# Backport

This will backport the following commits from `main` to `8.8`:
- [[ResponseOps][docs] add docs for new mustache lambdas and asJSON for
array (elastic#155417)](elastic#155417)

<!--- Backport version: 8.9.7 -->

### Questions ?
Please refer to the [Backport tool
documentation](https://github.com/sqren/backport)

<!--BACKPORT [{"author":{"name":"Patrick
Mueller","email":"patrick.mueller@elastic.co"},"sourceCommit":{"committedDate":"2023-05-14T18:39:25Z","message":"[ResponseOps][docs]
add docs for new mustache lambdas and asJSON for array
(elastic#155417)\n\nresolves:
elastic#155408
Summary\r\n\r\nadds doc for function added in [adds mustache lambdas
and\r\narray.asJSON](elastic#150572
add docs for new mustache lambdas and asJSON for array
(elastic#155417)\n\nresolves:
elastic#155408
Summary\r\n\r\nadds doc for function added in [adds mustache lambdas
and\r\narray.asJSON](elastic#150572
add docs for new mustache lambdas and asJSON for array
(elastic#155417)\n\nresolves:
elastic#155408
Summary\r\n\r\nadds doc for function added in [adds mustache lambdas
and\r\narray.asJSON](elastic#150572"}}]}]
BACKPORT-->

Co-authored-by: Patrick Mueller <patrick.mueller@elastic.co>
  • Loading branch information
kibanamachine and pmuellr committed May 14, 2023
1 parent 9b26927 commit b37d329
Show file tree
Hide file tree
Showing 2 changed files with 212 additions and 9 deletions.
221 changes: 212 additions & 9 deletions docs/user/alerting/action-variables.asciidoc
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
[[rule-action-variables]]
== Rule action variables

Alerting rules can use the https://mustache.github.io/[Mustache] template syntax
(`{{variable name}}`) to pass values when its actions run.
Alerting rules can use the https://mustache.github.io/mustache.5.html[Mustache] template syntax
(`{{variable name}}`) to pass values when the actions run.

[float]
[[common-rule-action-variables]]
=== Common variables

The available variables differ by rule type, however there are some common variables:

Expand All @@ -20,7 +24,7 @@ Mustache also supports "triple braces" of the form `{{{variable name}}}`, which

[float]
[[general-rule-action-variables]]
=== General
==== General

All rule types pass the following variables:

Expand All @@ -34,7 +38,7 @@ All rule types pass the following variables:
[float]
[role="child_attributes"]
[[alert-summary-action-variables]]
=== Action frequency: Summary of alerts
==== Action frequency: Summary of alerts

If the rule's action frequency is a summary of alerts, it passes the following variables:

Expand Down Expand Up @@ -91,7 +95,7 @@ include::action-variables.asciidoc[tag=alerts-data]

[float]
[[alert-action-variables]]
=== Action frequency: For each alert
==== Action frequency: For each alert

If the rule's action frequency is not a summary of alerts, it passes the following variables:

Expand All @@ -100,15 +104,15 @@ If the rule's action frequency is not a summary of alerts, it passes the followi
`alert.actionSubgroup`:: The action subgroup of the alert that scheduled the action.
`alert.flapping`:: A flag on the alert that indicates whether the alert status is changing repeatedly.
`alert.id`:: The ID of the alert that scheduled the action.
`alert.uuid`:: A universally unique identifier for the alert. While the alert is active, the UUID value remains unchanged each time the rule runs. preview:[]
`alert.uuid`:: A universally unique identifier for the alert. While the alert is active, the UUID value remains unchanged each time the rule runs. preview:[]

[float]
[[defining-rules-actions-variable-context]]
==== Context
===== Context

If the rule's action frequency is not a summary of alerts, the rule defines additional variables as properties of the variable `context`. For example, if a rule type defines a variable `value`, it can be used in an action parameter as `{{context.value}}`.
If the rule's action frequency is not a summary of alerts, the rule defines additional variables as properties of the variable `context`. For example, if a rule type defines a variable `value`, it can be used in an action parameter as `{{context.value}}`.

For diagnostic or exploratory purposes, action variables whose values are objects, such as `context`, can be referenced directly as variables. The resulting value will be a JSON representation of the object. For example, if an action parameter includes `{{context}}`, it will expand to the JSON representation of all the variables and values provided by the rule type. To see alert-specific variables, use `{{.}}`.
For diagnostic or exploratory purposes, action variables whose values are objects, such as `context`, can be referenced directly as variables. The resulting value will be a JSON representation of the object. For example, if an action parameter includes `{{context}}`, it will expand to the JSON representation of all the variables and values provided by the rule type. To see all alert-specific variables, use `{{.}}`.

For situations where your rule response returns arrays of data, you can loop through the `context`:

Expand All @@ -125,3 +129,202 @@ triggering data was:
{{#context.hits}} - {{_source.message}}
{{/context.hits}}
--------------------------------------------------

[discrete]
[[enhance-mustache-variables]]
=== Enhancing Mustache variables

preview::[]

You can enhance the values contained in Mustache variables when the Mustache template is rendered by rendering objects as JSON or by using Mustache lambdas.

[discrete]
==== Rendering objects as JSON

Some connectors (such as the <<webhook-action-type,Webhook connector>>) expect JSON values to be passed as parameters when the connector is invoked.
The following capabilities are available:

- Array values referenced in braces have a predefined rendering by Mustache as string versions of the array elements, joined with a comma (`,`). To render array values as JSON, access the `asJSON` property of the array, instead of the array directly. For example, given a Mustache variable `context.values` that has the value `[1, 4, 9]` the Mustache template `{{context.values}}` will render as `1,4,9`, and the Mustache template `{{context.values.asJSON}}` will render as `[1,4,9]`.

- The <<parse-hjson-lambda,ParseHjson lambda>> Mustache lambda makes it easier to create JSON in your templates by using https://hjson.github.io/[Hjson], a syntax extension to JSON, rather than strict JSON.

[discrete]
==== Using Mustache lambdas

Mustache lambdas provide additional rendering capabilities for Mustache templates.
A Mustache lambda is formatted like a Mustache section. For example:

[source]
----
{{#EvalMath}} round(context.value, 1) {{/EvalMath}}
----

In that example, the lambda `EvalMath` is passed the text `round(context.value, 1)` and renders a rounded value of the `context.value` variable.
This pattern is used by all the provided Mustache lambdas described in the subsequent sections.

[discrete]
===== EvalMath

The EvalMath lambda will evaluate the text passed to it as <<canvas-tinymath-functions>>.

For example, when the Mustache variable `context.value` is `3.1234`, the following template will render as `3.1`:

[source]
----
{{#EvalMath}} round(context.value, 1) {{/EvalMath}}
----

This lambda can access Mustache variables without having to wrap them in `{{}}`.
However, if the value is in a string form (for example, an Elasticsearch numeric field whose source was indexed as a string), or could be escaped, escaping the value with triple quotes should allow this to work.
For example, if the Mustache variable `context.value` is `"3.1234"`, the following template will render as `3.1`:

[source]
----
{{#EvalMath}} round( {{{context.value}}} , 1) {{/EvalMath}}
----

[discrete]
[[parse-hjson-lambda]]
===== ParseHjson

The ParseHjson lambda provides ease-of-use capabilities when constructing JSON objects.
https://hjson.github.io/[Hjson] is a syntax extension to JSON. It has the following features:

- Missing and extra trailing commas are allowed in arrays and objects.
- Comments are supported.
- Property names can be specified without quotes.
- Property values can be specified without quotes (one per line and no commas).
- Multi-line strings have dedent support to remove the leading whitespace.
- Legal JSON documents are supported.

To use it, surround your Hjson content with `{{#ParseHjson}}...{{/ParseHjson}}`.
For example:

[source]
----
{{#ParseHjson}}
{
# add the rule id and name to the JSON document
ruleId: "{{rule.id}}"
ruleName: "{{rule.name}}"
}
{{/ParseHjson}}
----

When rendered, this template will generate:

[source,json]
----
{
"ruleId": "<the rule id is here>",
"ruleName": "<the rule name is here>"
}
----

[discrete]
===== FormatDate

The FormatDate lambda provides date formatting capabilities.
Dates can be formatted in an arbitrary time zone and with an arbitrary format string.

To use it, surround the date and formatting parameters with `{{#FormatDate}}...{{/FormatDate}}`.

The format of the text passed to the lambda is: `<date>; <time zone>; <date format>`, where semicolons (`;`) separate each parameter.
The `<date>` parameter is required; the `<time zone>` and `<date format>` parameters are optional.
The default time zone is `"UTC"` and the default date format is `"YYYY-MM-DD hh:mma"`.
For example, the following templates all render the same value:

[source]
----
{{#FormatDate}} {{{timestamp}}} {{/FormatDate}}
{{#FormatDate}} {{{timestamp}}} ; UTC {{/FormatDate}}
{{#FormatDate}} {{{timestamp}}} ; UTC; YYYY-MM-DD hh:mma {{/FormatDate}}
{{#FormatDate}} {{{timestamp}}} ; ; YYYY-MM-DD hh:mma {{/FormatDate}}
----

The `<time zone>` parameter must be a valid time zone identifier as listed in https://en.wikipedia.org/wiki/List_of_tz_database_time_zones[TZ database time zone names], such as `"America/New_York"`.

The `<date format>` parameter must be a valid date format string as described in the https://momentjs.com/docs/#/displaying/[Moment `format()` documentation].
For example, the date format `"YYYY-MM-DD hh:mma"` will render in the following format: `"2023-04-24 11:21pm"`.

The date value itself should usually be referenced with triple braces since some characters in date strings may contain values that are escaped, which would prevent them from being parsed as dates.

[discrete]
[[mustache-examples]]
=== Mustache examples

This example demonstrates a Mustache template for an email action sent from an {es} query rule.
The template references the following Mustache variables:

- `date`
- `context.title`
- `context.conditions`
- `context.link`
- `context.hits[]._source.event.provider`
- `context.hits[]._source.event.action`
- `context.hits[]._source.event.duration`

For example, if you have data like this available as Mustache variables:

[source,json]
----
{
"date": "2023-04-27T22:40:34.153Z",
"context": {
"title": "rule 'esq' matched query for group host-2",
"conditions": "Number of matching documents for group \"host-2\" is less than 1000",
"link": "https://example.com/this-will-link-to-Discover",
"hits": [
{
"_source": {
"event": {
"provider": "alerting",
"action": "active-instance",
"duration": "96023000000"
}
}
},
{
"_source": {
"@timestamp": "2023-04-27T22:40:22.251Z",
"event": {
"provider": "alerting",
"action": "execute-action"
}
}
}
]
}
}
----

You can create the following Mustache template in the email action for your rule:

[source,js]
----
# {{context.title}} <1>
{{#FormatDate}} {{{date}}} ; America/New_York {{/FormatDate}} <2>
{{context.conditions}}
**documents** _[view in Discover]({{{context.link}}})_ <3>
| provider | action | duration | <4>
| -------- | ------ | -------- |
{{#context.hits}}{{#_source.event}}| {{provider}} | {{action}} | {{#duration}}{{#EvalMath}} round( {{{duration}}} / 1000 / 1000 / 1000 ) {{/EvalMath}} sec{{/duration}} {{^duration}}-n/a-{{/duration}} |{{/_source.event}}
{{/context.hits}}
----
<1> Renders the value of the `context.title` variable as a level 1 heading.
<2> Renders the value of the `date` variable as a formatted date in the America/New_York time zone.
<3> Shows examples of `**bold**`, `_italic_`, and `[text](url)` links.
<4> Shows a table with three columns, with one row per element in the `context.hits` array.
From each of those elements, you can access the `provider`, `action`, and `duration` fields of the `_source.event` object.
The `duration` field is rendered as a number of seconds, rounded to the nearest second.
It's stored as nanoseconds so it needs to be divided by a billion to yield seconds.
The duration field is optional, so you can use a `{{#duration}} ... {{/duration}}` section to render the duration if it's present and show `-n/a-` otherwise.

When rendered into Markdown and then HTML and viewed in an email client, it looks like this:

[role="screenshot"]
image:images/email-mustache-template-rendered.png[Email template rendered in an email client]
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.

0 comments on commit b37d329

Please sign in to comment.