ELK Lesson 29:使用Logstash發送告警E-Mail
Logstash的多種用途
在之前的文章,使用Logstash作為接收Metricbeat與Filebeat的工具,怎麼又可以用來發送告警資訊呢?這就要說到Logstash的一個簡單又聰明的設計:input與output!
Input,用來接收或擷取資料的,若資料來源不實各種的beat,而是檔案、資料庫、網頁…等,就可以使用Logstash的各種input模組,清單如官網。
Output,用來輸出資料,輸出目標可以是Elasticsearch、檔案、呼叫API…等,連接SMTP Server發送E-Mail當然也是重要的支援項目囉,清單如官網。
KQL語法
KQL,全名是Kibana Query Language,是Kibana提供給使用者用來搜尋資料用的語法,類似SQL,也可以對資料做運算或加工之用,教學請看官網。
新增一個Logstash的設定檔
步驟1:建立一個用於定義輸入、輸出的設定檔,檔名為send-alert.conf。
$ sudo cp /etc/logstash/logstash-sample.conf /etc/logstash/conf.d/send-alert.conf
步驟2:將Elasticsearch的憑證放入Logstash資料夾下的certs目錄。(若無該目錄,可自行建立)
步驟3:設定輸入的模組為Elasticsearch,並放入包括排程時間、KQL語法、Elasticsearch驗證參數等,官方說明。
$ sudo vi /etc/logstash/conf.d/send-alert.conf
input {
elasticsearch {
hosts => "lab-elk.example.com"
ca_file => "/etc/logstash/certs/ca.crt"
user => "changeme"
password => "changeme"
index => "alert-*"
schedule => "0 0/1 0 ? * * *" # 設定從0分開始每1分鐘執行一次排程。
query => 'context.timestamp > now-1m'
}
}
步驟4:設定使用Email的output模組,來發送E-Mail,官方說明。
output {
email {
to => '[email protected]'
from => '[email protected]'
subject => 'Alert-%{alert_name}-%{_id}'
body => "Alert Name: %{alert_name}\\nAlert ID: %{_id}\\nTime: %{context.timestamp}\\nHost: %{alert_instance_id}\\nMessage: %{context_message}"
address => "mailserver.example.com"
port => 25
domain => "example.com"
}
}
E-Mail的格式如下:
Alert Name: CPU Usage Over 90%
Alert ID: RJ2R8HwBA6pCdlF35C2W
Time: Nov 5, 2021 @ 22:47:42.612
Host: lab-elk.example.com
Message: CPU usage 96%, over 90% more than 1 minute.
步驟5:重新啟動Logstash後,新的設定檔案就會生效囉!
~ END ~