오픈소스
[Terrafrom] 구글 클라우드 모니터링 알람 리소스 생성 (1)
케이군
2023. 5. 26. 11:08
개요
구글 클라우드 Logging를 기반으로 메트릭을 생성하여 알람을 생성하려고 합니다.
예) Audit 로그를 활용하여 IAM 권한이 변경된 경우
목표
- 테라폼을 사용해서 구글 클라우드 모니터링 메트릭과 알람을 생성
- 이메일, Slack, Webhook으로 알람 수신
테라폼 리소스
- 알람 채널 생성 : google_monitoring_notification_channel
- Alert 정책 생성 : google_monitoring_alert_policy
- Log based metric 생성 : google_logging_metric
Slack 사용을 위한 사전 작업
Slack을 사용하기 위해서는 먼저 앱을 만들어야 합니다.
- Create New App 클릭
From scratch 선택

- 앱 이름과 워크스페이스를 선택 후 Create App 클릭

- OAuth & Permissions 메뉴에서 권한 추가
chat:으로 검색해서 3가지 권한을 추가해주면 됩니다.


앱을 설치하게 되면 인증키가 나옵니다.

알람 채널 생성 테라폼 코드 작업
variables.tf
variable "notification_channels" {
type = map(object({
type = string
workspace = string
endpoint = string
auth_token = string
}))
}
main.tf
resource "google_monitoring_notification_channel" "default" {
depends_on = []
for_each = var.notification_channels
display_name = each.key
type = each.value.type
labels = {
email_address = each.value.type == "email" ? each.value.endpoint : null
url = each.value.type == "webhook_tokenauth" ? each.value.endpoint : null
channel_name = each.value.type == "slack" ? each.value.endpoint : null
team = each.value.type == "slack" ? each.value.workspace : null
}
dynamic "sensitive_labels" {
for_each = each.value.type == "slack" && can(regex("^.*[^ ].*$", each.value.auth_token)) ? [each.value.auth_token] : []
content {
auth_token = each.value.auth_token
}
}
}
logging.tf
module "logging" {
source = "./modules/logging"
notification_channels = {
naverworks = { # #Webhook
type = "webhook_tokenauth"
workspace = "null"
endpoint = "https://www.abc.co.kr/webhook"
auth_token = "null"
}
email-minsukim = { # Email
type = "email"
workspace = "null"
endpoint = "abc@email.com"
auth_token = "null"
}
slack-test = { # Slack
type = "slack"
workspace = "workspace"
endpoint = "#alert"
auth_token = "xoxb-1234-1234"
}
}
}