Skip to content

Commit

Permalink
fix: Updated java/custom-resource to use non-deprecated software.amaz…
Browse files Browse the repository at this point in the history
…on.awscdk.CustomResource construct (#759)

* fix: Updated java/custom-resource to use non-deprecated software.amazon.awscdk.CustomResource construct

* fix: Addressed PR comments

* fix: added uuid generate call

* Fix: ECS FargateLB Test

---------

Co-authored-by: Michael Kaiser <[email protected]>
  • Loading branch information
its-mirus-lu and Michael Kaiser authored Oct 1, 2023
1 parent 0df2e2e commit 554dad4
Show file tree
Hide file tree
Showing 6 changed files with 188 additions and 119 deletions.
68 changes: 42 additions & 26 deletions java/custom-resource/lambda/custom-resource-handler.py
Original file line number Diff line number Diff line change
@@ -1,26 +1,42 @@
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)
def on_event(event, context):
print(event)
request_type = event['RequestType']
if request_type == 'Create': return on_create(event)
if request_type == 'Update': return on_update(event)
if request_type == 'Delete': return on_delete(event)
raise Exception("Invalid request type: %s" % request_type)

def on_create(event):
props = event["ResourceProperties"]
print("Create new resource with props %s" % props)

message = event['ResourceProperties']['Message']

attributes = {
'Response': 'Resource message "%s"' % message
}
return { 'Data': attributes }

def on_update(event):
physical_id = event["PhysicalResourceId"]
props = event["ResourceProperties"]
print("Update resource %s with props %s" % (physical_id, props))
# ...

return { 'PhysicalResourceId': physical_id }

def on_delete(event):
physical_id = event["PhysicalResourceId"]
print("Delete resource %s" % physical_id)
# ...

return { 'PhysicalResourceId': physical_id }

def is_complete(event, context):
physical_id = event["PhysicalResourceId"]
request_type = event["RequestType"]

# check if resource is stable based on request_type... fill in the blank below
# is_ready = ...

return { 'IsComplete': True }
Original file line number Diff line number Diff line change
@@ -1,12 +1,18 @@
package software.amazon.awscdk.examples;

import software.amazon.awscdk.App;
import java.util.HashMap;
import java.util.Map;

public class CustomResourceApp {

private static Map<String, Object> props = new HashMap<String, Object>();
public static void main(final String args[]) {
App app = new App();

new CustomResourceStack(app, "cdk-custom-resource-example2");
props.put("Message", "AWS CDK");

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

app.synth();
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,58 +1,37 @@
package software.amazon.awscdk.examples;

import java.nio.file.*;
import java.util.HashMap;

import java.util.Map;
import java.util.HashMap;

import software.constructs.Construct;
import software.amazon.awscdk.CfnOutput;
import software.amazon.awscdk.CustomResource;
import software.amazon.awscdk.CustomResourceProvider;
import software.amazon.awscdk.CustomResourceProviderProps;
import software.amazon.awscdk.CustomResourceProviderRuntime;
import software.amazon.awscdk.Duration;
import software.amazon.awscdk.Stack;
import software.amazon.awscdk.customresources.*;
import software.amazon.awscdk.CfnOutput;

public class CustomResourceStack extends Stack {
import software.amazon.awscdk.services.logs.*;
import software.amazon.awscdk.services.lambda.Runtime;
import software.amazon.awscdk.services.lambda.InlineCode;
import software.amazon.awscdk.services.lambda.SingletonFunction;

public CustomResourceStack(final Construct scope, final String id) {
public class CustomResourceStack extends Stack {
public String response = "";
public CustomResourceStack(final Construct scope, final String id, final Map<String, ? extends Object> props) {
super(scope, id);

try {
MyCustomResource resource = new MyCustomResource(this, "DemoResource", props);

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

String serviceToken = CustomResourceProvider.getOrCreate(this, "Custom::MyCustomResourceType", CustomResourceProviderProps.builder()
.codeDirectory("./lambda/custom-resource-handler.py")
.runtime(CustomResourceProviderRuntime.NODEJS_14_X)
.description("Lambda function created by the custom resource provider")
.build());

final CustomResource myCustomResource = CustomResource.Builder.create(this, "MyResource")
.resourceType("Custom::MyCustomResourceType")
.serviceToken(serviceToken)
.properties(map)
.build();

// Publish the custom resource output
CfnOutput.Builder.create(this, "MyCustomResourceOutput")
CfnOutput.Builder.create(this, "ResponseMessage")
.description("The message that came back from the Custom Resource")
.value(myCustomResource.getAtt("Response").toString())
.value((resource.response))
.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;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
package software.amazon.awscdk.examples;

import java.nio.file.*;

import java.util.Map;

import software.constructs.Construct;
import software.amazon.awscdk.CustomResource;
import software.amazon.awscdk.Duration;
import java.util.UUID;
import software.amazon.awscdk.customresources.*;

import software.amazon.awscdk.services.logs.*;
import software.amazon.awscdk.services.lambda.Runtime;
import software.amazon.awscdk.services.lambda.InlineCode;
import software.amazon.awscdk.services.lambda.SingletonFunction;

public class MyCustomResource extends Construct {
public String response = "";
public MyCustomResource(final Construct scope, final String id, final Map<String, ? extends Object> props) {
super(scope, id);


try {

final SingletonFunction onEvent = SingletonFunction.Builder.create(this, "Singleton")
.code(InlineCode.fromAsset("lambda"))
.handler("custom-resource-handler.on_event")
.runtime(Runtime.PYTHON_3_8)
.uuid(UUID.randomUUID().toString())
.timeout(Duration.minutes(1))
.build();

final Provider myProvider = Provider.Builder.create(this, "MyProvider")
.onEventHandler(onEvent)
.logRetention(RetentionDays.ONE_DAY)
.build();

final CustomResource resource = CustomResource.Builder.create(this, "Resource1")
.serviceToken(myProvider.getServiceToken())
.properties(props)
.build();

response = resource.getAtt("Response").toString();

} catch (Exception e) {
e.printStackTrace();
}
}
// function to read the file content
public static String readFileAsString(String fileName) throws Exception {
try {
return new String(Files.readAllBytes(Paths.get(fileName)), "UTF-8");
} catch (Exception e) {
e.printStackTrace();
throw e;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ public class ECSFargateLoadBalancedApp {
public static void main(final String argv[]) {
App app = new App();

new ECSFargateLoadBalancedStack(app, "fargate-load-balanced-service");
new ECSFargateLoadBalancedStack(app, "test");

// required until https://github.com/aws/jsii/issues/456 is resolved
app.synth();
Expand Down
Loading

0 comments on commit 554dad4

Please sign in to comment.