Skip to content
v2.274.0

CustomResource L2 construct ​

Instantiation of a custom resource, whose implementation is provided a Provider.

This class is intended to be used by construct library authors. Application builder should not be able to tell whether or not a construct is backed by a custom resource, and so the use of this class should be invisible.

Instead, construct library authors declare a custom construct that hides the choice of provider, and accepts a strongly-typed properties object with the properties your provider accepts.

Your custom resource provider (identified by the serviceToken property) can be one of 4 constructs:

  • If you are authoring a construct library or application, we recommend you use the Provider class in the custom-resources module.
  • If you are authoring a construct for the CDK's AWS Construct Library, you should use the CustomResourceProvider construct in this package.
  • If you want full control over the provider, you can always directly use a Lambda Function or SNS Topic by passing the ARN into serviceToken.

Example ​

ts
const stack = new Stack();
const durToken = new CfnParameter(stack, 'MyParameter', {
  type: 'Number',
  default: 60,
});
new CustomResource(stack, 'MyCustomResource', {
  serviceToken: 'MyServiceToken',
  serviceTimeout: Duration.seconds(durToken.valueAsNumber),
});
python
stack = Stack()
dur_token = CfnParameter(stack, "MyParameter",
    type="Number",
    default=60
)
CustomResource(stack, "MyCustomResource",
    service_token="MyServiceToken",
    service_timeout=Duration.seconds(dur_token.value_as_number)
)
java
Stack stack = new Stack();
CfnParameter durToken = CfnParameter.Builder.create(stack, "MyParameter")
        .type("Number")
        .default(60)
        .build();
CustomResource.Builder.create(stack, "MyCustomResource")
        .serviceToken("MyServiceToken")
        .serviceTimeout(Duration.seconds(durToken.getValueAsNumber()))
        .build();
csharp
// Install: dotnet add package Amazon.CDK.Lib
var stack = new Stack();
var durToken = new CfnParameter(stack, "MyParameter", new CfnParameterProps {
    Type = "Number",
    Default = 60
});
new CustomResource(stack, "MyCustomResource", new CustomResourceProps {
    ServiceToken = "MyServiceToken",
    ServiceTimeout = Duration.Seconds(durToken.ValueAsNumber)
});
go
// Install: go get github.com/aws/aws-cdk-go/awscdk/v2
stack := awscdk.Newstack()
durToken := awscdk.NewCfnParameter(stack, jsii.String("MyParameter"), &CfnParameterProps{
	Type: jsii.String("Number"),
	Default: jsii.Number(60),
})
awscdk.NewCustomResource(stack, jsii.String("MyCustomResource"), &CustomResourceProps{
	ServiceToken: jsii.String("MyServiceToken"),
	ServiceTimeout: awscdk.Duration_Seconds(durToken.valueAsNumber),
})

Initializer ​

ts
new CustomResource(scope: Construct, id: string, props: CustomResourceProps)
python
CustomResource(scope: Construct, id: str, props: CustomResourceProps)
java
new CustomResource(Construct scope, String id, CustomResourceProps props)
csharp
new CustomResource(Construct scope, string id, CustomResourceProps props)
go
NewCustomResource(Scope Construct, Id *string, Props CustomResourceProps)

Construct Props ​

pascalCasePropertiesbooleanpascal_case_propertiesboolpascalCasePropertiesBooleanPascalCasePropertiesboolPascalCaseProperties*bool= false#
Convert all property keys to pascal case.
properties{ [key: string]: any }propertiestyping.Mapping[str, Any]propertiesMap<String, Object>PropertiesIDictionary<string, object>Properties*map[string]interface{}= No properties.#
Properties to pass to the Lambda.

Values in this properties dictionary can possibly overwrite other values in CustomResourceProps E.g. ServiceToken and ServiceTimeout It is recommended to avoid using same keys that exist in CustomResourceProps

removalPolicyRemovalPolicyremoval_policyRemovalPolicyremovalPolicyRemovalPolicyRemovalPolicyRemovalPolicyRemovalPolicyRemovalPolicy= cdk.RemovalPolicy.Destroy#
The policy to apply when this resource is removed from the application.
resourceTypestringresource_typestrresourceTypeStringResourceTypestringResourceType*string= AWS::CloudFormation::CustomResou…#
For custom resources, you can specify AWS::CloudFormation::CustomResource (the default) as the resource type, or you can specify your own resource type name.
notes · default

For example, you can use "Custom::MyCustomResourceTypeName".

Custom resource type names must begin with "Custom::" and can include alphanumeric characters and the following characters: _@-. You can specify a custom resource type name up to a maximum length of 60 characters. You cannot change the type during an update.

Using your own resource type names helps you quickly differentiate the types of custom resources in your stack. For example, if you had two custom resources that conduct two different ping tests, you could name their type as Custom::PingTester to make them easily identifiable as ping testers (instead of using AWS::CloudFormation::CustomResource).

Default: AWS::CloudFormation::CustomResource

serviceTimeoutDurationservice_timeoutDurationserviceTimeoutDurationServiceTimeoutDurationServiceTimeoutDuration= Duration.seconds(3600)#
The maximum time that can elapse before a custom resource operation times out.
notes · example

The value must be between 1 second and 3600 seconds.

Maps to ServiceTimeout property for the AWS::CloudFormation::CustomResource resource

A token can be specified for this property, but it must be specified with Duration.seconds().

ts
const stack = new Stack();
const durToken = new CfnParameter(stack, 'MyParameter', {
  type: 'Number',
  default: 60,
});
new CustomResource(stack, 'MyCustomResource', {
  serviceToken: 'MyServiceToken',
  serviceTimeout: Duration.seconds(durToken.valueAsNumber),
});
serviceTokenstringservice_tokenstrserviceTokenStringServiceTokenstringServiceToken*stringrequired#
The ARN of the provider which implements this custom resource type.
notes

You can implement a provider by listening to raw AWS CloudFormation events and specify the ARN of an SNS topic (topic.topicArn) or the ARN of an AWS Lambda function (lambda.functionArn) or use the CDK's custom resource provider framework which makes it easier to implement robust providers.

Provider framework:

ts
// use the provider framework from aws-cdk/custom-resources:
const provider = new customresources.Provider(this, 'ResourceProvider', {
  onEventHandler,
  isCompleteHandler, // optional
});

new CustomResource(this, 'MyResource', {
  serviceToken: provider.serviceToken,
});

AWS Lambda function (not recommended to use AWS Lambda Functions directly, see the module README):

ts
// invoke an AWS Lambda function when a lifecycle event occurs:
new CustomResource(this, 'MyResource', {
  serviceToken: myFunction.functionArn,
});

SNS topic (not recommended to use AWS Lambda Functions directly, see the module README):

ts
// publish lifecycle events to an SNS topic:
new CustomResource(this, 'MyResource', {
  serviceToken: myTopic.topicArn,
});

Maps to ServiceToken property for the AWS::CloudFormation::CustomResource resource

Properties ​

The environment this resource belongs to.
notes

For resources that are created and managed in a Stack (those created by creating new class instances like new Role(), new Bucket(), etc.), this is always the same as the environment of the stack they belong to.

For referenced resources (those obtained from referencing methods like Role.fromRoleArn(), Bucket.fromBucketName(), etc.), they might be different than the stack they were imported into.

nodeNodenodeNodenodeNodeNodeNodeNodeNoderequired#
The tree node.
PROPERTY_INJECTION_IDstringproperty_injection_idstrPROPERTY_INJECTION_IDStringPROPERTY_INJECTION_IDstringPROPERTY_INJECTION_ID*stringrequiredstatic#
Uniquely identifies this class.
refstringrefstrrefStringRefstringRef*stringrequired#
The physical name of this custom resource.
stackStackstackStackstackStackStackStackStackStackrequired#
The stack in which this resource is defined.

Methods ​

applyCrossStackReferenceStrength(strength: ReferenceStrength): voiddef apply_cross_stack_reference_strength(self, strength: ReferenceStrength) -> Nonepublic void applyCrossStackReferenceStrength(ReferenceStrength strength)public void ApplyCrossStackReferenceStrength(ReferenceStrength strength)func ApplyCrossStackReferenceStrength(Strength ReferenceStrength)#
Override the cross-stack reference strength for this resource.
notes · 1 parameter

When set, any cross-stack reference to this resource will use the specified mechanism instead of the global default determined by the @aws-cdk/core:defaultCrossStackReferences context key. This is useful for selectively weakening specific references to avoid the "deadly embrace" problem without changing the app-wide default.

Parameters

  • strengthstrengthstrengthstrengthStrength — - The reference strength to use for this resource.
applyRemovalPolicy(policy: RemovalPolicy): voiddef apply_removal_policy(self, policy: RemovalPolicy) -> Nonepublic void applyRemovalPolicy(RemovalPolicy policy)public void ApplyRemovalPolicy(RemovalPolicy policy)func ApplyRemovalPolicy(Policy RemovalPolicy)#
Apply the given removal policy to this resource.
notes

The Removal Policy controls what happens to this resource when it stops being managed by CloudFormation, either because you've removed it from the CDK application or because you've made a change that requires the resource to be replaced.

The resource can be deleted (RemovalPolicy.DESTROY), or left in your AWS account for data recovery and cleanup later (RemovalPolicy.RETAIN).

getAtt(attributeName: string): Referencedef get_att(self, attribute_name: str) -> Referencepublic Reference getAtt(String attributeName)public Reference GetAtt(string attributeName)func GetAtt(AttributeName *string) Reference#
Returns the value of an attribute of the custom resource of an arbitrary type.

Attributes are returned from the custom resource provider through the Data map where the key is the attribute name.

1 parameter · returns

Parameters

  • attributeNameattribute_nameattributeNameattributeNameAttributeName — the name of the attribute.

Returns: a token for Fn::GetAtt. Use Token.asXxx to encode the returned Reference as a specific type or use the convenience getAttString for string attributes.

getAttString(attributeName: string): stringdef get_att_string(self, attribute_name: str) -> strpublic String getAttString(String attributeName)public string GetAttString(string attributeName)func GetAttString(AttributeName *string) *string#
Returns the value of an attribute of the custom resource of type string.

Attributes are returned from the custom resource provider through the Data map where the key is the attribute name.

1 parameter · returns

Parameters

  • attributeNameattribute_nameattributeNameattributeNameAttributeName — the name of the attribute.

Returns: a token for Fn::GetAtt encoded as a string.

isConstruct(x: any): boolean@staticmethod def is_construct(x: Any) -> boolpublic static Boolean isConstruct(Object x)public static bool IsConstruct(object x)func IsConstruct(X interface{}) *boolstatic#
Checks if `x` is a construct.
notes · 1 parameter · returns

Use this method instead of instanceof to properly detect Construct instances, even when the construct library is symlinked.

Explanation: in JavaScript, multiple copies of the constructs library on disk are seen as independent, completely different libraries. As a consequence, the class Construct in each copy of the constructs library is seen as a different class, and an instance of one class will not test as instanceof the other class. npm install will not create installations like this, but users may manually symlink construct libraries together or use a monorepo tool: in those cases, multiple copies of the constructs library can be accidentally installed, and instanceof will behave unpredictably. It is safest to avoid using instanceof, and using this type-testing method instead.

Parameters

  • xxxxX — Any object.

Returns: true if x is an object created from a class which extends Construct.

isOwnedResource(construct: IConstruct): boolean@staticmethod def is_owned_resource(construct: IConstruct) -> boolpublic static Boolean isOwnedResource(IConstruct construct)public static bool IsOwnedResource(IConstruct construct)func IsOwnedResource(Construct IConstruct) *boolstatic#
Returns true if the construct was created by CDK, and false otherwise.
isResource(construct: IConstruct): boolean@staticmethod def is_resource(construct: IConstruct) -> boolpublic static Boolean isResource(IConstruct construct)public static bool IsResource(IConstruct construct)func IsResource(Construct IConstruct) *boolstatic#
Check whether the given construct is a Resource.
toString(): stringdef to_string(self, ) -> strpublic String toString()public string ToString()func ToString() *string#
Returns a string representation of this construct.
with(...mixins: IMixin[]): IConstructdef with(self, mixins: IMixin) -> IConstructpublic IConstruct with(IMixin mixins)public IConstruct With(IMixin mixins)func With(Mixins IMixin) IConstruct#
Applies one or more mixins to this construct.

Mixins are applied in order. The list of constructs is captured at the start of the call, so constructs added by a mixin will not be visited. Use multiple with() calls if subsequent mixins should apply to added constructs.