What is the purpose of the app.synth() line in AWS CDK applications? For example it can be seen here on line 29:
https://github.com/aws-samples/aws-cdk-examples/blob/master/typescript/ecs/fargate-application-load-balanced-service/index.ts
I have looked at the CDK docs but I cannot find what the actual purpose of that function is. As I understand it, the app is automatically synthesized upon cdk deploy or cdk synth. I also took the example shown in repo linked above, commented out the app.synth() line, deployed it, and it seemed to work as expected. Therefore I'm wondering if I'm missing something when it comes to the purpose of app.synth()
I know it's been a while since this question was asked, but I was curious and looked into it myself, so I'll share it with you.
(I also thought that the current accepted answer was about the CDK CLI and not about the CDK application code.)
The App class has an option called autoSynth which is set to true by default, so even if you omit app.synth() in your code, it will be executed automatically.
https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.AppProps.html#autosynth
As mentioned in the documentation, this feature may not work in some languages, so it seems to be explicitly specified in many sample codes.
According to the documentation, it is OK to run app.synth() multiple times.
https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.App.html#synthoptions
autoSynth works fine on Node.js.
It is implemented in Node.js using process.once("beforeExit", listener).
https://github.com/aws/aws-cdk/blob/v2.51.1/packages/@aws-cdk/core/lib/app.ts#L166-L170
I started this investigation because when I ran CDK in Deno, I had to explicitly run app.synth() to generate the CDK assembly. As a result of this investigation, I found out that this is because the Node compatibility layer in Deno does not currently support "beforeExit" events.
https://github.com/denoland/deno_std/blob/113435ada1948b90188586f022d55745c6d2d19b/node/process.ts#L51-L52
As per this experience, it is better to explicitly call app.synth() as recommended.
cdk synth only constructs your CloudFormation template. It does not deploy (create actual resources) it to AWS. You can take the template constructed, deploy it manually in CFN console, edit or inspect.
cdk deploy is going to construct the template and deploy it to AWS as well.
People use synth with deploy because it is a good practice:
It is optional (though good practice) to synthesize before deploying. The AWS CDK synthesizes your stack before each deployment.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With