Commit 40d906fe authored by nimrod's avatar nimrod
Browse files

SMS: Remove Message Bird SMS sending.

In favor of AWS SNS.
parent 4d869765
Loading
Loading
Loading
Loading
Loading
+0 −1
Original line number Diff line number Diff line
dnspython
messagebird
requests

sms-notify.tf

deleted100644 → 0
+0 −200
Original line number Diff line number Diff line
# vi: ft=tf

variable "messagebird_access_key" {
  description = "MessageBird API access key."
  sensitive   = true
}

variable "send_sms_notifications" {
  default     = true
  description = "Whether or not to send SMS notifications."
  type        = bool
}

output "send_sms_notifications" {
  description = "Whether or not to send SMS notifications."
  value       = var.send_sms_notifications
}

resource "aws_ssm_parameter" "send_sms_notifications" {
  name  = "/${local.module}/${local.env}/send_sms_notifications"
  type  = "String"
  value = tostring(var.send_sms_notifications)
}

resource "aws_lambda_function" "sms_notify" {
  runtime                        = var.runtime
  function_name                  = "${local.function_name_prefix}-sms-notify"
  role                           = aws_iam_role.sms_notify.arn
  source_code_hash               = filebase64sha256("payload.zip")
  s3_bucket                      = local.payloads_bucket_name
  s3_key                         = local.payload_object_name
  s3_object_version              = local.payload_object_version
  package_type                   = "Zip"
  handler                        = "sms_notify.handler"
  description                    = "Send SMS message notification using MessageBird."
  memory_size                    = var.memory_size
  reserved_concurrent_executions = -1
  timeout                        = var.timeout

  environment {
    variables = {
      ENV                          = local.env
      MODULE                       = local.module
      TOPIC_ARN                    = local.topic_arn
      VERSION                      = local.payload_object_version
      MSGBIRD_ACCESS_KEY           = var.messagebird_access_key
      TO_NUMBER                    = local.my_phone_number
      SEND_SMS_NOTIFICATIONS_PARAM = aws_ssm_parameter.send_sms_notifications.name
    }
  }

  # Create the log group with retention before the function is created.
  # Otherwise it's created without retention and need to be imported.
  depends_on = [
    aws_cloudwatch_log_group.sms_notify,
  ]
}

locals {
  sms_notify_function_arn     = aws_lambda_function.sms_notify.arn
  sms_notify_function_name    = aws_lambda_function.sms_notify.function_name
  sms_notify_function_version = aws_lambda_function.sms_notify.version
}

output "sms_notify_function_arn" {
  description = "ARN of the SMS notification Lambda function."
  value       = local.sms_notify_function_arn
}

output "sms_notify_function_name" {
  description = "Name of the SMS notification Lambda function."
  value       = local.sms_notify_function_name
}

output "sms_notify_function_version" {
  description = "Version of the SMS notification Lambda function."
  value       = local.sms_notify_function_version
}

resource "aws_lambda_alias" "sms_notify" {
  name             = "${local.function_name_prefix}_${local.sms_notify_function_name}"
  function_name    = local.sms_notify_function_arn
  function_version = local.sms_notify_function_version
}

locals {
  sms_notify_function_alias_arn  = aws_lambda_alias.sms_notify.arn
  sms_notify_function_alias_name = aws_lambda_alias.sms_notify.name
}

output "sms_notify_function_alias_arn" {
  description = "ARN of the SMS notification Lambda function alias."
  value       = local.sms_notify_function_alias_arn
}

output "sms_notify_function_alias_name" {
  description = "Name of the SMS notification Lambda function alias."
  value       = local.sms_notify_function_alias_name
}

resource "aws_lambda_permission" "sms_notify" {
  statement_id  = "AllowExecutionFromSNS"
  action        = "lambda:InvokeFunction"
  principal     = "sns.amazonaws.com"
  source_arn    = local.topic_arn
  function_name = local.sms_notify_function_name
}

resource "aws_sns_topic_subscription" "sms_notify" {
  endpoint  = local.sms_notify_function_arn
  protocol  = "lambda"
  topic_arn = local.topic_arn
  depends_on = [
    aws_lambda_permission.sms_notify,
  ]
}
resource "aws_cloudwatch_log_group" "sms_notify" {
  name              = "/aws/lambda/${local.function_name_prefix}-sms-notify"
  retention_in_days = var.log_retention
}

locals {
  sms_notify_log_group_arn  = aws_cloudwatch_log_group.sms_notify.arn
  sms_notify_log_group_name = aws_cloudwatch_log_group.sms_notify.name
}

output "sms_notify_log_group_arn" {
  description = "ARN of the CloudWatch log groups for the SMS notify Lambda function invocations."
  value       = local.sms_notify_log_group_arn
}

output "sms_notify_log_group_name" {
  description = "Name of the CloudWatch log groups for the SMS notify Lambda function invocations."
  value       = local.sms_notify_log_group_name
}

data "aws_iam_policy_document" "sms_notify" {
  statement {
    effect = "Allow"

    actions = [
      "logs:CreateLogStream",
      "logs:PutLogEvents",
    ]

    resources = [local.sms_notify_log_group_arn, ]
  }

  statement {
    effect = "Allow"

    actions = [
      "ssm:GetParametersByPath",
    ]

    resources = [aws_ssm_parameter.send_sms_notifications.arn]
  }
}

locals {
  sms_notify_log_policy_doc = data.aws_iam_policy_document.sms_notify.json
}

resource "aws_iam_policy" "sms_notify" {
  name   = "${local.module}-${local.env}-sms-notify"
  policy = local.sms_notify_log_policy_doc
}

locals {
  sms_notify_policy_arn  = aws_iam_policy.log.arn
  sms_notify_policy_name = aws_iam_policy.log.name
}

output "sms_notify_policy_arn" {
  value       = local.sms_notify_policy_arn
  description = "AM policy for SMS notifications ARN."
}

output "sms_notify_policy_name" {
  value       = local.sms_notify_policy_name
  description = "IAM policy for SMS notifications name."
}

resource "aws_iam_role" "sms_notify" {
  name               = "${local.name}-sms-notify"
  assume_role_policy = local.lambda_assume_policy_doc
}

locals {
  sms_notify_policies = [
    local.sms_notify_policy_arn,
    "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole",
  ]
}

resource "aws_iam_role_policy_attachment" "sms_notify" {
  count      = length(local.sms_notify_policies)
  role       = aws_iam_role.sms_notify.name
  policy_arn = local.sms_notify_policies[count.index]
}

src/sms_notify.py

deleted100644 → 0
+0 −37
Original line number Diff line number Diff line
import os
import boto3  # pylint: disable=import-error
import messagebird  # pylint: disable=import-error

MSGBIRD_ACCESS_KEY = os.environ["MSGBIRD_ACCESS_KEY"]
TO_NUMBER = os.environ["TO_NUMBER"]


def send_notifications():
    """Check if sending SMSes is enabled."""
    try:
        param_path = os.environ["SEND_SMS_NOTIFICATIONS_PARAM"]
        client = boto3.client("ssm")
        param = client.get_parameters_by_path(
            Path=param_path, recursive=False, WithDecryption=False
        )["Parameters"][0]
        return param["Value"].tolower == "true"
    except Exception:  # pylint: disable=broad-except
        return True


# pylint: disable=unused-argument
def handler(event, context):
    if not send_notifications():
        print("Sending notification is disabled.")
        return
    message = event["Records"][0]["Sns"]["Message"]
    client = messagebird.Client(MSGBIRD_ACCESS_KEY)
    client.message_create(
        originator="Am I Live",
        recipients=TO_NUMBER,
        body=message,
    )


if __name__ == "__main__":
    handler({"Records": [{"Sns": {"Message": "foo"}}]}, "context")