# Watcherのwebhookのbodyの設定方法について

**URL:** <https://discuss.elastic.co/t/watcher-webhook-body/211064>\
**Category:** 日本語による質問・議論はこちら\
**Created:** [December 9, 2019, 7:40am UTC](https://discuss.elastic.co/t/watcher-webhook-body/211064 "2019-12-09T07:40:31Z")\
**Posts on this page:** 7\
**Page:** 1

<div class="post-metadata">

**Author:** ![harue](https://avatars.discourse-cdn.com/v4/letter/h/82dd89/32.png) [@harue](https://discuss.elastic.co/u/harue)\
**Post date:** [December 9, 2019, 7:40am UTC](https://discuss.elastic.co/t/watcher-webhook-body/211064/1 "2019-12-09T07:40:31Z")

</div>

お世話になっております。  
Watcherについて、質問させて頂きます。

ご質問  
①bodyの項目名(下記例だと"resion")について、以下エラーが発生します。  
[x\_content\_parse\_exception] [1:587] [script] unknown field [resion], parser not found

項目名は自由に指定できる認識ですが、違うのでしょうか。  
エラーの解決策についてご教示をお願いします。

②bodyの値について、input句で取得したフィールドの値を設定したいです。  
設定方法は下記で合っていますでしょうか。

お手数ですが、回答頂けますと幸いです。

例

```
{
  "trigger": {
    "schedule": {
      "interval": "1m"
    }
  },
  "input": {
    "search": {
      "request": {
        "search_type": "query_then_fetch",
        "indices": [
          "heartbeat*"
        ],
        "rest_total_hits_as_int": true,
        "body": {
          "query": {
            "match": {
              "monitor.status": "down"
            }
          }
        }
      }
    }
  },
  "condition": {
    "compare": {
      "ctx.payload.hits.total": {
        "gt": 0
      }
    }
  },
  "actions": {
    "test": {
      "webhook": {
        "scheme": "https",
        "host": "https://XXXXXXX",
        "port": XXXX,
        "method": "post",
        "params": {},
        "headers":{},
        "body": {
                 "resion": "{{ctx.metadata.cloud.region}} ",
                 "instanceid": "{{ctx.metadata.instance.id}} " 
     }
     }
    }
  }
}
```

---

<div class="post-metadata">

**Author:** ![tsgkdt](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/tsgkdt/32/39151_2.png) [@tsgkdt](https://discuss.elastic.co/u/tsgkdt)\
**Post date:** [December 9, 2019, 1:07pm UTC](https://discuss.elastic.co/t/watcher-webhook-body/211064/2 "2019-12-09T13:07:34Z")

</div>

①の部分について書きます。

[https://www.elastic.co/guide/en/elasticsearch/reference/current/actions-webhook.html#configuring-webook-actions](https://www.elastic.co/guide/en/elasticsearch/reference/current/actions-webhook.html#configuring-webook-actions)

上の「Configuring webhook actions」に記載のある例を見ますと、bodyはオブジェクトではなく文字列を指定するようになっているようです。

つまり、"body": "{ \"resion\": \"何か\"}" のように書かれるのではと思います。

Microsoft TeamsのWebhookを呼び出すことでテストしましたが、以下のように書いて正常終了し、期待したメッセージが投下されました。

```auto
"actions": {
    "my-logging-action": {
      "logging": {
        "text": "There are {{ctx.payload.hits.total}} documents in your index. Threshold is 10."
      }
    },
    "test-hook": {
        "webhook": {
            "url": "https://outlook.office.com/webhook/hihimitsu/IncomingWebhook/himitsunomojiretsu",
            "method": "post",
            "params": {},
            "headers":{},
            "body": """
            {
              "text": "あいうえおmg"
            }
            """
        }
    }
  }

```

bodyのところの設定方法を上記のように文字列で指定してみてはどうでしょうか？

---

<div class="post-metadata">

**Author:** ![tsgkdt](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/tsgkdt/32/39151_2.png) [@tsgkdt](https://discuss.elastic.co/u/tsgkdt)\
**Post date:** [December 10, 2019, 1:44am UTC](https://discuss.elastic.co/t/watcher-webhook-body/211064/3 "2019-12-10T01:44:49Z")

</div>

②の書き方ですが、取得した結果を含めることは可能ですが、取得した結果ごとにアクションを実行したいのか、１回のWatcherアクションを実行したいのかによっても書き方は変わるかと思います。

１つずつ通知すると、何度もWebhookを実行することとなり避けたいかな？と考えたので、今回は後者の例の書き方を示します。  
通知された後のイメージは以下のようになります。

 ![image](https://us1.discourse-cdn.com/elastic/original/3X/f/0/f0ab062335b7f4ad506b4e695f6d521a278f1d0a.png)

## テストデータ

3件分のテストデータを作成しました。

```auto
POST forum1210/_doc/1
{
  "cloud": {
    "region": "ap-northeast-1",
    "instanceid": "instance-11111111"
  }
}
POST forum1210/_doc/2
{
  "cloud": {
    "region": "ap-northeast-1",
    "instanceid": "instance-22222222"
  }
}
POST forum1210/_doc/3
{
  "cloud": {
    "region": "us-west-2",
    "instanceid": "instance-33333333"
  }
}

```

## Watcherの設定

ポイントは、bodyのsizeを0にしないこと。0にしていると、取得した中身が取れないので。  
mustacheテンプレートの記法を使う `{{#ctx.payload.hits.hits}}`と`{{/ctx.payload.hits.hits}}`の部分です。

検索クエリ部分などは本来何らかの条件を入れるべきですが、今回は１つの通知アクションで複数の検索結果の中身を含めるというサンプルにつき、match\_allで省略します。

```auto
PUT _watcher/watch/forum1210
{
  "trigger": {
    "schedule": {
      "interval": "30m"
    }
  },
  "input": {
    "search": {
      "request": {
        "body": {
          "size": 10,
          "query": {
            "match_all": {}
          }
        },
        "indices": [
          "forum1210"
        ]
      }
    }
  },
  "condition": {
    "compare": {
      "ctx.payload.hits.total": {
        "gt": 0
      }
    }
  },
  "actions": {
    "test-hook": {
      "webhook": {
            "url": "https://outlook.office.com/webhook/himitsu/IncomingWebhook/himitsunomoji,
            "method": "post",
            "params": {},
            "headers":{},
            "body": """
            {
              "text": "{{ctx.payload.hits.total}} Errors have occured in the logs: <br>
                {{#ctx.payload.hits.hits}}
                  {{_source.cloud.region}}: {{_source.cloud.instanceid}} <br>
                {{/ctx.payload.hits.hits}}"
            }
            """
        }
    }
  }
}

```

ご参考になれば幸いです。

---

<div class="post-metadata">

**Author:** ![harue](https://avatars.discourse-cdn.com/v4/letter/h/82dd89/32.png) [@harue](https://discuss.elastic.co/u/harue)\
**Post date:** [December 10, 2019, 4:04am UTC](https://discuss.elastic.co/t/watcher-webhook-body/211064/4 "2019-12-10T04:04:52Z")

</div>

早急に回答頂きありがとうございます。  
大変助かります。

下記body句の記載ですが、Watcherにコピーしたところ  
エラー「Expected ' , ' instead of ' " '」が起こり保存できません。

お手数ですが、こちらのエラーの解決策も教えて頂けますと幸いです。

```
        "body": """
        {
          "text": "あいうえおmg"
        }
        """
```

---

<div class="post-metadata">

**Author:** ![tsgkdt](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/tsgkdt/32/39151_2.png) [@tsgkdt](https://discuss.elastic.co/u/tsgkdt)\
**Post date:** [December 10, 2019, 4:18am UTC](https://discuss.elastic.co/t/watcher-webhook-body/211064/5 "2019-12-10T04:18:18Z")

</div>

KibanaのManagement/Watcherの管理画面より、条件を入力されてますでしょうか？

 ![image](https://us1.discourse-cdn.com/elastic/original/3X/9/e/9ee2ce58b3cb8e46d4e7aa948a0d26cbb531e67f.png)

このエディタでは、 ””” を使って改行を入れた書き方がサポートされていませんので、１行で書く必要があります。

そこで、このように書いてみてください。

```auto
        ～中略～
        "params": {},
        "headers": {},
        "body": "{\"text\": \"あいうえお\"}"

```

 ![image](https://us1.discourse-cdn.com/elastic/original/3X/1/8/1858c8a926aca7b045d3e2076192eab828ebd192.png)

DevToolsからWatcherを作成する場合には、先に示しました”””を使った書き方でもエラーになりません。

現象としては、以下の投稿と同一の現象かと思われます。

> [@Watcherのscriptにおける記述作法](https://discuss.elastic.co/t/watcher-script/207610):
>
> お世話になります。 基礎的な質問で大変恐縮なのですが、 Watcher の advanced watch に設定するconditionで、scriptを記述したいのですが、 下記URLのような書き方（scriptのプログラムを「"""」で囲む）をすると、エラーが発生します。 エラーメッセージ [Watch%20JSON%20error] Watch JSON（抜粋） "condition": { "script": { "source": """ ctx.payload.hits.hits[0] = ctx.payload.hits.hits[0].\_source; int i = ctx.payload.hits.hits[0]['value0']; return i \> 0 """ , "lang": "painless" } }, 補足 scriptのプログラムを 「"""」で囲って複数行 → 「"」で囲って1行にまとめる と変更すると、問題なく動作します…

---

<div class="post-metadata">

**Author:** ![harue](https://avatars.discourse-cdn.com/v4/letter/h/82dd89/32.png) [@harue](https://discuss.elastic.co/u/harue)\
**Post date:** [December 12, 2019, 2:16am UTC](https://discuss.elastic.co/t/watcher-webhook-body/211064/6 "2019-12-12T02:16:30Z")

</div>

返信が遅くなり申し訳ありません。

①bodyの項目名のエラー  
②bodyの値について、input句で取得したフィールドの値の設定

下記記載で解決しました。

`"body": "{\"resion\": \"{{#ctx.payload.hits.hits}} {{_source.cloud.region}} {{/ctx.payload.hits.hits}}\",\"instanceid\": \"{{#ctx.payload.hits.hits}} {{_source.cloud.instance.id}} {{/ctx.payload.hits.hits}}\"}"`

早急に回答頂きありがとうございました。  
大変助かりました。

---

<div class="post-metadata">

**Author:** ![system](https://us1.discourse-cdn.com/elastic/original/3X/1/a/1ac57faf039f6b580b3f104ef42a2a89e41014de.png) [@system](https://discuss.elastic.co/u/system)\
**Post date:** [January 9, 2020, 2:16am UTC](https://discuss.elastic.co/t/watcher-webhook-body/211064/7 "2020-01-09T02:16:33Z")

</div>

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.
