Skip to content

Commit

Permalink
feat(DMVP-1202): sns to servicenow (#5)
Browse files Browse the repository at this point in the history
* feat(DMVP-1202): sns to servicenow

* feat(DMVP-1202): sns to servicenow
  • Loading branch information
aghamyan44 authored Sep 19, 2022
1 parent 442f1e0 commit bef1ee6
Show file tree
Hide file tree
Showing 13 changed files with 358 additions and 0 deletions.
58 changes: 58 additions & 0 deletions modules/sns_to_lambda/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
# Create Lambda for trasfer alert data in to servicenow. SNS topic and lambda subscriptions. You can create alert and send data to created sns.

```
module "sns_to_servicenow" {
source = "dasmeta/monitoring/aws//modules/sns_to_servicenow"
name = "sns"
topic_name = "sns_to_servicenow"
lambda_envs = {
SERVICENOW_AUTH = ""
SERVICENOW_DOMAIN = ""
SERVICENOW_PATH = ""
}
}
```

<!-- BEGIN_TF_DOCS -->
## Requirements

| Name | Version |
|------|---------|
| <a name="requirement_terraform"></a> [terraform](#requirement\_terraform) | ~> 1.0 |
| <a name="requirement_aws"></a> [aws](#requirement\_aws) | ~> 4.16 |

## Providers

| Name | Version |
|------|---------|
| <a name="provider_aws"></a> [aws](#provider\_aws) | ~> 4.16 |

## Modules

| Name | Source | Version |
|------|--------|---------|
| <a name="module_sns_to_servicenow"></a> [sns\_to\_servicenow](#module\_sns\_to\_servicenow) | ./sns_to_servicenow | n/a |
| <a name="module_subscriptions"></a> [subscriptions](#module\_subscriptions) | dasmeta/sns/aws//modules//subscription | 1.2.3 |
| <a name="module_topic"></a> [topic](#module\_topic) | dasmeta/sns/aws//modules/topic | 1.2.3 |

## Resources

| Name | Type |
|------|------|
| [aws_cloudwatch_log_group.log](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/cloudwatch_log_group) | resource |

## Inputs

| Name | Description | Type | Default | Required |
|------|-------------|------|---------|:--------:|
| <a name="input_lambda_envs"></a> [lambda\_envs](#input\_lambda\_envs) | n/a | `any` | <pre>{<br> "SERVICENOW_AUTH": "",<br> "SERVICENOW_DOMAIN": "",<br> "SERVICENOW_PATH": ""<br>}</pre> | no |
| <a name="input_name"></a> [name](#input\_name) | n/a | `string` | `"test"` | no |
| <a name="input_topic_name"></a> [topic\_name](#input\_topic\_name) | n/a | `string` | `"test_topic"` | no |

## Outputs

| Name | Description |
|------|-------------|
| <a name="output_sns_topic_arn"></a> [sns\_topic\_arn](#output\_sns\_topic\_arn) | n/a |
<!-- END_TF_DOCS -->
13 changes: 13 additions & 0 deletions modules/sns_to_lambda/lambda.tf
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
resource "aws_cloudwatch_log_group" "log" {
name = "sns-${var.name}"
retention_in_days = 365
}

module "sns_to_servicenow" {
source = "./sns_to_servicenow"

name = var.name
create_alarm = false

envs = var.lambda_envs
}
7 changes: 7 additions & 0 deletions modules/sns_to_lambda/output.tf
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
output "sns_topic_arn" {
value = module.topic.topic_arn
}

output "lambda_function_arn" {
value = module.sns_to_servicenow.function_arn
}
19 changes: 19 additions & 0 deletions modules/sns_to_lambda/sns.tf
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
module "topic" {
source = "dasmeta/sns/aws//modules/topic"
version = "1.2.3"

topic_name = var.topic_name
}

module "subscriptions" {
source = "dasmeta/sns/aws//modules//subscription"
version = "1.2.3"

topic = var.topic_name
protocol = "lambda"
endpoint = module.sns_to_servicenow.function_arn

depends_on = [
module.topic
]
}
1 change: 1 addition & 0 deletions modules/sns_to_lambda/sns_to_servicenow/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
*.zip
21 changes: 21 additions & 0 deletions modules/sns_to_lambda/sns_to_servicenow/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2020 Claranet

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
46 changes: 46 additions & 0 deletions modules/sns_to_lambda/sns_to_servicenow/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
# cloudfront-to-s3-to-cloudwatch

<!-- BEGINNING OF PRE-COMMIT-TERRAFORM DOCS HOOK -->
## Requirements

No requirements.

## Providers

| Name | Version |
|------|---------|
| <a name="provider_aws"></a> [aws](#provider\_aws) | n/a |

## Modules

| Name | Source | Version |
|------|--------|---------|
| <a name="module_lambda"></a> [lambda](#module\_lambda) | raymondbutcher/lambda-builder/aws | 1.1.0 |

## Resources

| Name | Type |
|------|------|
| [aws_cloudwatch_metric_alarm.errors](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/cloudwatch_metric_alarm) | resource |
| [aws_caller_identity.current](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/caller_identity) | data source |
| [aws_iam_policy_document.lambda](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/iam_policy_document) | data source |
| [aws_region.current](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/region) | data source |

## Inputs

| Name | Description | Type | Default | Required |
|------|-------------|------|---------|:--------:|
| <a name="input_bucket_name"></a> [bucket\_name](#input\_bucket\_name) | n/a | `string` | n/a | yes |
| <a name="input_create_alarm"></a> [create\_alarm](#input\_create\_alarm) | n/a | `bool` | `false` | no |
| <a name="input_function_name"></a> [function\_name](#input\_function\_name) | n/a | `string` | `""` | no |
| <a name="input_log_group_name"></a> [log\_group\_name](#input\_log\_group\_name) | n/a | `string` | n/a | yes |
| <a name="input_memory_size"></a> [memory\_size](#input\_memory\_size) | Memory size for Lambda function | `number` | `null` | no |
| <a name="input_timeout"></a> [timeout](#input\_timeout) | Timeout for Lambda function | `number` | `null` | no |

## Outputs

| Name | Description |
|------|-------------|
| <a name="output_function_arn"></a> [function\_arn](#output\_function\_arn) | n/a |
| <a name="output_function_name"></a> [function\_name](#output\_function\_name) | n/a |
<!-- END OF PRE-COMMIT-TERRAFORM DOCS HOOK -->
43 changes: 43 additions & 0 deletions modules/sns_to_lambda/sns_to_servicenow/main.tf
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
module "lambda" {
source = "raymondbutcher/lambda-builder/aws"
version = "1.1.0"

function_name = coalesce(var.name, "${substr(var.name, 0, 45)}-to-servicenow")
handler = "lambda.lambda_handler"
runtime = "python3.8"
memory_size = var.memory_size
timeout = var.timeout

build_mode = "FILENAME"
source_dir = "${path.module}/src"
filename = "${path.module}/package.zip"

role_cloudwatch_logs = true

environment = {
variables = var.envs
}
}

resource "aws_cloudwatch_metric_alarm" "errors" {
count = var.create_alarm ? 1 : 0

alarm_name = "${module.lambda.function_name}-errors"
alarm_description = "${module.lambda.function_name} invocation errors"

namespace = "AWS/Lambda"
metric_name = "Errors"

dimensions = {
FunctionName = module.lambda.function_name
}

statistic = "Sum"
comparison_operator = "GreaterThanThreshold"
threshold = 0
period = 60 * 60
evaluation_periods = 1

# alarm_actions = var.alarm_actions
# ok_actions = var.ok_actions
}
7 changes: 7 additions & 0 deletions modules/sns_to_lambda/sns_to_servicenow/outputs.tf
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
output "function_arn" {
value = module.lambda.arn
}

output "function_name" {
value = module.lambda.function_name
}
75 changes: 75 additions & 0 deletions modules/sns_to_lambda/sns_to_servicenow/src/lambda.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import json
import http.client, urllib.parse
from os import environ

DEBUG = environ.get("DEBUG", 0)

def lambda_handler(event, context):
print ("> Alarm Name:", json.loads(event["Records"][0]["Sns"]["Message"])["AlarmName"])
print ("> Alarm Body:", json.dumps(json.loads(event["Records"][0]["Sns"]["Message"])))

json_body = json.loads(event["Records"][0]["Sns"]["Message"])
trigger_body = json_body["Trigger"]
print ("> Alarm Trigger Body Value",trigger_body)
dimension_string = ""
metric_name = ""
metric_namespace = ""

if "Metrics" in trigger_body:
metrics_body = trigger_body["Metrics"]

print ("> Alarm Metrics Body Value",metrics_body)
metric_stat = metrics_body[0]["MetricStat"]
metric = metric_stat["Metric"]
metric_name = metric["MetricName"]
metric_namespace = metric["Namespace"]

for dimension_object in metric["Dimensions"]:
dimension_string += dimension_object["name"] + "/" + dimension_object["value"] + "/"
else:
for dimension_object in trigger_body["Dimensions"]:
dimension_string += dimension_object["name"] + "/" + dimension_object["value"] + "/"

metric_name = trigger_body["MetricName"]
metric_namespace = trigger_body["Namespace"]

dictionary = {
"records":
[
{
"source":"CloudWatch Alerts",
"event_class":json_body["AlarmName"], # alarm name
"resource":dimension_string, # dimension
"node":json_body["AWSAccountId"],
"metric_name":metric_name,
"type":metric_namespace, # Namespace
"severity":"4",
"description":json_body["NewStateReason"],
"additional_info":json.dumps(trigger_body)
}
]
}

jsonString_dictionary = json.dumps(dictionary)

print("> Matched json format",jsonString_dictionary)


print(environ["SERVICENOW_DOMAIN"], environ["SERVICENOW_PATH"])

connection = http.client.HTTPSConnection(environ["SERVICENOW_DOMAIN"], 443)
connection.set_debuglevel(DEBUG)

headers = {
"content-type": "application/json",
"Authorization": environ["SERVICENOW_AUTH"]
}

# params have to be mapped to ServiceNow event structure
connection.request("POST", environ["SERVICENOW_PATH"], jsonString_dictionary, headers)

response = connection.getresponse()

print("> Response: ", response.status, response.reason)
print("> Response Body: ", json.dumps(response.read().decode('utf-8')))

40 changes: 40 additions & 0 deletions modules/sns_to_lambda/sns_to_servicenow/variables.tf
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
variable "function_name" {
type = string
default = ""
}

variable "name" {
type = string
}

variable "memory_size" {
description = "Memory size for Lambda function"
type = number
default = null
}

variable "timeout" {
description = "Timeout for Lambda function"
type = number
default = null
}

variable "create_alarm" {
type = bool
default = false
}

variable "envs" {
type = any
default = {}
}

# variable "alarm_actions" {
# type = list(string)
# default = []
# }

# variable "ok_actions" {
# type = list(string)
# default = []
# }
18 changes: 18 additions & 0 deletions modules/sns_to_lambda/variables.tf
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
variable "name" {
type = string
default = "test"
}

variable "topic_name" {
type = string
default = "test_topic"
}

variable "lambda_envs" {
type = any
default = {
SERVICENOW_AUTH = ""
SERVICENOW_DOMAIN = ""
SERVICENOW_PATH = ""
}
}
10 changes: 10 additions & 0 deletions modules/sns_to_lambda/versions.tf
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 4.16"
}
}

required_version = "~> 1.0"
}

0 comments on commit bef1ee6

Please sign in to comment.