The EventBridge rule will match events for EC2 instance state changes and invoke the Lambda function.

Let’s consider another example where you want to trigger an AWS Lambda function when an EC2 instance state changes. The EventBridge rule will match events for EC2 instance state changes and invoke the Lambda function.

Step 1: Create an AWS Lambda Function

Create an AWS Lambda function that will be triggered by the EventBridge rule.

Example Lambda function code (Node.js):

javascriptCopy code// Lambda function code (index.js)
exports.handler = async (event) => {
    console.log("EC2 instance state change event:", JSON.stringify(event, null, 2));
    // Your custom logic here
    return {
        statusCode: 200,
        body: JSON.stringify('Lambda function executed successfully'),
    };
};

Step 2: Create an EventBridge Rule

Create an EventBridge rule that matches events when an EC2 instance state changes.

hclCopy code# Terraform script for creating EventBridge resources
provider "aws" {
  region = "us-east-1"  # Change to your desired region
}

resource "aws_iam_role" "lambda_execution_role" {
  name = "lambda_execution_role"

  assume_role_policy = jsonencode({
    Version = "2012-10-17",
    Statement = [
      {
        Action = "sts:AssumeRole",
        Effect = "Allow",
        Principal = {
          Service = "lambda.amazonaws.com"
        }
      }
    ]
  })
}

resource "aws_lambda_function" "my_lambda_function" {
  filename      = "lambda.zip"  # Path to your Lambda function code (zip file)
  function_name = "my_lambda_function"
  role          = aws_iam_role.lambda_execution_role.arn
  handler       = "index.handler"
  runtime       = "nodejs14.x"
}

resource "aws_cloudwatch_event_rule" "ec2_state_change_rule" {
  name        = "ec2_state_change_rule"
  description = "Event rule for EC2 instance state changes"
  event_pattern = <<PATTERN
{
  "source": ["aws.ec2"],
  "detail-type": ["EC2 Instance State-change Notification"],
  "detail": {
    "state": ["pending", "running", "shutting-down", "terminated", "stopping", "stopped"]
  }
}
PATTERN
}

resource "aws_cloudwatch_event_target" "lambda_target" {
  rule        = aws_cloudwatch_event_rule.ec2_state_change_rule.name
  arn         = aws_lambda_function.my_lambda_function.arn
}

In this example, the EventBridge rule is configured to match events from the AWS EC2 service with the detail-type “EC2 Instance State-change Notification” and specific states.

Step 3: Deploy Resources

Run terraform init and terraform apply to deploy the resources.

Step 4: Trigger EC2 Instance State Change

Trigger an EC2 instance state change (e.g., start, stop an instance), and you should see the Lambda function being triggered by the EventBridge rule.

This example showcases how EventBridge can be used to build event-driven architectures, reacting to specific events in AWS services. You can customize the event pattern to match your specific requirements.