Joe Davidson

aws-cdk-go: Sharing Resources Between Stacks

gocdkaws

A quick guide on sharing a resource between stacks in a multiple-stack CDK app.

Introduction #

A colleague was trying to navigate the aws-cdk-go docs [1], trying to create multiple stacks in one app and share resources between them. Since the docs are generated and not really Go specific, it's not very obvious as to how this would be done.

Exporting A Resource #

To export a resource from a stack we must create a custom stack type where the resources can be set. In this example I plan on exporting a bucket:

type myStack struct {
awscdk.Stack
Bucket awss3.Bucket
}

Then, a function to create this stack can be made to return a *myStack:

func SharedStack(scope constructs.Construct, id string) *myStack {
stack := &myStack{Stack: awscdk.NewStack(scope, &id, &awscdk.StackProps{})}

stack.Bucket = awss3.NewBucket(stack.Stack, jsii.String("mybucket"), &awss3.BucketProps{
BucketName: jsii.String("mybucket"),
})

return stack
}

When creating this stack CDK will automatically identify any values that are used from the Bucket interface, and automatically export them.

Importing A Resource #

Now we can create this stack in the scope of a CDK app, then import it into another stack:

func main() {
app := awscdk.NewApp(nil)

shared := SharedStack(app, "SharedStack")

stack := awscdk.NewStack(app, jsii.String("OtherStack"), &awscdk.StackProps{})

r := awsiam.NewRole(stack, jsii.String("someRole"), &awsiam.RoleProps{
AssumedBy: awsiam.NewServicePrincipal(jsii.String("sns.amazonaws.com"), &awsiam.ServicePrincipalOpts{}),
})

shared.Bucket.GrantReadWrite(r, nil)

app.Synth(nil)
}

This will create 2 stacks: SharedStack and OtherStack. SharedStack will create a new bucket and a CFN Export for the buckets ARN, CDK knows to do this as the ARN is used in GrantReadWrite.

TLDR #

I've created a gist for the example [2].