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

feat: custom resource example for Java #171

Merged
merged 3 commits into from
Dec 7, 2019
Merged
Show file tree
Hide file tree
Changes from 6 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
13 changes: 13 additions & 0 deletions java/custom-resource/.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

44 changes: 44 additions & 0 deletions java/custom-resource/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
# Custom Resource
<!--BEGIN STABILITY BANNER-->
---

![Stability: Stable](https://img.shields.io/badge/stability-Stable-success.svg?style=for-the-badge)

> **This is a stable example. It should successfully build out of the box**
>
> This examples only on the core CDK library, and does not have any infrastructure prerequisites to build.

---
<!--END STABILITY BANNER-->

This example shows adding a custom resource to a CDK app in Java. This custom resource is useful when considering design of constructs, or separating your architecture into components.


## Building

To build this app, run `mvn compile`. This will download the required
dependencies to compile the Java code.

You can use your IDE to write code and unit tests, but you will need to use the
CDK toolkit if you wish to synthesize/deploy stacks.

## CDK Toolkit

The [`cdk.json`](./cdk.json) file in the root of this repository includes
instructions for the CDK toolkit on how to execute this program.

Specifically, it will tell the toolkit to use the `mvn exec:java` command as the
entry point of your application. After changing your Java code, you will be able
to run the CDK toolkit commands as usual (Maven will recompile as needed):

$ cdk ls
<list all stacks in this program>

$ cdk synth
<cloudformation template>

$ cdk deploy
<deploy stack to your account>

$ cdk diff
<diff against deployed stack>
4 changes: 4 additions & 0 deletions java/custom-resource/cdk.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"app": "mvn exec:java -Dexec.mainClass=software.amazon.awscdk.examples.CustomResourceApp"

}
26 changes: 26 additions & 0 deletions java/custom-resource/lambda/custom-resource-handler.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
def handler(event, context):
import logging as log
import cfnresponse
log.getLogger().setLevel(log.INFO)

# This needs to change if there are to be multiple resources in the same stack
physical_id = 'TheOnlyCustomResource'

try:
log.info('Input event: %s', event)

# Check if this is a Create and we're failing Creates
if event['RequestType'] == 'Create' and event['ResourceProperties'].get('FailCreate', False):
raise RuntimeError('Create failure requested')

# Do the thing
message = event['ResourceProperties']['Message']
attributes = {
'Response': 'Hello "%s"' % message
}

cfnresponse.send(event, context, cfnresponse.SUCCESS, attributes, physical_id)
except Exception as e:
log.exception(e)
# cfnresponse's error message is always "see CloudWatch"
cfnresponse.send(event, context, cfnresponse.FAILED, {}, physical_id)
81 changes: 81 additions & 0 deletions java/custom-resource/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
<?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.amazonaws.cdk</groupId>
<artifactId>custom-resource</artifactId>
<version>1.0.0</version>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>

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

<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<version>3.1.0</version>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
<archive>
<manifest>
<mainClass>com.amazonaws.cdk.examples.CustomResourceApp</mainClass>
</manifest>
</archive>
</configuration>
<executions>
<execution>
<id>make-assembly</id> <!-- this is used for inheritance merges -->
<phase>package</phase> <!-- bind to the packaging phase -->
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>

<dependencies>
<!-- AWS Cloud Development Kit -->
<dependency>
<groupId>software.amazon.awscdk</groupId>
<artifactId>core</artifactId>
<version>1.18.0</version>
</dependency>

<!-- Respective AWS Construct Libraries -->
<dependency>
<groupId>software.amazon.awscdk</groupId>
<artifactId>cloudformation</artifactId>
<version>1.18.0</version>
</dependency>
<dependency>
<groupId>software.amazon.awscdk</groupId>
<artifactId>lambda</artifactId>
<version>1.18.0</version>
</dependency>

<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package software.amazon.awscdk.examples;

import software.amazon.awscdk.core.App;

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

new CustomResourceStack(app, "cdk-custom-resource-example2");

app.synth();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
package software.amazon.awscdk.examples;

import software.amazon.awscdk.core.CfnOutput;
import software.amazon.awscdk.core.Construct;
import software.amazon.awscdk.core.Duration;
import software.amazon.awscdk.core.Stack;
import software.amazon.awscdk.services.cloudformation.*;
import software.amazon.awscdk.services.lambda.*;
import software.amazon.awscdk.services.lambda.Runtime;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.nio.file.*;

public class CustomResourceStack extends Stack {

public CustomResourceStack(final Construct scope, final String id) {
super(scope, id);

try {

// Get the lambda function code
String LambdaContent = readFileAsString("./lambda/custom-resource-handler.py");

// Sample Lambda Function Resource
final SingletonFunction lambdaFunction = SingletonFunction.Builder.create(this, "cdk-lambda-customresource")
.description("My Custom Resource Lambda")
.code(Code.fromInline(LambdaContent))
.handler("index.handler")
.timeout(Duration.seconds(300))
.runtime(Runtime.PYTHON_2_7)
.uuid(UUID.randomUUID().toString())
.build();

// Sample Property to send to Lambda Function
Map<String, Object> map = new HashMap<String, Object>();
map.put("Message", "AWS CDK");

final CustomResource myCustomResource = CustomResource.Builder.create(this, "MyCustomResource")
.provider(CustomResourceProvider.fromLambda(lambdaFunction))
.properties(map).build();


// Publish the custom resource output
CfnOutput cfnoutput = CfnOutput.Builder.create(this, "MyCustomResourceOutput")
.description("The message that came back from the Custom Resource")
.value(myCustomResource.getAtt("Response").toString()).build();


} catch (Exception e) {
e.printStackTrace();
}

}
// function to read the file content
public static String readFileAsString(String fileName) throws Exception
{
String data = "";
try
{
data = new String(Files.readAllBytes(Paths.get(fileName)),"UTF-8");
}
catch (Exception e)
{
e.printStackTrace();
}
return data;
}
}