Search code examples
amazon-web-servicesaws-cloudformationaws-cdkamazon-kms

AWS-CDK: Passing cross-stack references props between multi region (cross-region) stacks in AWS- CDK


I have to deploy one stack, let's call it the parent stack in one region Them a second stack(child) needs to be deployed, in another region. The region of the second stack(child stack) can not include the region where the parent was deployed. The second stack can be deployed in multiple regions.

However, the second stack needs props from the first stack. Specifically, it needs an ARN value. The default region is us-east-1. That is where the parent stack will get deployed.

To solve this I attempted the following

1- First Attempt : Using cfnOutput

  • Created a cfnOutput in the parent and in the child I capture the value with cdk.Fn.ImportValue()
  • RESULT: Got an error as cfnOutput can not be used between stacks on different regions as explained in CloudFormation User Guide

2- Second Attempt: Using StackProps

  • Created an interface in the parent stack that inherit from StackProps, set a public property and put the ARN value there

from the lib/mystack file

export interface myStackProps extends cdk.StackProps {
 principalKeyArn: string
}
  • Passed the value to the second stack as props along with the env key containing the region as under:

from the bin/myapp file

const app = new cdk.App();
const regions = ["us-east-2"]

const primaryMRKey = new KmsMultiregionPrincipalKey(app, 'KmsMultiregionKeyStack')

for (let region of regions){
 const envToDeploy = {region: region, account: "123456789123"}
 new  KmsReplicaKey(app, 'KmsReplicaKey-' + region, {env: envToDeploy, principalKeyArn: primaryMRKey.principalKeyArn  } )

}

RESULT: Cross stack references are only supported for stacks deployed to the same environment or between nested stacks and their parent stack

Question:

  • How to resolve the issue of passing cross-stack references between stacks that are using different regions in CDK?

[Edited] one solution to this problem is using SSM as explained below.

Thanks in advance


Solution

  • CDK now has an override to allow cross-region references between stacks in the same app.

    Set the parameter crossRegionReferences to true in both stacks.

    For example stack 1 with a global CloudFront WAF:

    new WafStack(app, 'waf', {
      env: { region: 'us-east-1'},
      crossRegionReferences: true // <-- Enable cross region references
    })
    

    Do the same for the other stacks.

    There is an example in this issue: https://github.com/aws/aws-cdk/issues/22820