0

This excellent question provides two methods for adding conditions to resources.

Add Conditions to Resources in CDK

However, an AwsCustomResource has neither an underlying CfnConstruct nor an addPropertyOverride() method.

How would one add a condition to an AwsCustomResource?

bravogolfgolf
  • 357
  • 2
  • 11
  • Do you need this because you're manually deploying the synthed templates? Why not use `if` and let `cdk deploy` deal with this for you? – kichik Aug 15 '21 at 23:36
  • I have a AwsCustomResource in a stack I only want to run when the stack is deployed under specific conditions. It could be as simple as different environment, for example dev & test, for discussion purposes. – bravogolfgolf Aug 17 '21 at 21:15
  • You can check that in your CDK code. For example you can set a context item named `stage` and change your deployment based on it. Then use `-c stage=prod` when deploying. – kichik Aug 18 '21 at 03:36
  • I ran into the same issue. Is there a workaround? – Stefan May 15 '23 at 10:31

1 Answers1

0

If you are using Typescript, this is possible. I assume it is possible for other languages as well if we use similar casting tricks.

In the CDK Github, we see that AwsCustomResource has an underlying CustomResource member: https://github.com/aws/aws-cdk/blob/d7e4b7a7009aa03a81902266313c521b12b12d25/packages/aws-cdk-lib/custom-resources/lib/aws-custom-resource/aws-custom-resource.ts#L397

We also see that CustomResource has an underlying CfnResource member: https://github.com/aws/aws-cdk/blob/d7e4b7a7009aa03a81902266313c521b12b12d25/packages/aws-cdk-lib/core/lib/custom-resource.ts#L126

CfnResource is the class that provides the cfnOptions member where you can set a resource's condition. Both AwsCustomResource.customResource and CustomResource.resource have private visibility, but we can circumvent this by casting the objects to any. When all is said and done:

(((myCustomResource as any).customResource as any).resource as CfnResource).cfnOptions.condition = myCondition;
victor
  • 1,573
  • 11
  • 23