Watcher创建场景下,如何阻止Webhook payload中部分Mustache标签被解析?
我搭建了一个主Watcher,它能根据索引记录创建或删除子Watcher。这些子Watcher会每周执行审计任务,给索引指定团队发送HTML格式邮件。
目前已经解决了Webhook payload长度问题,但碰到新问题:主Watcher执行搜索后,用Mustache把结果填充到创建子Watcher的payload里。但子Watcher自身需要执行搜索来填充邮件内容,它里面的Mustache标签会被主Watcher提前解析,无法保留到子Watcher执行时使用。
我需要让部分Mustache标签在主Watcher创建子Watcher时不被解析,保留原始形式供子Watcher使用。
示例代码:
主Watcher通过Webhook创建子Watcher:
"foreach": "ctx.payload.to_be_created", "max_iterations": 60, "webhook": { "scheme": "https", "host": "xxxxx", "port": xxxxx, "method": "put", "path": "_watcher/watch/{{ctx.payload._source.watchername}}", "params": {}, "headers": {}, "auth": { "basic": { "username": "xxxx", "password": "xxxx" } }, "body": """New Watchers to be created with mustach tag that needs to be interpreted, meaning value must be filled for the new watcher creation{{ctx.payload._source.watchername}} and mustach tag that should not be interpreted because they are part of the main code of the new watcher {{ctx.payload.bipbip.value}}""" }
期望创建后的子Watcher内容:
New Watchers to be created with mustach tag that needs to be interpreted, meaning value must be filled for the new watcher creation "this tag has been interpreted" and mustach tag that should not be interpreted because they are part of the main code of the new watcher {{ctx.payload.bipbip.value}}
方法一:转义Mustache标签
Elasticsearch Watcher的Mustache解析支持通过双重包裹来保留原始标签:把需要保留的{{...}}写成{{{{...}}}}。主Watcher解析时会自动将{{{{转换为{{,}}}}转换为}},这样子Watcher就能拿到原始的Mustache标签,不会被提前解析。
修改后的主Watcher Webhook body部分:
"body": """New Watchers to be created with mustach tag that needs to be interpreted, meaning value must be filled for the new watcher creation{{ctx.payload._source.watchername}} and mustach tag that should not be interpreted because they are part of the main code of the new watcher {{{{ctx.payload.bipbip.value}}}}"""
主Watcher执行后,子Watcher的body中就会保留{{ctx.payload.bipbip.value}},等子Watcher自己执行时再解析。
方法二:在Transform阶段处理字符串
如果需要更灵活的内容控制,可以在主Watcher的transform步骤中,用Painless脚本生成子Watcher的完整内容,把需要保留的Mustache标签作为普通字符串处理,避免被主Watcher解析。
示例配置:
"transform": { "script": { "source": """ // 生成子Watcher的body内容,把需要保留的标签直接写死为字符串 ctx.payload.child_body = 'New Watchers to be created with mustach tag that needs to be interpreted, meaning value must be filled for the new watcher creation' + ctx.payload._source.watchername + ' and mustach tag that should not be interpreted because they are part of the main code of the new watcher {{ctx.payload.bipbip.value}}'; """ } }, "actions": { "create_sub_watch": { "foreach": "ctx.payload.to_be_created", "max_iterations": 60, "webhook": { "scheme": "https", "host": "xxxxx", "port": xxxxx, "method": "put", "path": "_watcher/watch/{{ctx.payload._source.watchername}}", "params": {}, "headers": {}, "auth": { "basic": { "username": "xxxx", "password": "xxxx" } }, "body": "{{ctx.payload.child_body}}" } } }
脚本中用单引号包裹字符串,主Watcher的Mustache解析器不会处理字符串内部的{{...}},会直接把完整内容传递给子Watcher。
内容的提问来源于stack exchange,提问作者JohnJM35

