diff --git a/lambda-endusermessaging/README.md b/lambda-endusermessaging/README.md new file mode 100644 index 000000000..089d4d308 --- /dev/null +++ b/lambda-endusermessaging/README.md @@ -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 + +![Lambda End User Messaging Architecture](images/lambda_endusermessaging.png) + +### 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 \ No newline at end of file diff --git a/lambda-endusermessaging/app.py b/lambda-endusermessaging/app.py new file mode 100644 index 000000000..bbc403326 --- /dev/null +++ b/lambda-endusermessaging/app.py @@ -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() \ No newline at end of file diff --git a/lambda-endusermessaging/cdk.json b/lambda-endusermessaging/cdk.json new file mode 100644 index 000000000..0216f6516 --- /dev/null +++ b/lambda-endusermessaging/cdk.json @@ -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 + } +} diff --git a/lambda-endusermessaging/example-pattern.json b/lambda-endusermessaging/example-pattern.json new file mode 100644 index 000000000..84c7fd7ee --- /dev/null +++ b/lambda-endusermessaging/example-pattern.json @@ -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:cdk deploy." + ] + }, + "testing": { + "text": [ + "See the GitHub repo for detailed testing instructions." + ] + }, + "cleanup": { + "text": [ + "Delete the stack: cdk delete." + ] + }, + "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" + } + ] +} diff --git a/lambda-endusermessaging/images/lambda_endusermessaging.png b/lambda-endusermessaging/images/lambda_endusermessaging.png new file mode 100644 index 000000000..33ef1d5c1 Binary files /dev/null and b/lambda-endusermessaging/images/lambda_endusermessaging.png differ diff --git a/lambda-endusermessaging/lambda-endusermessaging.json b/lambda-endusermessaging/lambda-endusermessaging.json new file mode 100644 index 000000000..9d84d8c3f --- /dev/null +++ b/lambda-endusermessaging/lambda-endusermessaging.json @@ -0,0 +1,90 @@ +{ + "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:cdk deploy." + ] + }, + "testing": { + "text": [ + "See the GitHub repo for detailed testing instructions." + ] + }, + "cleanup": { + "text": [ + "Delete the stack: cdk delete." + ] + }, + "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" + } + ], + "patternArch": { + "icon1": { + "x": 20, + "y": 50, + "service": "eventbridge", + "label": "EventBridge Schedule" + }, + "icon2": { + "x": 50, + "y": 50, + "service": "lambda", + "label": "AWS Lambda" + }, + "icon3": { + "x": 80, + "y": 50, + "service": "pinpoint", + "label": "End User Messaging" + }, + "line1": { + "from": "icon1", + "to": "icon2", + "label": "" + }, + "line2": { + "from": "icon2", + "to": "icon3", + "label": "" + } + } +} diff --git a/lambda-endusermessaging/lambda/simple_sms_sender/requirements.txt b/lambda-endusermessaging/lambda/simple_sms_sender/requirements.txt new file mode 100644 index 000000000..2cf4eaba5 --- /dev/null +++ b/lambda-endusermessaging/lambda/simple_sms_sender/requirements.txt @@ -0,0 +1 @@ +boto3>=1.28.0 \ No newline at end of file diff --git a/lambda-endusermessaging/lambda/simple_sms_sender/send_sms.py b/lambda-endusermessaging/lambda/simple_sms_sender/send_sms.py new file mode 100644 index 000000000..dcce43f22 --- /dev/null +++ b/lambda-endusermessaging/lambda/simple_sms_sender/send_sms.py @@ -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() + }) + } \ No newline at end of file diff --git a/lambda-endusermessaging/requirements.txt b/lambda-endusermessaging/requirements.txt new file mode 100644 index 000000000..b1aa9e191 --- /dev/null +++ b/lambda-endusermessaging/requirements.txt @@ -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 + diff --git a/lambda-endusermessaging/simple_sms_messaging/__init__.py b/lambda-endusermessaging/simple_sms_messaging/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/lambda-endusermessaging/simple_sms_messaging/constants.py b/lambda-endusermessaging/simple_sms_messaging/constants.py new file mode 100644 index 000000000..4c9b1ae05 --- /dev/null +++ b/lambda-endusermessaging/simple_sms_messaging/constants.py @@ -0,0 +1,5 @@ +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." \ No newline at end of file diff --git a/lambda-endusermessaging/simple_sms_messaging/simple_sms_messaging_stack.py b/lambda-endusermessaging/simple_sms_messaging/simple_sms_messaging_stack.py new file mode 100644 index 000000000..192bbd81b --- /dev/null +++ b/lambda-endusermessaging/simple_sms_messaging/simple_sms_messaging_stack.py @@ -0,0 +1,112 @@ +from aws_cdk import ( + Duration, + Stack, + aws_lambda as _lambda, + aws_events as events, + aws_events_targets as targets, + aws_iam as iam, + aws_logs as logs, + CfnOutput, +) +from constructs import Construct +from simple_sms_messaging import constants + +class SimpleSmSMessagingStack(Stack): + + def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None: + super().__init__(scope, construct_id, **kwargs) + + # Create IAM role for SMS Sender Lambda + sms_sender_role = iam.Role( + self, "SmsSenderRole", + assumed_by=iam.ServicePrincipal("lambda.amazonaws.com"), + managed_policies=[ + iam.ManagedPolicy.from_aws_managed_policy_name("service-role/AWSLambdaBasicExecutionRole") + ] + ) + + # Add SMS permissions + sms_sender_role.add_to_policy( + iam.PolicyStatement( + effect=iam.Effect.ALLOW, + actions=[ + "sms-voice:SendTextMessage", + ], + resources=["*"] + ) + ) + + # Add Secrets Manager permissions + sms_sender_role.add_to_policy( + iam.PolicyStatement( + effect=iam.Effect.ALLOW, + actions=[ + "secretsmanager:GetSecretValue" + ], + resources=[ + constants.DESTINATION_PHONE_SECRET_ARN, + constants.ORIGINATION_PHONE_SECRET_ARN + ] + ) + ) + + # Create SMS Sender Lambda Function + sms_sender_function = _lambda.Function( + self, "SmsSenderFunction", + runtime=_lambda.Runtime.PYTHON_3_13, + handler="send_sms.lambda_handler", + code=_lambda.Code.from_asset("lambda/simple_sms_sender"), + timeout=Duration.seconds(30), + memory_size=128, + role=sms_sender_role, + environment={ + "DESTINATION_PHONE_SECRET_ARN": constants.DESTINATION_PHONE_SECRET_ARN, + "ORIGINATION_PHONE_SECRET_ARN": constants.ORIGINATION_PHONE_SECRET_ARN, + "MESSAGE": constants.MESSAGE + }, + log_retention=logs.RetentionDays.ONE_WEEK + ) + + # Create EventBridge rule for scheduling + schedule_rule = events.Rule( + self, "DailyMessageSchedule", + schedule=events.Schedule.cron( + minute=str(constants.SCHEDULE_MINUTE), + hour=str(constants.SCHEDULE_HOUR), + day="*", + month="*", + year="*" + ), + description="Simple daily SMS message schedule" + ) + + # Add SMS sender function as target + schedule_rule.add_target( + targets.LambdaFunction(sms_sender_function) + ) + + # Grant EventBridge permission to invoke Lambda + sms_sender_function.add_permission( + "AllowEventBridge", + principal=iam.ServicePrincipal("events.amazonaws.com"), + source_arn=schedule_rule.rule_arn + ) + + # Outputs + CfnOutput( + self, "SmsSenderFunctionName", + value=sms_sender_function.function_name, + description="SMS Sender Lambda Function Name" + ) + + CfnOutput( + self, "ScheduleRuleArn", + value=schedule_rule.rule_arn, + description="EventBridge Schedule Rule ARN" + ) + + CfnOutput( + self, "ScheduleExpression", + value=f"cron({constants.SCHEDULE_MINUTE} {constants.SCHEDULE_HOUR} * * ? *)", + description="Schedule Expression (UTC)" + ) \ No newline at end of file