Loading...

Schedule AWS Lambda Function using Amazon EventBridge Rule

Schedule AWS Lambda Function using Amazon EventBridge Rule

You use Cron Jobs to schedule various IT tasks. In addition, Cron Jobs allows you to automate specific commands or scripts on your server to complete repetitive tasks automatically.

This article will show you how to create a simple scheduled task using AWS Lambda and Amazon EventBridge to post messages to a Slack channel.

The AWS Services

There are two AWS services involved in building the scheduled task on AWS which are:

Amazon EventBridge Rule: Amazon EventBridge delivers a near real-time stream of system events that describe Amazon Web Services (AWS) resources changes. You can also use EventBridge Events to schedule automated actions that self-trigger at specific times using cron or rate expressions.

AWS Lambda Function: AWS Lambda is a compute service that lets you run code without provisioning or managing servers. Lambda runs your code on a high-availability compute infrastructure and performs all the administration of the compute resources, including server and operating system maintenance, capacity provisioning and automatic scaling, code monitoring, and logging. You can run code for virtually any application or back-end service with Lambda. All you need to do is supply your code in one of the languages that Lambda supports.

Situation

Slack Workflow Builder is a visual tool that allows Slack users to automate routine functions by creating custom workflows. For example, the Scheduled date and time workflow trigger start automatically at a set date and time. But the problem with this trigger is that we cannot trigger the workflow every hour or minute. Instead, we must create duplicates of a scheduled workflow for different time schedules, which may not be a good solution. However, you can set up an Amazon EventBridge rule to run an AWS Lambda function on a schedule to overcome this limitation.

slack-bot-flow.png

Prerequisites

  • AWS Lambda Layer for Python requests package
  • Bot App registered with Slack Workspace with the necessary access token and permission scope to post message and read user details
  • Bot App installed on the target Slack channel

Step 1: Create an AWS Lambda function

  • Open the AWS Lambda console.
  • Choose Create Function. slack-bot-aws-lambda-1.png
  • Choose Author from scratch.
  • Enter a Function name. For example, name the function slack-bot.
  • Select Python 3.9 as Runtime slack-bot-aws-lambda-2.png
  • Leave the rest of the options as the defaults and choose Create Function. slack-bot-aws-lambda-4.png
  • On the Code tab of the function page, double click on lambda_function.py. Replace the existing code with the following code.
import requests
import json
from logging import exception

SLACK_INSTANCE_NAME = "your-slack-instance-name"
SLACK_TOKEN = "your-slack-token"
SLACK_BOT_USERNAME = "your-bot-username"
SLACK_CHANNEL_ID = "your-slack-channel-id"
SLACK_MESSAGE = "Hello, This is a test message from the AWS Lambda function. "


def post_message_in_slack(channel_id, message, posted_by):
    try:
        headers = {
            'Authorization': 'Bearer ' + SLACK_TOKEN,
            'Content-Type': 'application/json',
            'accept': 'application/json'
        }
        payload = json.dumps({
            "channel": channel_id,
            "text": message,
            "username": posted_by
        })
        url = f'https://{SLACK_INSTANCE_NAME}.slack.com/api/chat.postMessage'
        response = requests.post(url, headers=headers, data=payload)
        message = response.json().get('message', None)
        return message
    except requests.exceptions.RequestException as err:
        raise exception(err)


def lambda_handler(event, context):
    try:
        message = post_message_in_slack(
            SLACK_CHANNEL_ID, SLACK_MESSAGE, SLACK_BOT_USERNAME)
        messageId = message.get('ts', None)
        return {
            'statusCode': 200,
            'body': json.dumps('Message posted! Message ID: ' + messageId)
        }
    except Exception as err:
        return {
            'statusCode': 400,
            'body': json.dumps(str(err))
        }

NOTE: Update the environment-specific values in the sample code.

  • Under Layers, choose Add a layer.
  • For the Specify an ARN layer source:
    • Enter the requests layer ARN in the text box and choose Verify.
    • Choose Add. slack-bot-aws-lambda-6.png
  • Choose Deploy.

Step 2: Create Amazon EventBridge Rule

  • Open the Amazon EventBridge console.
  • In the navigation pane, choose Rules. Choose Create rule. slack-bot-amazon-eventbridge-1.png
  • Enter a name and description for the rule.
  • For Select event bus, choose AWS default event bus. Scheduled rules are supported only on the default event bus.
  • For Define pattern, do the following:
    • Choose Schedule.
    • Choose A schedule that runs at a regular rate, such as every 10 minutes. and specify the schedule interval, for example, 5 minutes. slack-bot-amazon-eventbridge-2.png slack-bot-amazon-eventbridge-3.png
  • For Target, choose Lambda function.
  • For Function, select the Lambda function that you created in step 1. slack-bot-amazon-eventbridge-4.png
  • Choose Create. slack-bot-amazon-eventbridge-5.png

This rule will be triggered every 5 minutes, and it will also trigger our Lambda function accordingly.

slack-bot-aws-cloudwatch-1.png

If you see the Lambda event in the CloudWatch logs, you can see the message posted in the Slack channel.

slack-bot-output.png

Thank you for reading this article. I hope it helped you in some way.

Published on:

Learn more
Need help with this product?

We can help you with Schedule AWS Lambda Function using Amazon EventBridge Rule

If you want help implementing, troubleshooting, or improving this product, contact us and we’ll point you in the right direction.

Home | Joseph Velliah
Home | Joseph Velliah

Fulfilling God’s purpose for my life

Share post:

Related posts

Jev Does Not Paint: Putting TypeSafe in Front of Gemini

I wanted a reason to use TypeSafe that was not another chatbot wrapper. Most of the AI I wire into software still wants to talk. I needed some...

9 days ago

I Asked God to Hold My Hand

Almost 20 years ago, I was waiting outside my company to collect my documents and start my first IT job. I sat under a banyan tree. That day ...

17 days ago

Identity-Aware SRE Agents with kagent on Akamai LKE

I wanted a reason to put an AI agent in front of a real Kubernetes cluster and watch what happens when two different people ask it to fix the ...

1 month ago

Vasanam Studio: How I Built a Bible Verse Video Generator for My Church as a Hobby Project

Every morning at 5 AM, the women of my church gather for prayer. At the end of the session, our pastor’s wife shares a Bible verse and sends a...

3 months ago

The demo worked. That was the problem.

Over a weekend I built a small Kubernetes demo to play with zero trust. Three little services calling each other in a chain, a login page in f...

4 months ago

Notes from building an agent on AgentCore end to end

I wanted a reason to use AgentCore end to end. Runtime, memory, guardrails, identity, the whole thing. A Bible Q&A agent felt like a good ...

5 months ago

Building a Rust gRPC AI Security Gateway for LLM Traffic

I wanted a small, honest implementation of the GenAI governance shape in code: a component on every LLM call that applies policy first, option...

6 months ago

Claude Code Security: The Smart Way to Integrate AI

Anthropic just dropped Claude Code Security, and if you’re anywhere near AppSec or DevSecOps, you’ve probably already seen the debate lighting...

7 months ago

How I Built a Semantic Cache Using Only AWS Services

LLM calls are expensive and slow, but here’s the thing - users ask the same questions in different ways all the time. “What’s your refund poli...

8 months ago

How to Build Better AI Agent Tools: Cut Costs by 70% (MCP Server Case Study)

Building tools for AI agents isn’t the same as building regular APIs. This guide shows you how to design tools that reduce token costs by 60-7...

8 months ago

Newsletter

Get the latest Dynamics 365 and Power Platform content in your inbox

A curated digest of community blogs, product news, videos, and podcasts — delivered without the noise.

Weekly updates Unsubscribe anytime Fresh community picks
We use your email only for the newsletter and you can unsubscribe at any time.
By subscribing, you agree to the privacy policy.