DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

SBOMs are essential to circumventing software supply chain attacks, and they provide visibility into various software components.

Related

  • Serverless at Scale
  • The AWS Playbook for Building Future-Ready Data Systems
  • AWS CloudTrail Monitoring Using Event-Driven Ansible
  • Building Scalable Data Lake Using AWS

Trending

  • Vibe Coding: Conversational Software Development - Part 2, In Practice
  • Run Scalable Python Workloads With Modal
  • How to Troubleshoot Common Linux VPS Issues: CPU, Memory, Disk Usage
  • Multiple Stakeholder Management in Software Engineering
  1. DZone
  2. Software Design and Architecture
  3. Cloud Architecture
  4. AWS Lambda: Programmatically Scheduling a CloudWatch Event

AWS Lambda: Programmatically Scheduling a CloudWatch Event

AWS Lambda is a solid serverless option, but setting up automatically scheduled events might not be intuitive. Let's see how CloudWatch can solve the problem.

By 
Mark Needham user avatar
Mark Needham
·
May. 01, 17 · Tutorial
Likes (4)
Comment
Save
Tweet
Share
20.7K Views

Join the DZone community and get the full member experience.

Join For Free

I recently wrote a blog post showing how to create a Python ‘Hello World’ AWS Lambda function and manually invoke it, but what I really wanted to do was have it run automatically every hour.

To achieve that in AWS Lambda land, we need to create a CloudWatch Event. The documentation describes them as follows:

Using simple rules that you can quickly set up, you can match events and route them to one or more target functions or streams.

Image title

This is actually really easy from the Amazon web console, as you just need to click the ‘Triggers’ tab and then ‘Add trigger’. It’s not obvious that there are actually three steps are involved as they’re abstracted from you.

So what are the steps?

  1. Create rule
  2. Give permission for that rule to execute
  3. Map the rule to the function

I forgot to do step 2 initially, and then you just end up with a rule that never triggers, which isn’t particularly useful.

The following code creates a ‘Hello World’ Lambda function and runs it once an hour:

import boto3

lambda_client = boto3.client('lambda')
events_client = boto3.client('events')

fn_name = "HelloWorld"
fn_role = 'arn:aws:iam::[your-aws-id]:role/lambda_basic_execution'

fn_response = lambda_client.create_function(
    FunctionName=fn_name,
    Runtime='python2.7',
    Role=fn_role,
    Handler="{0}.lambda_handler".format(fn_name),
    Code={'ZipFile': open("{0}.zip".format(fn_name), 'rb').read(), },
)

fn_arn = fn_response['FunctionArn']
frequency = "rate(1 hour)"
name = "{0}-Trigger".format(fn_name)

rule_response = events_client.put_rule(
    Name=name,
    ScheduleExpression=frequency,
    State='ENABLED',
)

lambda_client.add_permission(
    FunctionName=fn_name,
    StatementId="{0}-Event".format(name),
    Action='lambda:InvokeFunction',
    Principal='events.amazonaws.com',
    SourceArn=rule_response['RuleArn'],
)

events_client.put_targets(
    Rule=name,
    Targets=[
        {
            'Id': "1",
            'Arn': fn_arn,
        },
    ]
)


import boto3 lambda_client = boto3.client('lambda') events_client = boto3.client('events') fn_name = "HelloWorld" fn_role = 'arn:aws:iam::[your-aws-id]:role/lambda_basic_execution' fn_response = lambda_client.create_function( FunctionName=fn_name, Runtime='python2.7', Role=fn_role, Handler="{0}.lambda_handler".format(fn_name), Code={'ZipFile': open("{0}.zip".format(fn_name), 'rb').read(), }, ) fn_arn = fn_response['FunctionArn'] frequency = "rate(1 hour)" name = "{0}-Trigger".format(fn_name) rule_response = events_client.put_rule( Name=name, ScheduleExpression=frequency, State='ENABLED', ) lambda_client.add_permission( FunctionName=fn_name, StatementId="{0}-Event".format(name), Action='lambda:InvokeFunction', Principal='events.amazonaws.com', SourceArn=rule_response['RuleArn'], ) events_client.put_targets( Rule=name, Targets=[ { 'Id': "1", 'Arn': fn_arn, }, ] )

We can now check if our trigger has been configured correctly:

$ aws events list-rules --query "Rules[?Name=='HelloWorld-Trigger']"
[
    {
        "State": "ENABLED", 
        "ScheduleExpression": "rate(1 hour)", 
        "Name": "HelloWorld-Trigger", 
        "Arn": "arn:aws:events:us-east-1:[your-aws-id]:rule/HelloWorld-Trigger"
    }
]

$ aws events list-targets-by-rule --rule HelloWorld-Trigger
{
    "Targets": [
        {
            "Id": "1", 
            "Arn": "arn:aws:lambda:us-east-1:[your-aws-id]:function:HelloWorld"
        }
    ]
}

$ aws lambda get-policy --function-name HelloWorld
{
    "Policy": "{\"Version\":\"2012-10-17\",\"Id\":\"default\",\"Statement\":[{\"Sid\":\"HelloWorld-Trigger-Event\",\"Effect\":\"Allow\",\"Principal\":{\"Service\":\"events.amazonaws.com\"},\"Action\":\"lambda:InvokeFunction\",\"Resource\":\"arn:aws:lambda:us-east-1:[your-aws-id]:function:HelloWorld\",\"Condition\":{\"ArnLike\":{\"AWS:SourceArn\":\"arn:aws:events:us-east-1:[your-aws-id]:rule/HelloWorld-Trigger\"}}}]}"
}


All looks good, so we’re done! 

Be sociable and share!


AWS AWS Lambda Event Scheduling (computing)

Published at DZone with permission of Mark Needham, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Serverless at Scale
  • The AWS Playbook for Building Future-Ready Data Systems
  • AWS CloudTrail Monitoring Using Event-Driven Ansible
  • Building Scalable Data Lake Using AWS

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • [email protected]

Let's be friends: