Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

build(examples): Add example for the powertools-cloudformation module #1089

Merged
merged 7 commits into from
Jul 19, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions examples/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
<module>powertools-examples-serialization</module>
<module>powertools-examples-sqs</module>
<module>powertools-examples-validation</module>
<module>powertools-examples-cloudformation</module>
</modules>

<!-- Don't deploy the examples -->
Expand Down
40 changes: 40 additions & 0 deletions examples/powertools-examples-cloudformation/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
# Cloudformation Custom Resource Example

This project contains an example of Lambda function using the CloudFormation module of Powertools for AWS Lambda in Java. For more information on this module, please refer to the [documentation](https://awslabs.github.io/aws-lambda-powertools-java/utilities/custom_resources/).

## Deploy the sample application

This sample can be used either with the Serverless Application Model (SAM) or with CDK.

### Deploy with SAM CLI
To use the SAM CLI, you need the following tools.

* SAM CLI - [Install the SAM CLI](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html)
* Java 8 - [Install Java 8](https://docs.aws.amazon.com/corretto/latest/corretto-8-ug/downloads-list.html)
* Maven - [Install Maven](https://maven.apache.org/install.html)
* Docker - [Install Docker community edition](https://hub.docker.com/search/?type=edition&offering=community)

To build and deploy this application for the first time, run the following in your shell:

```bash
cd infra/sam
sam build
sam deploy --guided --parameter-overrides BucketNameParam=my-unique-bucket-20230717
```

### Deploy with CDK
To use CDK you need the following tools.

* CDK - [Install CDK](https://docs.aws.amazon.com/cdk/v2/guide/getting_started.html)
* Java 8 - [Install Java 8](https://docs.aws.amazon.com/corretto/latest/corretto-8-ug/downloads-list.html)
* Maven - [Install Maven](https://maven.apache.org/install.html)
* Docker - [Install Docker community edition](https://hub.docker.com/search/?type=edition&offering=community)

To build and deploy this application for the first time, run the following in your shell:

```bash
cd infra/cdk
mvn package
cdk synth
cdk deploy -c BucketNameParam=my-unique-bucket-20230718
```
13 changes: 13 additions & 0 deletions examples/powertools-examples-cloudformation/infra/cdk/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
.classpath.txt
target
.classpath
.project
.idea
.settings
.vscode
*.iml

# CDK asset staging directory
.cdk.staging
cdk.out

37 changes: 37 additions & 0 deletions examples/powertools-examples-cloudformation/infra/cdk/cdk.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
{
"app": "mvn -e -q compile exec:java",
"watch": {
"include": [
"**"
],
"exclude": [
"README.md",
"cdk*.json",
"target",
"pom.xml",
"src/test"
]
},
"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-iam:standardizedServicePrincipals": true,
"@aws-cdk/aws-ecs:disableExplicitDeploymentControllerForCircuitBreaker": true,
"@aws-cdk/aws-s3:serverAccessLogsUseBucketPolicy": true
}
}
53 changes: 53 additions & 0 deletions examples/powertools-examples-cloudformation/infra/cdk/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>

<groupId>com.myorg</groupId>
<artifactId>powertools-examples-cloudformation-cdk</artifactId>
<version>0.1</version>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<cdk.version>2.59.0</cdk.version>
<constructs.version>[10.0.0,11.0.0)</constructs.version>
</properties>

<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>8</source>
<target>8</target>
</configuration>
</plugin>

<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>3.0.0</version>
<configuration>
<mainClass>com.myorg.PowertoolsExamplesCloudformationCdkApp</mainClass>
</configuration>
</plugin>
</plugins>
</build>

<dependencies>
<!-- AWS Cloud Development Kit -->
<dependency>
<groupId>software.amazon.awscdk</groupId>
<artifactId>aws-cdk-lib</artifactId>
<version>${cdk.version}</version>
</dependency>

<dependency>
<groupId>software.constructs</groupId>
<artifactId>constructs</artifactId>
<version>${constructs.version}</version>
</dependency>
</dependencies>
</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package com.myorg;
mriccia marked this conversation as resolved.
Show resolved Hide resolved

import software.amazon.awscdk.App;
import software.amazon.awscdk.StackProps;

public class PowertoolsExamplesCloudformationCdkApp {
public static void main(final String[] args) {
App app = new App();

new PowertoolsExamplesCloudformationCdkStack(app, "PowertoolsExamplesCloudformationCdkStack", StackProps.builder()
.build());

app.synth();
}
}

Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
package com.myorg;

import software.amazon.awscdk.Stack;
import software.amazon.awscdk.*;
import software.amazon.awscdk.services.iam.Effect;
import software.amazon.awscdk.services.iam.PolicyStatement;
import software.amazon.awscdk.services.iam.PolicyStatementProps;
import software.amazon.awscdk.services.lambda.Code;
import software.amazon.awscdk.services.lambda.Function;
import software.amazon.awscdk.services.lambda.FunctionProps;
import software.amazon.awscdk.services.lambda.Runtime;
import software.amazon.awscdk.services.s3.assets.AssetOptions;
import software.constructs.Construct;

import java.io.Serializable;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


import static java.util.Collections.singletonList;
import static software.amazon.awscdk.BundlingOutput.NOT_ARCHIVED;

public class PowertoolsExamplesCloudformationCdkStack extends Stack {

public static final String SAMPLE_BUCKET_NAME = "sample-bucket-name-20230315-abc123";

public PowertoolsExamplesCloudformationCdkStack(final Construct scope, final String id) {
this(scope, id, null);
}

public PowertoolsExamplesCloudformationCdkStack(final Construct scope, final String id, final StackProps props) {
super(scope, id, props);


List<String> functionPackagingInstructions = Arrays.asList(
"/bin/sh",
scottgerring marked this conversation as resolved.
Show resolved Hide resolved
"-c",
"mvn clean install" +
"&& mkdir /asset-output/lib" +
"&& cp target/powertools-examples-cloudformation-*.jar /asset-output/lib"
);
BundlingOptions bundlingOptions = BundlingOptions.builder()
.command(functionPackagingInstructions)
.image(Runtime.JAVA_11.getBundlingImage())
.volumes(singletonList(
// Mount local .m2 repo to avoid download all the dependencies again inside the container
DockerVolume.builder()
.hostPath(System.getProperty("user.home") + "/.m2/")
.containerPath("/root/.m2/")
.build()
))
.user("root")
.outputType(NOT_ARCHIVED)
.build();

Function helloWorldFunction = new Function(this, "HelloWorldFunction", FunctionProps.builder()
.runtime(Runtime.JAVA_11)
.code(Code.fromAsset("../../", AssetOptions.builder().bundling(bundlingOptions)
.build()))
.handler("helloworld.App::handleRequest")
.memorySize(512)
.timeout(Duration.seconds(20))
.environment(Collections
.singletonMap("JAVA_TOOL_OPTIONS", "-XX:+TieredCompilation -XX:TieredStopAtLevel=1"))
.build());
helloWorldFunction.addToRolePolicy(new PolicyStatement(PolicyStatementProps.builder()
.effect(Effect.ALLOW)
.actions(Arrays.asList("s3:GetLifecycleConfiguration",
"s3:PutLifecycleConfiguration",
"s3:CreateBucket",
"s3:ListBucket",
"s3:DeleteBucket"))
.resources(singletonList("*")).build()));

String bucketName = (String) this.getNode().tryGetContext("BucketNameParam");

Map<String, Serializable> crProperties = new HashMap<>();
crProperties.put("BucketName", bucketName);
CustomResource.Builder
.create(this, "HelloWorldCustomResource")
.serviceToken(helloWorldFunction.getFunctionArn())
.properties(crProperties)
.build();

}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"RequestType": "Create",
"ResponseURL": "http://pre-signed-S3-url-for-response",
"StackId": "arn:aws:cloudformation:us-east-1:123456789012:stack/MyStack/guid",
"RequestId": "unique id for this create request",
"ResourceType": "Custom::TestResource",
"ResourceProperties": {
"BucketName": "test-bucket-20230307-1",
"RetentionDays" : 10,
"StackName": "MyStack"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"RequestType": "Delete",
"ResponseURL": "http://pre-signed-S3-url-for-response",
"StackId": "arn:aws:cloudformation:us-east-1:123456789012:stack/MyStack/guid",
"RequestId": "unique id for this create request",
"ResourceType": "Custom::TestResource",
"LogicalResourceId": "MyTestResource",
"PhysicalResourceId": "test-bucket-20230307-1",
"ResourceProperties": {
"BucketName": "test-bucket-20230307-1",
"RetentionDays" : 10,
"StackName": "MyStack"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"RequestType": "Update",
"ResponseURL": "http://pre-signed-S3-url-for-response",
"StackId": "arn:aws:cloudformation:us-east-1:123456789012:stack/MyStack/guid",
"RequestId": "unique id for this create request",
"ResourceType": "Custom::TestResource",
"LogicalResourceId": "MyTestResource",
"PhysicalResourceId": "test-bucket-20230307-1",
"ResourceProperties": {
"BucketName": "test-bucket-20230307-1",
"RetentionDays" : 100,
"StackName": "MyStack"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: >
powertools-examples-cloudformation

Sample SAM Template for powertools-examples-cloudformation

Globals:
Function:
Timeout: 20

Parameters:
BucketNameParam:
Type: String

Resources:
HelloWorldCustomResource:
Type: AWS::CloudFormation::CustomResource
Properties:
ServiceToken: !GetAtt HelloWorldFunction.Arn
BucketName: !Ref BucketNameParam

HelloWorldFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: ../../
Handler: helloworld.App::handleRequest
Runtime: java11
Architectures:
- x86_64
MemorySize: 512
Policies:
- Statement:
- Sid: bucketaccess1
Effect: Allow
Action:
- s3:GetLifecycleConfiguration
- s3:PutLifecycleConfiguration
- s3:CreateBucket
- s3:ListBucket
- s3:DeleteBucket
Resource: '*'
Environment:
Variables:
JAVA_TOOL_OPTIONS: -XX:+TieredCompilation -XX:TieredStopAtLevel=1

Outputs:
HelloWorldFunction:
Description: "Hello World Lambda Function ARN"
Value: !GetAtt HelloWorldFunction.Arn
Loading