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

CustomeResource error resource.getAtt('Response') #671

Closed
entest-hai opened this issue May 8, 2022 · 3 comments · Fixed by #1020
Closed

CustomeResource error resource.getAtt('Response') #671

entest-hai opened this issue May 8, 2022 · 3 comments · Fixed by #1020
Labels
bug This issue is a bug. effort/small Small work item – less than a day of effort good first issue Related to contributions. See CONTRIBUTING.md p1

Comments

@entest-hai
Copy link

Describe the bug

I follow this example to create a custom resource. However, there is error due to these lines

    // custom resource
    const resource = new CustomResource(this, "Resource", {
      serviceToken: provider.serviceToken,
      properties: props,
    });

    // 
    this.response = resource.getAtt('Response').toString(); 

Got error

Received response status [FAILED] from custom resource. Message returned: See the details in CloudWatch Log Stream: 2022/05/08/[$LATEST]293aa907cb9443eba850d678af331cbe (RequestId: 1a5830d9-8e5e-46d9-873e-51e6f7fe9147)

Expected Behavior

Should be no error

Current Behavior

Create Failed

Reproduction Steps

custom-resource-handler.py

def main(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': 'You said "%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)

custom-resource-stack.ts

import {
  aws_lambda,
  CfnOutput,
  CustomResource,
  custom_resources,
  Duration,
  Stack,
  StackProps,
} from "aws-cdk-lib";
import { Construct } from "constructs";
import * as path from "path";
import * as fs from "fs";

export interface CustomResourceStackProps {
  message: string; 
}

export class CustomResourceStack extends Construct {

  public readonly response: string; 

  constructor(scope: Construct, id: string, props: CustomResourceStackProps) {
    super(scope, id);

    // lambda
    const fn = new aws_lambda.SingletonFunction(this, "Singleton", {
      uuid: "f7d4f730-4ee1-11e8-9c2d-fa7ae01bbebc",
      code: new aws_lambda.InlineCode(
        fs.readFileSync(path.join(__dirname, "custom-resource-handler.py"), {
          encoding: "utf-8",
        })
      ),
      handler: "index.main",
      timeout: Duration.seconds(300),
      runtime: aws_lambda.Runtime.PYTHON_3_7,
    });

    // provider
    const provider = new custom_resources.Provider(this, "Provider", {
      onEventHandler: fn,
    });

    // custom resource
    const resource = new CustomResource(this, "Resource", {
      serviceToken: provider.serviceToken,
      properties: props,
    });

    // get attribute 
    this.response = resource.getAtt('Response').toString(); 


  }
}

index.ts

#!/usr/bin/env node
import 'source-map-support/register';
import * as cdk from 'aws-cdk-lib';
import { CustomResourceStack } from '../lib/custom-resource-stack';
import { CfnOutput } from 'aws-cdk-lib';

const app = new cdk.App();

class MyStack extends cdk.Stack {
  constructor(scope: cdk.App, id: string, props?: cdk.StackProps) {
    super(scope, id, props);

    const resource = new CustomResourceStack(
      this,
      'CustomResourceDemoStack',
      {
        message: 'Create a custom resource'
      }
    )

    // publish the custom resource output 
    new CfnOutput(
      this, 
      'ResponseMessage',
      {
        description: 'the message that came back from the Custom Resource',
        value: resource.response
      }
    )

  }
}

new MyStack(app, 'CustomResrouceStackDemo');

package.json

{
  "name": "custom-resource",
  "version": "0.1.0",
  "bin": {
    "custom-resource": "bin/custom-resource.js"
  },
  "scripts": {
    "build": "tsc",
    "watch": "tsc -w",
    "test": "jest",
    "cdk": "cdk"
  },
  "devDependencies": {
    "@types/jest": "^27.4.1",
    "@types/node": "10.17.27",
    "jest": "^27.5.1",
    "ts-jest": "^27.1.4",
    "aws-cdk": "2.23.0",
    "ts-node": "^10.7.0",
    "typescript": "~3.9.7"
  },
  "dependencies": {
    "aws-cdk-lib": "2.23.0",
    "constructs": "^10.0.0",
    "source-map-support": "^0.5.21"
  }
}

Possible Solution

No response

Additional Information/Context

No response

CDK CLI Version

2.23

Framework Version

No response

Node.js Version

v16.15.0

OS

Amazon Linux 2

Language

Typescript

Language Version

3.9.7

@entest-hai entest-hai added bug This issue is a bug. needs-triage This issue or PR still needs to be triaged. labels May 8, 2022
@peterwoodworth
Copy link
Contributor

You're right, I'm able to reproduce this. Thanks for letting us know, we'll get it fixed up soon!

@peterwoodworth peterwoodworth added effort/small Small work item – less than a day of effort p1 and removed needs-triage This issue or PR still needs to be triaged. labels May 25, 2022
@peterwoodworth peterwoodworth self-assigned this May 25, 2022
@peterwoodworth peterwoodworth removed their assignment Sep 3, 2022
@peterwoodworth peterwoodworth added the good first issue Related to contributions. See CONTRIBUTING.md label Sep 3, 2022
@balx
Copy link
Contributor

balx commented Mar 29, 2024

Instead of using cfnresponse, return { 'Data': attributes } should fix the issue.

def main(event, context):
    import logging as log
    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': 'You said "%s"' % message
        }

        return { 'Data': attributes }
    except Exception as e:
        log.exception(e)
        return { 'Data': {} }

Copy link

⚠️COMMENT VISIBILITY WARNING⚠️

Comments on closed issues are hard for our team to see.
If you need more assistance, please either tag a team member or open a new issue that references this one.
If you wish to keep having a conversation with other community members under this issue feel free to do so.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug This issue is a bug. effort/small Small work item – less than a day of effort good first issue Related to contributions. See CONTRIBUTING.md p1
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants