Introduction to SNS with CFN – email version

Introduction to SNS with CFN - email version

Introduction to SNS with CFN – email version

AWS SNS is a messaging service.

In this introductory article, we will show you how to specify Email as the notification destination.

Environment

Diagram of introduction to SNS with CFN.

We will create two types of resources.

The first is an SNS topic.
Specify an email address as a subscriber.

The second is a Lambda function.
It acts as a publisher that sends messages to the SNS topic.
The runtime environment for the function is Python 3.8.

CloudFormation template files

The above configuration is built using CloudFormation.
The CloudFormation templates are located at the following URL

https://github.com/awstut-an-r/awstut-fa/tree/main/067

Explanation of key points of the template files

SNS Topic

Resources:
  Topic:
    Type: AWS::SNS::Topic
    Properties:
      Subscription:
        - Endpoint: !Ref MailAddress
          Protocol: email
      TopicName: !Ref Prefix
Code language: YAML (yaml)

The Subscription property is the key.
To send a message to an email address, set the two properties inside.
Specify “email” for the Protocol property.
Specify the email address in the Endpoint property.

Lambda Function

Resources:
  Function:
    Type: AWS::Lambda::Function
    Properties:
      Architectures:
        - !Ref Architecture
      Environment:
        Variables:
          REGION: !Ref AWS::Region
          TOPIC: !Ref TopicArn
      Code:
        ZipFile: |
          import boto3
          import json
          import os

          topic = os.environ['TOPIC']
          region = os.environ['REGION']

          client = boto3.client('sns', region_name=region)

          def lambda_handler(event, context):
            response = client.publish(
              TopicArn=topic,
              Subject='hogehoge',
              Message='fugafuga'
              )

            return {
              'statusCode': 200,
              'body': json.dumps(response, indent=2)
            }
      FunctionName: !Sub "${Prefix}-function"
      Handler: !Ref Handler
      Runtime: !Ref Runtime
      Role: !GetAtt FunctionRole.Arn
Code language: YAML (yaml)

The Environment property allows you to define environment variables that can be passed to the function.
The ARN of the SNS topic mentioned above and the region where the topic was created can be passed.

Define the code to be executed by the Lambda function in inline notation.
For more information, please refer to the following page

あわせて読みたい
3 parterns to create Lambda with CloudFormation (S3/Inline/Container) 【Creating Lambda with CloudFormation】 When creating a Lambda with CloudFormation, there are three main patterns as follows. Uploading the code to an S3 buc...

The code to be executed is as follows

  1. get the environment variables defined in the CloudFormation template by accessing os.environ.
  2. create an SNS client object in Boto3.
  3. publish a message to the SNS topic using the client object.
  4. Return the result of the above with a return statement.

Note that to publish a message, it is necessary to specify the title and body of the message.
In this case, we specify the test strings “hogehoge” and “fugafuga” for verification.

Incidentally, the IAM role for the function is as follows

Resources:
  FunctionRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: 2012-10-17
        Statement:
          - Effect: Allow
            Action: sts:AssumeRole
            Principal:
              Service:
                - lambda.amazonaws.com
      ManagedPolicyArns:
        - arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
      Policies:
        - PolicyName: SNSPublishPolicy
          PolicyDocument:
            Version: 2012-10-17
            Statement:
              - Effect: Allow
                Action:
                  - sns:Publish
                Resource:
                  - !Ref TopicArn
Code language: YAML (yaml)

First, specify the AWS administrative policy AWSLambdaBasicExecutionRole and grant the necessary permissions to execute the function.
In addition, grant permission to publish messages to SNS topics.

Architecting

Using CloudFormation, build this environment and check the actual behavior.

Create CloudFormation stacks and check resources in stacks

Create a CloudFormation stack.
For information on how to create stacks and check each stack, please refer to the following page

あわせて読みたい
CloudFormation’s nested stack 【How to build an environment with a nested CloudFormation stack】 Examine nested stacks in CloudFormation. CloudFormation allows you to nest stacks. Nested ...

After checking the resources in each stack, information on the main resources created this time is as follows

  • SNS topic: fa-067
  • Function URL for Lambda function: https://sh53ix7pkfnajqekan4qgeol3a0fuhwg.lambda-url.ap-northeast-1.on.aws/

Authentication of Email Address

If an e-mail address is specified as a subscriber to an SNS topic, the e-mail address must be authenticated.
The following authentication email will be sent to the specified email address.

Authentication to use email address for SNS subscriber 1.

Click “Confirm subscription” to proceed with the authentication.

Authentication to use email address for SNS subscriber 2.

The above page will appear, indicating that the authentication has been completed.

Resource Confirmation

Check each resource from the AWS Management Console.
First, check the SNS topic.

Detail of SNS.

You can see that the SNS topic has been successfully created.

In addition, you can see that the email address registered as a subscriber has been registered.
The Status value of the email address is “Confirmed,” indicating that the authentication has been completed.

Checking Action

Now that everything is ready, let’s check the Operation.

Checking Action is done by accessing the Function URL of the Lambda function.

For details on the Function URL, please refer to the following page.

あわせて読みたい
Lambda Function URL by CFN – Auth Type: NONE 【Creating Lambda Function URL by CloudFormation (NONE version)】 Lambda Function URL was released on April 22, 2022. AWS Lambda is announcing Lambda Functio...
Result of Lambda Function.

The result is returned normally.
You can see that the function has successfully acted.

The following is the e-mail sent to the specified address.

SNS Message.

The email with the title and body specified for verification has been received.
As you can see, it is possible to specify an e-mail address as a subscriber to SNS topics.

Summary

We have introduced how to specify an email address as the notification destination for SNS topics.