Matching on JSON with jmespath
Using JMESPath Queries Inside
match_onandmatch_with
When a resource property contains complex structured data (a JSON object or array), the standard value,
contains, and regexp operators may not be expressive enough. In these cases you can use the expression
operator combined with the jmespath filter for precise, targeted
matching against nested data.
How It Works
A jmespath query inside an expression renders to an empty string when no match is found and to a non-empty
value when a match is found. The {% if ... %} block converts this to the exact string "true" that the
expression operator requires.
The condition is considered true when the JMESPath query returns a truthy result — anything other than null,
false, an empty string, an empty array, or an empty object.
Example: Matching Nested Tags
Goal: Apply a backup policy only to databases that carry a tag with key = "env" and value = "prod" stored
in a nested JSON structure.
database_details = {
"db-prod-01" = { tags = [{ key = "env", value = "prod" }] },
"db-dev-01" = { tags = [{ key = "env", value = "dev" }] }
}
[[create_resource]]
match_on = [
{
expression = """
{%- set tags = database_details[origin_resource.name].tags
| jmespath(query="[?key == 'env' && value == 'prod']") -%}
{% if tags %}true{% endif %}
"""
}
]
resource_type = "backup_policy"
name = "backup_policy_for_{{ origin_resource.name }}"
Example: Matching Against a Property on the Resource
If the JSON data lives directly on the resource as a property (rather than in a header variable), the same
pattern applies — just reference origin_resource.<property> in the jmespath filter call.
[[create_resource]]
match_on = [
{
expression = """
{%- set match = origin_resource.config
| jmespath(query="storage[?class == 'premium-ssd']") -%}
{% if match %}true{% endif %}
"""
}
]
resource_type = "premium_storage_policy"
name = "psp_for_{{ origin_resource.name }}"
For the full match_on and match_with operator reference, see OR Logic and DNF and
match_on and match_with Operators.