-
Notifications
You must be signed in to change notification settings - Fork 1k
New serverless pattern - lambda-endusermessaging #2800
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
SarathKumarKS
wants to merge
6
commits into
aws-samples:main
Choose a base branch
from
SarathKumarKS:SarathKumarKS-feature-lambda-endusermessaging
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
4749b3a
Personalized SMS Briefing using serverless architecture
SarathKumarKS 4e7e9ee
Initial code for Lambda-EUM
SarathKumarKS 26a0f98
Initial code for Lambda-EUM
SarathKumarKS 66ad618
Removed Lambda-bedrock-eum example folder
SarathKumarKS 8b4da6b
Review comments
SarathKumarKS c596530
Title changes
SarathKumarKS File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,155 @@ | ||
# Sending SMS with AWS Lambda and AWS End User Messaging | ||
|
||
This sample pattern demonstrates how to send scheduled SMS messages using AWS Lambda and AWS End User Messaging. The solution uses Amazon EventBridge to trigger a Lambda function at a specified time each day, which then sends an SMS message to a configured phone number. | ||
|
||
Built with a serverless-first approach, this solution automatically sends messages at your preferred time each day. | ||
|
||
**Important:** this application uses various AWS services and there are costs associated with these services after the Free Tier usage - please see the [AWS Pricing page](https://aws.amazon.com/pricing/) for details. You are responsible for any AWS costs incurred. No warranty is implied in this example. | ||
|
||
### Getting Started | ||
|
||
The entire solution is built using AWS Cloud Development Kit (CDK) and AWS Lambda functions running on Python 3.11 runtime. This serverless architecture ensures minimal operational overhead while providing maximum flexibility for customization. | ||
|
||
### Requirements | ||
|
||
* [Create an AWS account](https://portal.aws.amazon.com/gp/aws/developer/registration/index.html) if you do not already have one and log in. The IAM user that you use must have sufficient permissions to make necessary AWS service calls and manage AWS resources. | ||
* [AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2.html) installed and configured | ||
* [Git Installed](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git) | ||
* [AWS Cloud Development Kit](https://docs.aws.amazon.com/cdk/v2/guide/getting_started.html) installed | ||
* [Node.js](https://nodejs.org/en) and [npm](https://www.npmjs.com/) installed (required for CDK) | ||
* A destination phone number to receive SMS messages | ||
* An originating number based on your [country's requirements](https://docs.aws.amazon.com/sms-voice/latest/userguide/phone-numbers-sms-by-country.html) | ||
|
||
### AWS Services Used | ||
|
||
* AWS Lambda | ||
* AWS End User Messaging SMS | ||
* AWS Secrets Manager | ||
* Amazon EventBridge | ||
|
||
### Architecture Diagram | ||
|
||
 | ||
|
||
### How it works | ||
|
||
* EventBridge triggers the Lambda function daily at your specified time | ||
* Lambda function performs the following actions: | ||
* Retrieves phone numbers from AWS Secrets Manager | ||
* Uses End User Messaging to send SMS with a predefined message | ||
|
||
### Deployment Instructions | ||
|
||
1. Create a new directory, navigate to that directory in a terminal and clone the GitHub repository: | ||
``` | ||
git clone https://github.com/aws-samples/serverless-patterns/ | ||
``` | ||
2. Change directory to the pattern directory: | ||
``` | ||
cd lambda-endusermessaging | ||
``` | ||
|
||
3. Create [AWS Secrets Manager Secret](https://docs.aws.amazon.com/secretsmanager/latest/userguide/create_secret.html) Secrets for your destination phone number and origination phone number. | ||
|
||
Log in to your AWS account and navigate to the AWS Secrets Manager service in the AWS Console in your preferred region. Then select the Store a new secret button. | ||
|
||
For the secret type, select Other type of secret. Under Key/value pair, select the Plaintext tab and enter the phone number. For the encryption key, you can either encrypt using the AWS KMS key that AWS Secrets Manager creates or use a customer-managed AWS KMS key that you create. Select Next, provide the secret name as DestinationPhone, select Next, and click the Store button to create the secret. Note the secret ARN, as this will be needed for the next step. | ||
|
||
Repeat this process for your origination phone number, creating a separate secret named OriginationPhone. | ||
|
||
If you prefer the CLI option, use the commands below. Replace the placeholder values with your actual destination and origination phone numbers, along with your preferred region. | ||
|
||
``` | ||
aws secretsmanager create-secret \ | ||
--name "OriginationPhone" \ | ||
--description "Origination phone number for SMS sending" \ | ||
--secret-string "+12065550100" \ | ||
--region us-east-1 | ||
|
||
aws secretsmanager create-secret \ | ||
--name "DestinationPhone" \ | ||
--description "Destination phone number for SMS messages" \ | ||
--secret-string "+12065550123" \ | ||
--region us-east-1 | ||
``` | ||
|
||
4. Edit the constants.py file under the folder simple_sms_messaging and customize the following parameters according to your preferences: | ||
1. DESTINATION_PHONE_SECRET_ARN: The ARN of the secret containing the phone number where you want to receive SMS messages | ||
2. ORIGINATION_PHONE_SECRET_ARN: The ARN of the secret containing your verified sender ID for SMS messages | ||
3. SCHEDULE_HOUR and SCHEDULE_MINUTE: Your desired delivery time (in UTC) | ||
4. MESSAGE: The message you want to send | ||
|
||
Example below | ||
|
||
``` | ||
DESTINATION_PHONE_SECRET_ARN = "arn:aws:secretsmanager:us-west-2:123456789012:secret:destination-phone-Abc123" | ||
ORIGINATION_PHONE_SECRET_ARN = "arn:aws:secretsmanager:us-west-2:123456789012:secret:origination-phone-Def456" | ||
SCHEDULE_HOUR = 15 | ||
SCHEDULE_MINUTE = 0 | ||
MESSAGE = "Hello! This is your daily message from AWS End User Messaging." | ||
``` | ||
|
||
5. Create a virtualenv on MacOS and Linux | ||
``` | ||
python3 -m venv .venv | ||
``` | ||
6. After the init process completes and the virtualenv is created, you can use the following step to activate your virtualenv | ||
``` | ||
source .venv/bin/activate | ||
``` | ||
[Optional - for Windows] If you are a Windows platform, you would activate the virtualenv with below command | ||
|
||
``` | ||
.venv\Scripts\activate.bat | ||
``` | ||
7. Once the virtualenv is activated, you can install the required dependencies | ||
``` | ||
pip install -r requirements.txt | ||
``` | ||
8. Synthesize the CloudFormation template for this code | ||
``` | ||
cdk synth | ||
``` | ||
9. Deploy the stack | ||
|
||
``` | ||
cdk deploy | ||
``` | ||
### Testing Your Deployment | ||
|
||
* For quick verification of your deployment using only the AWS CLI, invoke the SMS sender function to trigger an immediate message: | ||
|
||
``` | ||
aws lambda invoke \ | ||
--function-name $(aws cloudformation describe-stacks --stack-name SimpleSmSMessagingStack --query "Stacks[0].Outputs[?OutputKey=='SmsSenderFunctionName'].OutputValue" --output text) \ | ||
--payload '{}' \ | ||
--cli-binary-format raw-in-base64-out \ | ||
response.json | ||
|
||
``` | ||
|
||
* Check the execution status for detailed logs and any error messages. You should also have received an SMS on the destination phone number. | ||
|
||
``` | ||
cat response.json | ||
``` | ||
|
||
### Cleanup | ||
|
||
1. To cleanup/delete resources created while deploying the solution, go to the root folder of the project repository and run | ||
``` | ||
cdk destroy | ||
``` | ||
|
||
### Useful commands | ||
|
||
* `cdk ls` list all stacks in the app | ||
* `cdk synth` emits the synthesized CloudFormation template | ||
* `cdk deploy` deploy this stack to your default AWS account/region | ||
* `cdk diff` compare deployed stack with current state | ||
* `cdk docs` open CDK documentation | ||
|
||
------ | ||
Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved. | ||
|
||
SPDX-License-Identifier: MIT-0 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,17 @@ | ||
#!/usr/bin/env python3 | ||
import os | ||
import aws_cdk as cdk | ||
from simple_sms_messaging.simple_sms_messaging_stack import SimpleSmSMessagingStack | ||
|
||
app = cdk.App() | ||
|
||
SimpleSmSMessagingStack( | ||
app, | ||
"SimpleSmSMessagingStack", | ||
env=cdk.Environment( | ||
account=os.getenv('CDK_DEFAULT_ACCOUNT'), | ||
region=os.getenv('CDK_DEFAULT_REGION') | ||
) | ||
) | ||
|
||
app.synth() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,94 @@ | ||
{ | ||
"app": "python3 app.py", | ||
"watch": { | ||
"include": [ | ||
"**" | ||
], | ||
"exclude": [ | ||
"README.md", | ||
"cdk*.json", | ||
"requirements*.txt", | ||
"source.bat", | ||
"**/__init__.py", | ||
"**/__pycache__", | ||
"tests" | ||
] | ||
}, | ||
"context": { | ||
"@aws-cdk/aws-lambda:recognizeLayerVersion": true, | ||
"@aws-cdk/core:checkSecretUsage": true, | ||
"@aws-cdk/core:target-partitions": [ | ||
"aws", | ||
"aws-cn" | ||
], | ||
"@aws-cdk-containers/ecs-service-extensions:enableDefaultLogDriver": true, | ||
"@aws-cdk/aws-ec2:uniqueImdsv2TemplateName": true, | ||
"@aws-cdk/aws-ecs:arnFormatIncludesClusterName": true, | ||
"@aws-cdk/aws-iam:minimizePolicies": true, | ||
"@aws-cdk/core:validateSnapshotRemovalPolicy": true, | ||
"@aws-cdk/aws-codepipeline:crossAccountKeyAliasStackSafeResourceName": true, | ||
"@aws-cdk/aws-s3:createDefaultLoggingPolicy": true, | ||
"@aws-cdk/aws-sns-subscriptions:restrictSqsDescryption": true, | ||
"@aws-cdk/aws-apigateway:disableCloudWatchRole": true, | ||
"@aws-cdk/core:enablePartitionLiterals": true, | ||
"@aws-cdk/aws-events:eventsTargetQueueSameAccount": true, | ||
"@aws-cdk/aws-ecs:disableExplicitDeploymentControllerForCircuitBreaker": true, | ||
"@aws-cdk/aws-iam:importedRoleStackSafeDefaultPolicyName": true, | ||
"@aws-cdk/aws-s3:serverAccessLogsUseBucketPolicy": true, | ||
"@aws-cdk/aws-route53-patters:useCertificate": true, | ||
"@aws-cdk/customresources:installLatestAwsSdkDefault": false, | ||
"@aws-cdk/aws-rds:databaseProxyUniqueResourceName": true, | ||
"@aws-cdk/aws-codedeploy:removeAlarmsFromDeploymentGroup": true, | ||
"@aws-cdk/aws-apigateway:authorizerChangeDeploymentLogicalId": true, | ||
"@aws-cdk/aws-ec2:launchTemplateDefaultUserData": true, | ||
"@aws-cdk/aws-secretsmanager:useAttachedSecretResourcePolicyForSecretTargetAttachments": true, | ||
"@aws-cdk/aws-redshift:columnId": true, | ||
"@aws-cdk/aws-stepfunctions-tasks:enableEmrServicePolicyV2": true, | ||
"@aws-cdk/aws-ec2:restrictDefaultSecurityGroup": true, | ||
"@aws-cdk/aws-apigateway:requestValidatorUniqueId": true, | ||
"@aws-cdk/aws-kms:aliasNameRef": true, | ||
"@aws-cdk/aws-autoscaling:generateLaunchTemplateInsteadOfLaunchConfig": true, | ||
"@aws-cdk/core:includePrefixInUniqueNameGeneration": true, | ||
"@aws-cdk/aws-efs:denyAnonymousAccess": true, | ||
"@aws-cdk/aws-opensearchservice:enableOpensearchMultiAzWithStandby": true, | ||
"@aws-cdk/aws-lambda-nodejs:useLatestRuntimeVersion": true, | ||
"@aws-cdk/aws-efs:mountTargetOrderInsensitiveLogicalId": true, | ||
"@aws-cdk/aws-rds:auroraClusterChangeScopeOfInstanceParameterGroupWithEachParameters": true, | ||
"@aws-cdk/aws-appsync:useArnForSourceApiAssociationIdentifier": true, | ||
"@aws-cdk/aws-rds:preventRenderingDeprecatedCredentials": true, | ||
"@aws-cdk/aws-codepipeline-actions:useNewDefaultBranchForCodeCommitSource": true, | ||
"@aws-cdk/aws-cloudwatch-actions:changeLambdaPermissionLogicalIdForLambdaAction": true, | ||
"@aws-cdk/aws-codepipeline:crossAccountKeysDefaultValueToFalse": true, | ||
"@aws-cdk/aws-codepipeline:defaultPipelineTypeToV2": true, | ||
"@aws-cdk/aws-kms:reduceCrossAccountRegionPolicyScope": true, | ||
"@aws-cdk/aws-eks:nodegroupNameAttribute": true, | ||
"@aws-cdk/aws-ec2:ebsDefaultGp3Volume": true, | ||
"@aws-cdk/aws-ecs:removeDefaultDeploymentAlarm": true, | ||
"@aws-cdk/custom-resources:logApiResponseDataPropertyTrueDefault": false, | ||
"@aws-cdk/aws-s3:keepNotificationInImportedBucket": false, | ||
"@aws-cdk/aws-ecs:enableImdsBlockingDeprecatedFeature": false, | ||
"@aws-cdk/aws-ecs:disableEcsImdsBlocking": true, | ||
"@aws-cdk/aws-ecs:reduceEc2FargateCloudWatchPermissions": true, | ||
"@aws-cdk/aws-dynamodb:resourcePolicyPerReplica": true, | ||
"@aws-cdk/aws-ec2:ec2SumTImeoutEnabled": true, | ||
"@aws-cdk/aws-appsync:appSyncGraphQLAPIScopeLambdaPermission": true, | ||
"@aws-cdk/aws-rds:setCorrectValueForDatabaseInstanceReadReplicaInstanceResourceId": true, | ||
"@aws-cdk/core:cfnIncludeRejectComplexResourceUpdateCreatePolicyIntrinsics": true, | ||
"@aws-cdk/aws-lambda-nodejs:sdkV3ExcludeSmithyPackages": true, | ||
"@aws-cdk/aws-stepfunctions-tasks:fixRunEcsTaskPolicy": true, | ||
"@aws-cdk/aws-ec2:bastionHostUseAmazonLinux2023ByDefault": true, | ||
"@aws-cdk/aws-route53-targets:userPoolDomainNameMethodWithoutCustomResource": true, | ||
"@aws-cdk/aws-elasticloadbalancingV2:albDualstackWithoutPublicIpv4SecurityGroupRulesDefault": true, | ||
"@aws-cdk/aws-iam:oidcRejectUnauthorizedConnections": true, | ||
"@aws-cdk/core:enableAdditionalMetadataCollection": true, | ||
"@aws-cdk/aws-lambda:createNewPoliciesWithAddToRolePolicy": false, | ||
"@aws-cdk/aws-s3:setUniqueReplicationRoleName": true, | ||
"@aws-cdk/aws-events:requireEventBusPolicySid": true, | ||
"@aws-cdk/core:aspectPrioritiesMutating": true, | ||
"@aws-cdk/aws-dynamodb:retainTableReplica": true, | ||
"@aws-cdk/aws-stepfunctions:useDistributedMapResultWriterV2": true, | ||
"@aws-cdk/s3-notifications:addS3TrustKeyPolicyForSnsSubscriptions": true, | ||
"@aws-cdk/aws-ec2:requirePrivateSubnetsForEgressOnlyInternetGateway": true, | ||
"@aws-cdk/aws-s3:publicAccessBlockedByDefault": true | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,60 @@ | ||
{ | ||
"title": "Sending SMS with AWS Lambda and AWS End User Messaging", | ||
"description": "Scheduled SMS messaging using AWS Lambda and AWS End User Messaging", | ||
"language": "Python", | ||
"level": "300", | ||
"framework": "AWS CDK", | ||
"introBox": { | ||
"headline": "How it works", | ||
"text": [ | ||
"This pattern demonstrates how to send scheduled SMS messages using AWS Lambda and AWS End User Messaging with a serverless architecture." | ||
] | ||
}, | ||
"gitHub": { | ||
"template": { | ||
"repoURL": "https://github.com/aws-samples/serverless-patterns/tree/main/lambda-endusermessaging", | ||
"templateURL": "serverless-patterns/lambda-endusermessaging", | ||
"projectFolder": "lambda-endusermessaging", | ||
"templateFile": "simple_sms_messaging/simple_sms_messaging_stack.py" | ||
} | ||
}, | ||
"resources": { | ||
"bullets": [ | ||
{ | ||
"text": "AWS Lambda", | ||
"link": "https://aws.amazon.com/lambda/" | ||
}, | ||
{ | ||
"text": "AWS End User Messaging", | ||
"link": "https://aws.amazon.com/end-user-messaging/" | ||
}, | ||
{ | ||
"text": "Amazon EventBridge", | ||
"link": "https://aws.amazon.com/eventbridge/" | ||
} | ||
] | ||
}, | ||
"deploy": { | ||
"text": [ | ||
"Deploy the stack:<code>cdk deploy</code>." | ||
] | ||
}, | ||
"testing": { | ||
"text": [ | ||
"See the GitHub repo for detailed testing instructions." | ||
] | ||
}, | ||
"cleanup": { | ||
"text": [ | ||
"Delete the stack: <code>cdk delete</code>." | ||
] | ||
}, | ||
"authors": [ | ||
{ | ||
"name": "Sarath Kumar K.S", | ||
"image": "https://i.postimg.cc/6qpwHbWD/IMG-0258.jpg", | ||
"bio": "Sarath is a Senior Technical Account Manager at AWS.", | ||
"linkedin": "kssarathkumar" | ||
} | ||
] | ||
} |
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
1 change: 1 addition & 0 deletions
1
lambda-endusermessaging/lambda/simple_sms_sender/requirements.txt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
boto3>=1.28.0 |
56 changes: 56 additions & 0 deletions
56
lambda-endusermessaging/lambda/simple_sms_sender/send_sms.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,56 @@ | ||
import json | ||
import os | ||
import boto3 | ||
from datetime import datetime | ||
|
||
def get_secret_value(secret_arn): | ||
"""Retrieve a secret value from AWS Secrets Manager""" | ||
client = boto3.client('secretsmanager') | ||
response = client.get_secret_value(SecretId=secret_arn) | ||
return response['SecretString'] | ||
|
||
def send_sms(phone_number: str, originating_number: str, message: str): | ||
"""Send SMS using AWS End User Messaging""" | ||
sms_client = boto3.client('pinpoint-sms-voice-v2') | ||
|
||
response = sms_client.send_text_message( | ||
DestinationPhoneNumber=phone_number, | ||
OriginationIdentity=originating_number, | ||
MessageBody=message | ||
) | ||
|
||
return response | ||
|
||
def lambda_handler(event, context): | ||
"""Main Lambda handler for sending SMS messages""" | ||
|
||
# Get configuration from environment variables | ||
message = os.environ['MESSAGE'] | ||
phone_number = get_secret_value(os.environ['DESTINATION_PHONE_SECRET_ARN']) | ||
originating_number = get_secret_value(os.environ['ORIGINATION_PHONE_SECRET_ARN']) | ||
|
||
try: | ||
# Send SMS | ||
sms_response = send_sms(phone_number, originating_number, message) | ||
|
||
print(f"SMS sent successfully: {message}") | ||
print(f"SMS Message ID: {sms_response.get('MessageId')}") | ||
|
||
return { | ||
'statusCode': 200, | ||
'body': json.dumps({ | ||
'message': 'SMS message sent successfully!', | ||
'sms_message_id': sms_response.get('MessageId'), | ||
'timestamp': datetime.now().isoformat() | ||
}) | ||
} | ||
|
||
except Exception as e: | ||
return { | ||
'statusCode': 500, | ||
'body': json.dumps({ | ||
'error': 'Failed to send SMS message', | ||
'details': str(e), | ||
'timestamp': datetime.now().isoformat() | ||
}) | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
aws-cdk-lib==2.199.0 | ||
constructs>=10.0.0,<11.0.0 | ||
boto3>=1.36.0 | ||
aws-cdk.aws-lambda-python-alpha==2.199.0a0 | ||
|
Empty file.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.