---
# System prepended metadata

title: Service Alarm Flow
tags: [Ubiquiti]

---

###### tags: `Ubiquiti`

# Service Alarm Flow




`service/alarms` 的目錄結構
```
.
├── cloudevents.tf
├── cloudwatch-dashboard.tf
├── cloudwatch.tf
├── main.tf
└── variables.tf
```

## Terraform 建立了哪些資源

以 `proto-door-access-critical-error` 為例

```mermaid
flowchart LR
    CloudWatch-->a[EventBridge rule]--notify-->SNS--trigger-->Lambda--notify-->Slack
```

---

CloudWatch: `proto-door-access-critical-error`
EventBridge rule: `door-access-error-code20210528034950291300000001`
SNS: `slack-proto-shared20200116083213518200000002`
Lambda: `slack-proto-shared`

---

主要有四種類型的資源:

* aws_cloudwatch_event_rule
* aws_cloudwatch_event_target
* aws_cloudwatch_metric_alarm
* aws_cloudwatch_log_metric_filter


## Post Slack Message 需要什麼參數 


```mermaid
flowchart LR
    a[SNS event]--EventDef class-->b[EventDef]--processEvent and Slack.postMessage-->c[Slack Message]
```


以 `SNS` 傳來的event會包裝成這個樣子:

```json
{
  "Records": [
    {
      "EventVersion": "1.0",
      "EventSubscriptionArn": "arn:aws:sns:us-east-2:123456789012:sns-lambda:21be56ed-a058-49f5-8c98-aedd2564c486",
      "EventSource": "aws:sns",
      "Sns": {
        "SignatureVersion": "1",
        "Timestamp": "2019-01-02T12:45:07.000Z",
        "Signature": "tcc6faL2yUC6dgZdmrwh1Y4cGa/ebXEkAi6RibDsvpi+tE/1+82j...65r==",
        "SigningCertUrl": "https://sns.us-east-2.amazonaws.com/SimpleNotificationService-ac565b8b1a6c5d002d285f9598aa1d9b.pem",
        "MessageId": "95df01b4-ee98-5cb9-9903-4c221d41eb5e",
        "Message": "Hello from SNS!",
        "MessageAttributes": {
          "Test": {
            "Type": "String",
            "Value": "TestString"
          },
          "TestBinary": {
            "Type": "Binary",
            "Value": "TestBinary"
          }
        },
        "Type": "Notification",
        "UnsubscribeUrl": "https://sns.us-east-2.amazonaws.com/?Action=Unsubscribe&amp;SubscriptionArn=arn:aws:sns:us-east-2:123456789012:test-lambda:21be56ed-a058-49f5-8c98-aedd2564c486",
        "TopicArn":"arn:aws:sns:us-east-2:123456789012:sns-lambda",
        "Subject": "TestInvoke"
      }
    }
  ]
}
```
---



1. 因為event可能有不同的來源格式，先統一包裝成 `EventDef`
2. `processEvent` 根據不同的來源以 `parser` 把 `EventDef` 處理成  <br/>`{ parser, parserName, slackMessage: message }` 的形式， <br/>其中 message 的格式為 `{text: ...}`
3. 呼叫 `Slack.postMessage` 傳入要送的 `slackMessage`
4. `postMessage` 會需要 `hookUrl` 和 `slackChannel` 的資訊，由環境變數提供<br/> ![](https://i.imgur.com/rbP7P9j.png)
5. `shouldDecryptBlob`: 用以向KMS取得 `hookUrlPromise` 及 `slackChannelPromise`

---

Slack message需要的params為:

* webhook url
* slack channel
* message

---

Slack Incoming Webhooks

```json
POST https://hooks.slack.com/services/T00000000/B00000000/XXXXXXXXXXXXXXXXXXXXXXXX
Content-type: application/json
{
    "text": "Hello, world."
}
```