Skip to content

Commit beee694

Browse files
sobrabkaiz-io
andauthored
Feat(java/eventbridge):added a java example for an EventBridge Rule scheduled Lambda (#1073)
Co-authored-by: Michael Kaiser <[email protected]>
1 parent bf6877e commit beee694

File tree

8 files changed

+463
-0
lines changed

8 files changed

+463
-0
lines changed

java/eventbridge-lambda/.gitignore

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
.classpath.txt
2+
target
3+
.classpath
4+
.project
5+
.idea
6+
.settings
7+
.vscode
8+
*.iml
9+
10+
# CDK asset staging directory
11+
.cdk.staging
12+
cdk.out

java/eventbridge-lambda/README.md

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
# EventBridge Rule scheduled Lambda
2+
3+
<!--BEGIN STABILITY BANNER-->
4+
5+
---
6+
7+
![Stability: Stable](https://img.shields.io/badge/stability-Stable-success.svg?style=for-the-badge)
8+
9+
> **This is a stable example. It should successfully build out of the box**
10+
>
11+
> This example is built on Construct Libraries marked "Stable" and does not have any infrastructure prerequisites to build.
12+
13+
---
14+
<!--END STABILITY BANNER-->
15+
16+
This example creates a new EventBridge rule that executes a Lambda function every minute. It sends an email via the lambda that calls an SNS topic.
17+
18+
## Build
19+
20+
To build this example, you need to be in this example's root directory. Then run the following:
21+
22+
```bash
23+
npm install -g aws-cdk
24+
npm install
25+
cdk synth
26+
```
27+
28+
This will install the necessary CDK, then this example's dependencies, and then build the CloudFormation template. The resulting CloudFormation template will be in the `cdk.out` directory.
29+
30+
## Deploy
31+
32+
Run `cdk deploy --parameters email=<email_address>` replacing <email_address> with a valid email address. This will deploy / redeploy the Stack to AWS and start sending email notifications to the address provided every 1 minute.
33+
34+
## Useful commands
35+
36+
* `mvn package` compile and run tests
37+
* `cdk ls` list all stacks in the app
38+
* `cdk synth` emits the synthesized CloudFormation template
39+
* `cdk deploy` deploy this stack to your default AWS account/region
40+
* `cdk diff` compare deployed stack with current state
41+
* `cdk docs` open CDK documentation

java/eventbridge-lambda/cdk.json

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
{
2+
"app": "mvn -e -q compile exec:java",
3+
"watch": {
4+
"include": [
5+
"**"
6+
],
7+
"exclude": [
8+
"README.md",
9+
"cdk*.json",
10+
"target",
11+
"pom.xml",
12+
"src/test"
13+
]
14+
},
15+
"context": {
16+
"@aws-cdk/aws-lambda:recognizeLayerVersion": true,
17+
"@aws-cdk/core:checkSecretUsage": true,
18+
"@aws-cdk/core:target-partitions": [
19+
"aws",
20+
"aws-cn"
21+
],
22+
"@aws-cdk-containers/ecs-service-extensions:enableDefaultLogDriver": true,
23+
"@aws-cdk/aws-ec2:uniqueImdsv2TemplateName": true,
24+
"@aws-cdk/aws-ecs:arnFormatIncludesClusterName": true,
25+
"@aws-cdk/aws-iam:minimizePolicies": true,
26+
"@aws-cdk/core:validateSnapshotRemovalPolicy": true,
27+
"@aws-cdk/aws-codepipeline:crossAccountKeyAliasStackSafeResourceName": true,
28+
"@aws-cdk/aws-s3:createDefaultLoggingPolicy": true,
29+
"@aws-cdk/aws-sns-subscriptions:restrictSqsDescryption": true,
30+
"@aws-cdk/aws-apigateway:disableCloudWatchRole": true,
31+
"@aws-cdk/core:enablePartitionLiterals": true,
32+
"@aws-cdk/aws-events:eventsTargetQueueSameAccount": true,
33+
"@aws-cdk/aws-ecs:disableExplicitDeploymentControllerForCircuitBreaker": true,
34+
"@aws-cdk/aws-iam:importedRoleStackSafeDefaultPolicyName": true,
35+
"@aws-cdk/aws-s3:serverAccessLogsUseBucketPolicy": true,
36+
"@aws-cdk/aws-route53-patters:useCertificate": true,
37+
"@aws-cdk/customresources:installLatestAwsSdkDefault": false,
38+
"@aws-cdk/aws-rds:databaseProxyUniqueResourceName": true,
39+
"@aws-cdk/aws-codedeploy:removeAlarmsFromDeploymentGroup": true,
40+
"@aws-cdk/aws-apigateway:authorizerChangeDeploymentLogicalId": true,
41+
"@aws-cdk/aws-ec2:launchTemplateDefaultUserData": true,
42+
"@aws-cdk/aws-secretsmanager:useAttachedSecretResourcePolicyForSecretTargetAttachments": true,
43+
"@aws-cdk/aws-redshift:columnId": true,
44+
"@aws-cdk/aws-stepfunctions-tasks:enableEmrServicePolicyV2": true,
45+
"@aws-cdk/aws-ec2:restrictDefaultSecurityGroup": true,
46+
"@aws-cdk/aws-apigateway:requestValidatorUniqueId": true,
47+
"@aws-cdk/aws-kms:aliasNameRef": true,
48+
"@aws-cdk/aws-autoscaling:generateLaunchTemplateInsteadOfLaunchConfig": true,
49+
"@aws-cdk/core:includePrefixInUniqueNameGeneration": true,
50+
"@aws-cdk/aws-efs:denyAnonymousAccess": true,
51+
"@aws-cdk/aws-opensearchservice:enableOpensearchMultiAzWithStandby": true,
52+
"@aws-cdk/aws-lambda-nodejs:useLatestRuntimeVersion": true,
53+
"@aws-cdk/aws-efs:mountTargetOrderInsensitiveLogicalId": true,
54+
"@aws-cdk/aws-rds:auroraClusterChangeScopeOfInstanceParameterGroupWithEachParameters": true,
55+
"@aws-cdk/aws-appsync:useArnForSourceApiAssociationIdentifier": true,
56+
"@aws-cdk/aws-rds:preventRenderingDeprecatedCredentials": true,
57+
"@aws-cdk/aws-codepipeline-actions:useNewDefaultBranchForCodeCommitSource": true,
58+
"@aws-cdk/aws-cloudwatch-actions:changeLambdaPermissionLogicalIdForLambdaAction": true,
59+
"@aws-cdk/aws-codepipeline:crossAccountKeysDefaultValueToFalse": true,
60+
"@aws-cdk/aws-codepipeline:defaultPipelineTypeToV2": true,
61+
"@aws-cdk/aws-kms:reduceCrossAccountRegionPolicyScope": true,
62+
"@aws-cdk/aws-eks:nodegroupNameAttribute": true,
63+
"@aws-cdk/aws-ec2:ebsDefaultGp3Volume": true,
64+
"@aws-cdk/aws-ecs:removeDefaultDeploymentAlarm": true,
65+
"@aws-cdk/custom-resources:logApiResponseDataPropertyTrueDefault": false,
66+
"@aws-cdk/aws-s3:keepNotificationInImportedBucket": false
67+
}
68+
}

java/eventbridge-lambda/pom.xml

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
3+
xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
4+
<modelVersion>4.0.0</modelVersion>
5+
6+
<groupId>com.myorg</groupId>
7+
<artifactId>eventbridge-lambda</artifactId>
8+
<version>0.1</version>
9+
10+
<properties>
11+
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
12+
<cdk.version>2.158.0</cdk.version>
13+
<constructs.version>[10.0.0,11.0.0)</constructs.version>
14+
<junit.version>5.7.1</junit.version>
15+
</properties>
16+
17+
<build>
18+
<plugins>
19+
<plugin>
20+
<groupId>org.apache.maven.plugins</groupId>
21+
<artifactId>maven-compiler-plugin</artifactId>
22+
<version>3.11.0</version>
23+
<configuration>
24+
<source>17</source>
25+
<target>17</target>
26+
</configuration>
27+
</plugin>
28+
29+
<plugin>
30+
<groupId>org.codehaus.mojo</groupId>
31+
<artifactId>exec-maven-plugin</artifactId>
32+
<version>3.1.0</version>
33+
<configuration>
34+
<mainClass>com.myorg.EventBridgeLambdaApp</mainClass>
35+
</configuration>
36+
</plugin>
37+
</plugins>
38+
</build>
39+
40+
<dependencies>
41+
42+
<dependency>
43+
<groupId>software.amazon.awscdk</groupId>
44+
<artifactId>aws-cdk-lib</artifactId>
45+
<version>${cdk.version}</version>
46+
</dependency>
47+
48+
<dependency>
49+
<groupId>software.constructs</groupId>
50+
<artifactId>constructs</artifactId>
51+
<version>${constructs.version}</version>
52+
</dependency>
53+
54+
<dependency>
55+
<groupId>org.junit.jupiter</groupId>
56+
<artifactId>junit-jupiter</artifactId>
57+
<version>${junit.version}</version>
58+
<scope>test</scope>
59+
</dependency>
60+
</dependencies>
61+
</project>
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
package com.myorg;
2+
3+
import software.amazon.awscdk.App;
4+
import software.amazon.awscdk.StackProps;
5+
6+
public class EventBridgeLambdaApp {
7+
public static void main(final String... args) {
8+
App app = new App();
9+
StackProps stackProps = StackProps.builder().build();
10+
new EventBridgeLambdaStack(app, "EventBridgeLambdaStack", stackProps);
11+
app.synth();
12+
}
13+
}
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
package com.myorg;
2+
3+
import software.amazon.awscdk.*;
4+
import software.amazon.awscdk.services.events.Rule;
5+
import software.amazon.awscdk.services.events.RuleProps;
6+
import software.amazon.awscdk.services.events.Schedule;
7+
import software.amazon.awscdk.services.events.targets.LambdaFunction;
8+
import software.amazon.awscdk.services.iam.PolicyStatement;
9+
import software.amazon.awscdk.services.iam.PolicyStatementProps;
10+
import software.amazon.awscdk.services.lambda.InlineCode;
11+
import software.amazon.awscdk.services.lambda.Runtime;
12+
import software.amazon.awscdk.services.lambda.SingletonFunction;
13+
import software.amazon.awscdk.services.sns.Topic;
14+
import software.amazon.awscdk.services.sns.TopicProps;
15+
import software.amazon.awscdk.services.sns.subscriptions.EmailSubscription;
16+
import software.constructs.Construct;
17+
18+
import java.io.IOException;
19+
import java.nio.file.Files;
20+
import java.nio.file.Path;
21+
import java.util.List;
22+
import java.util.Map;
23+
24+
public class EventBridgeLambdaStack extends Stack {
25+
public EventBridgeLambdaStack(final Construct scope, final String id, final StackProps props) {
26+
super(scope, id, props);
27+
TopicProps topicProps = TopicProps.builder()
28+
.displayName("Lambda SNS Topic")
29+
.build();
30+
Topic topic = new Topic(this, "Topic", topicProps);
31+
CfnParameterProps emailAddressCfnParameterProps = CfnParameterProps.builder()
32+
.type("String")
33+
.description("The e-mail address where notifications are to be sent.")
34+
.build();
35+
CfnParameter emailAddressParameter = new CfnParameter(this, "email", emailAddressCfnParameterProps);
36+
topic.addSubscription(new EmailSubscription(emailAddressParameter.getValueAsString()));
37+
SingletonFunction lambdaFunction = SingletonFunction.Builder.create(this, "Singleton")
38+
.functionName("Singleton")
39+
.code(InlineCode.fromInline(getInlineCode()))
40+
.handler("index.main")
41+
.timeout(Duration.seconds(300))
42+
.runtime(Runtime.PYTHON_3_9)
43+
.environment(Map.of("TOPIC_ARN", topic.getTopicArn()))
44+
.uuid("")
45+
.build();
46+
RuleProps ruleProps = RuleProps.builder()
47+
.schedule(Schedule.expression("cron(* * ? * * *)"))
48+
.build();
49+
Rule eventsRule = new Rule(this, "Rule", ruleProps);
50+
eventsRule.addTarget(new LambdaFunction(lambdaFunction));
51+
PolicyStatement snsTopicPolicy = new PolicyStatement(
52+
PolicyStatementProps.builder()
53+
.actions(List.of("sns:publish"))
54+
.resources(List.of("*"))
55+
.build()
56+
);
57+
lambdaFunction.addToRolePolicy(snsTopicPolicy);
58+
}
59+
60+
private String getInlineCode() {
61+
try {
62+
return new String(Files.readAllBytes(Path.of("src/main/resources/lambda/lambda-handler.py")));
63+
} catch (IOException e) {
64+
throw new RuntimeException(e);
65+
}
66+
}
67+
}
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
import json
2+
import boto3
3+
import os
4+
client = boto3.client('sns')
5+
6+
def main(event, context):
7+
print("I'm running!")
8+
response = client.publish(TopicArn=os.environ.get('TOPIC_ARN'),Message="Test message")
9+
print("Message published")
10+
return(response)

0 commit comments

Comments
 (0)