AWS CDK turns infrastructure code into CloudFormation templates. These sections explain its construct model, synthesis checks, bootstrap roles and deployment workflows.
Apps, stacks, and constructs
AWS CDK defines infrastructure in a programming language and turns it into CloudFormation templates. A constructA reusable code component that describes one or more CloudFormation resources and their configuration. is a reusable component that describes resources; a stackA group of resource definitions that CDK maps to a CloudFormation stack. groups constructs into a CloudFormation deployment.
How it works
- Create an app, the root that contains your stacks.
- Add stacks and define resources inside them with constructs.
- Choose the construct level that exposes the control you need. Compose your own constructs when several apps need the same pattern.
- Run
cdk synthto produce the deployment files,cdk diffto inspect changes, andcdk deployto deploy through CloudFormation.
| Level | What it provides | Example |
|---|---|---|
| L1 | Direct CloudFormation resource properties | CfnBucket |
| L2 | Resource defaults and helper methods | s3.Bucket |
| L3 | Several resources configured as a pattern | ApplicationLoadBalancedFargateService |
Exam cues
- If the question says several teams need the same infrastructure pattern, think a shared construct library, because constructs can be composed and distributed.
- If the question says a resource needs explicit CloudFormation properties, think L1, because it maps directly to that resource.
Remember
- An app contains stacks; stacks contain constructs.
- L1 names start with
Cfn. L2 adds defaults and helpers. L3 combines resources.
Trap: CDK code produces CloudFormation templates. Choosing a higher construct level still leads to a CloudFormation deployment.
Da documentação da AWS (14)
- AWS CDK defines infrastructure in programming languages and synthesizes CloudFormation templates.
- A CDK app contains stacks.
- A CDK stack represents a CloudFormation stack and contains resource constructs.
- A construct is a reusable component representing one or more CloudFormation resources and their configuration.
- Each L1 construct maps to a single CloudFormation resource.
- L1 construct names start with Cfn, such as CfnBucket.
- L2 constructs provide resource defaults and helper methods for permissions and resource interactions.
- s3.Bucket is an L2 construct.
- L3 patterns compose resources for a use case.
- ApplicationLoadBalancedFargateService combines a Fargate service and an application load balancer.
- Teams can define their own constructs, compose them from other constructs and distribute them for reuse.
- cdk synth produces a cloud assembly.
- cdk diff compares infrastructure changes.
- cdk deploy deploys stacks.
Synthesis and deployment
SynthesisRunning a CDK app to produce CloudFormation templates and deployment artifacts. turns a CDK app into deployment files called a cloud assemblyThe set of templates and other artifacts produced by CDK synthesis for deployment.. Deployment uploads the assetsA local file or container image packaged and published for use by deployed infrastructure., such as function packages or container images, and asks CloudFormation to create or update resources.
How it works
- ConstructA reusable code component that describes one or more CloudFormation resources and their configuration. the app and its resource tree.
- Prepare constructs, apply AspectsAn operation CDK applies to constructs in a scope during synthesis. (operations across that tree), and validate the result.
- Synthesize CloudFormation templates and assets into
cdk.outby default. - Publish file and image assets with their bootstrapProvisioning storage and roles needed for CDK deployment in an AWS account and Region. publishing roles. Submit the template with the deployment roleAn identity that a user, application or service assumes to obtain a set of permissions.; CloudFormation provisions resources with its execution role.
A change setA proposed CloudFormation update that can be prepared for review before execution. is a proposed CloudFormation update that can be reviewed before execution.
| Deployment method | Effect |
|---|---|
change-set |
Create and execute a change set; default |
prepare-change-set |
Create the change set for review |
execute-change-set |
Execute a prepared change set |
direct |
Apply the update without creating a change set |
Exam cues
- If the question says external tooling must review a proposed stackA group of resource definitions that CDK maps to a CloudFormation stack. update, think
prepare-change-setfollowed byexecute-change-set, because preparation does not execute the update. - If the question says a health alarm should undo a deployment, think rollback trigger alarms, because CloudFormation monitors them during deployment and the configured monitoring period.
- If the question says code must react during resource creation, think a custom resourceA resource definition that lets CloudFormation run custom logic during deployment., because the CDK app has already exited.
Remember
--require-approvalacceptsany-change,broadeningandnever; defaultbroadening.- Rollback triggers accept up to 5 metric alarms.
- Post-deployment monitoring is 0 to 180 whole minutes; default 0 monitors only during deployment.
Trap: Template generation and resource creation happen at different times. A CDK constructor cannot wait for a resource that CloudFormation has not deployed yet.
Synthesis constructs the app, applies Aspects, validates constructs and writes a cloud assembly.
File and image publishing roles upload assets to the bootstrap S3 bucket and ECR repository.
The deployment role submits the template to CloudFormation, which uses the execution role to provision resources.
Detalhes das caixas (4)
- CDK app
An app holds stacks; each CDK stack becomes one CloudFormation stack. Constructs (L1
Cfn*, L2, L3) are the building blocks inside a stack.- Cloud assembly
A cloud assembly contains CloudFormation templates and deployment artifacts. cdk synth writes it to cdk.out.
- CloudFormation
The deployment role submits the template. CloudFormation uses the execution role to provision resources.
- CDKToolkit stack
Bootstrapping provisions the S3 bucket, ECR repository and roles used to publish assets and deploy stacks.
Da documentação da AWS (21)
- Synthesis produces a cloud assembly containing CloudFormation templates and deployment artifacts such as file and image assets.
- The synthesis lifecycle is construction, preparation with Aspects, validation, then synthesis triggered by app.synth().
- The CDK CLI writes the cloud assembly to cdk.out by default.
- During deployment, assets are uploaded to bootstrap S3 and ECR resources and templates are submitted to CloudFormation.
- The CDK app has exited before CloudFormation deployment starts.
- Deploy-time code can be represented by a CloudFormation custom resource.
- cdk deploy defaults to change-set, creating and executing a CloudFormation change set.
- The direct method deploys without creating a change set.
- prepare-change-set creates a change set without deploying it.
- execute-change-set executes a previously prepared change set.
- --require-approval accepts any-change, broadening and never.
- --require-approval defaults to broadening.
- broadening prompts when changes widen permissions or security group rules.
- --rollback-trigger-alarm-arns accepts up to 5 CloudWatch metric alarms.
- An alarm entering ALARM during rollback monitoring causes CloudFormation to roll back the deployment.
- --monitoring-time-minutes accepts whole numbers from 0 to 180 when used with rollback trigger alarms.
- The monitoring-time default is 0, so alarms are monitored only during deployment.
- FilePublishingRole publishes file assets.
- ImagePublishingRole publishes image assets.
- DeploymentActionRole submits deployments.
- CloudFormationExecutionRole grants CloudFormation resource permissions.
Bootstrap resources and roles
BootstrappingProvisioning storage and roles needed for CDK deployment in an AWS account and Region. prepares an AWS account and Region for CDK deployments. It creates the storage and IAM roles that deployment tools need before they can publish application assetsA local file or container image packaged and published for use by deployed infrastructure. and submit templates. An IAM roleAn identity that a user, application or service assumes to obtain a set of permissions. is an identity that a tool or service assumes to obtain permissions.
How it works
- Bootstrap each target environmentThe AWS account and Region where CDK resources are deployed., meaning each account and Region.
- CloudFormation creates
CDKToolkitby default, including an S3 bucket, ECR repository, IAM roles and an SSM parameter that records the bootstrap version. - The CDK CLI uses separate roles for lookups, file publishing, image publishing and deployment. CloudFormation uses its service roleAn IAM role that an AWS service assumes to perform actions on your behalf. to create resources.
- Re-run
cdk bootstrapto upgrade the stackA group of resource definitions that CDK maps to a CloudFormation stack. when needed. Enable--termination-protectionto prevent accidental deletion.
| Role | Purpose |
|---|---|
CloudFormationExecutionRole |
Let CloudFormation provision resources |
DeploymentActionRole |
Submit deployments, including across accounts |
FilePublishingRole |
Publish files to S3 |
ImagePublishingRole |
Publish images to ECR |
LookupRole |
Read environment information for contextKey-value settings and cached environment information associated with a CDK construct. |
Exam cues
- If the question says the bootstrap version parameter is missing, think bootstrap the intended environment, because the deployment expects its supporting stack.
- If the question says a CDK Pipeline reports invalid principals in the target, think missing bootstrap roles, because the policy references roles that may not exist.
- If the question says many accounts need identical bootstrap resources, think export the template and use StackSets, because the template can be deployed with CloudFormation tools.
Remember
- Default stack name:
CDKToolkit. Default bootstrap roles: five. - The unbootstrapped exception requires no assets and a template under 51,200 bytes.
- Re-running bootstrap upgrades when needed; otherwise it makes no change.
Trap: Deleting the bootstrap stack deletes supporting resources and breaks the pipeline. AWS documents no general recovery solution; update the stack in place.
Da documentação da AWS (18)
- A CDK environment is an AWS account and Region.
- Bootstrap each account and Region intended for CDK deployment.
- Bootstrapping provisions an S3 asset bucket, an ECR image repository and IAM roles.
- The bootstrap CloudFormation stack is named CDKToolkit by default.
- The bootstrap stack includes an SSM parameter that records the bootstrap template version.
- CloudFormationExecutionRole is the service role CloudFormation uses to provision resources.
- DeploymentActionRole is assumed by the CDK CLI for deployment and can be assumed across accounts.
- FilePublishingRole uploads and deletes file assets in the bootstrap S3 bucket.
- ImagePublishingRole publishes image assets to the bootstrap ECR repository.
- LookupRole grants read-only access for context lookups.
- A missing /cdk-bootstrap/.../version SSM parameter error can indicate that the target environment has not been bootstrapped.
- Without bootstrap resources, only stacks with no assets and synthesized templates under 51,200 bytes can deploy.
- For CDK Pipelines, invalid principals in a target environment can mean bootstrap IAM roles do not exist; an unbootstrapped environment is the most likely cause.
- cdk bootstrap --show-template exports the bootstrap template for deployment with CloudFormation tools such as StackSets or Control Tower.
- Re-running cdk bootstrap upgrades the bootstrap stack if needed and otherwise makes no change.
- Deleting a bootstrap stack breaks its pipeline and has no general recovery solution.
- --termination-protection protects the bootstrap stack against accidental deletion.
- An IAM role is an identity that can be assumed to obtain its permissions.
Assertions and snapshot tests
CDK assertions inspect generated CloudFormation templates to catch infrastructure mistakes before deployment. A snapshot is a saved template baseline; a fine-grained assertionA test of a specific property or requirement in a generated CloudFormation template. checks one specific requirement.
How it works
- Define the stackA group of resource definitions that CDK maps to a CloudFormation stack. in a test using a framework such as Jest or pytest.
- Create a template with
Template.fromStack(). Check properties withhasResourceProperties()and resource counts withresourceCountIs(). - Compare snapshots when you need to review the whole template, while retaining specific assertions for required settings.
- Run validation commands in a pipeline step before deployment.
- For local Lambda behavior, run
cdk synthand pass the template tosam local invokewith the function identifier. Usesam local start-apiorsam local start-lambdafor local endpoints.
Exam cues
- If the question says an infrastructure property must be checked before deployment, think a fine-grained template assertion, because it examines the generated resource configuration.
- If the question says invoke CDK-defined Lambda code locally, think synthesize first and use SAM local, because SAM reads the resulting template.
Remember
hasResourceProperties()uses partial matching; other properties may exist.resourceCountIs()checks a resource type’s count.- CDK upgrades can change snapshots without proving a defect.
Trap: A saved snapshot records the previous template. It does not prove the template met the intended requirements.
Da documentação da AWS (12)
- Fine-grained CDK assertions test specific properties of synthesized CloudFormation templates.
- Snapshot tests compare a synthesized template with a stored baseline.
- CDK upgrades can change synthesized templates, so snapshots alone do not establish correctness.
- The CDK assertions module works with frameworks such as Jest for TypeScript or JavaScript and pytest for Python.
- Template.fromStack creates a template for assertions from a CDK stack.
- hasResourceProperties partially matches supplied properties, allowing untested properties to exist.
- resourceCountIs checks the number of resources of a specified CloudFormation type.
- CDK Pipelines supports validation steps before or after a deployment.
- Run cdk synth before testing a CDK application with SAM local.
- sam local invoke uses the synthesized template path and function identifier.
- sam local start-api can expose API endpoints from the synthesized CDK template.
- sam local start-lambda exposes a local Lambda endpoint using the synthesized CDK template.
Context and lookups
CDK contextKey-value settings and cached environment information associated with a CDK construct. stores settings and environmentThe AWS account and Region where CDK resources are deployed. lookup results used during synthesisRunning a CDK app to produce CloudFormation templates and deployment artifacts.. Its cache freezes values such as an Amazon Machine ImageAn image used to launch EC2 instances that CDK can look up and cache during synthesis. (AMI), an EC2 launch image, so a changed external value does not silently change the template.
How it works
- A constructA reusable code component that describes one or more CloudFormation resources and their configuration. requests an environment value such as an AMI ID or an Availability Zone.
- If the cache lacks the value, the CLI queries AWS with read-only lookup permissions, saves the result in
cdk.context.jsonand runs the app again. - Commit
cdk.jsonandcdk.context.jsonso CI uses the same context. - Refresh an entry deliberately with
cdk context --reset <key-or-number>; the next synthesis fetches it again.
Exam cues
- If the question says a later deployment unexpectedly replaces instances after a new AMI appears, think cached context, because uncached latest-image lookups can change the template.
- If the question says an app setting must survive cache clearing, think the
contextkey incdk.json, because cached lookup data belongs in a separate file.
Remember
LookupRoleprovides read-only lookup access.cdk context --resetaccepts an entry key or number.- Context includes feature flags and app settings as well as cached lookups.
Trap: Deleting cached context to make CI succeed can change the generated template. Refresh specific values deliberately.
The CLI queries the environment when a required context value is missing.
The CLI saves the result in cdk.context.json, then runs the app again with that context.
Da documentação da AWS (11)
- CDK context consists of key-value pairs associated with apps, stacks or constructs.
- CDK context includes cached environment values, feature flags and application settings.
- cdk.context.json caches environment lookups such as Availability Zones and AMI IDs so external changes do not silently alter synthesis.
- When context is missing, the CLI queries the AWS account, stores the result in cdk.context.json and runs the app again.
- Commit cdk.json and cdk.context.json with application source so CI uses the same project context.
- cdk context --reset <key-or-number> removes a cached context entry.
- The next synthesis refreshes a reset cached context entry.
- Keep noncached application context under the context key in cdk.json.
- Do not manually edit cached context lookup values.
- Without context caching, a new latest AMI can cause instance replacement on a later deployment.
- The bootstrap LookupRole provides read-only permissions for environment lookups.
Cross-account trust
Cross-account CDK deployment lets a pipeline use roles in a separate target account. Trust controls who may enter; the CloudFormation execution policy controls which resources the deployment may change.
How it works
- BootstrapProvisioning storage and roles needed for CDK deployment in an AWS account and Region. the pipeline environmentThe AWS account and Region where CDK resources are deployed. and every target account and Region.
- An Amazon Resource NameA string that uniquely identifies an AWS resource. (ARN) identifies the execution policy to use. In each target, set
--trust <pipeline-account-id>together with--cloudformation-execution-policies <policy-ARN>. - Publish file assetsA local file or container image packaged and published for use by deployed infrastructure. using the target’s
FilePublishingRole. UseDeploymentActionRoleto submit the CloudFormation deployment. - CloudFormation assumes
CloudFormationExecutionRoleand provisions the resources allowed by its policies.
Exam cues
- If the question says a pipeline must deploy into another account, think target bootstrap trust plus execution policies, because both roleAn identity that a user, application or service assumes to obtain a set of permissions. access and resource permissions are required.
- If the question says synthesisRunning a CDK app to produce CloudFormation templates and deployment artifacts. needs read access but deployment must remain prohibited, think
--trust-for-lookup, because lookup trust does not grant deployment rights. - If the question says a target reports invalid principals, think missing bootstrap roles, because the policy may reference roles that were never created.
Remember
- Execution policies default to
AdministratorAccess. ScopeA construct and its children to which an operation such as an Aspect applies. them to the required resources and actions. - Updating
--trustreplaces the trusted account list; include every account to retain. - File publishing and deployment use separate roles.
Trap: Trust grants access to deployment roles. It does not restrict their execution policies to the pipeline author’s intended resources.
A commit to the source repository starts the pipeline.
The synth build runs the app and produces the cloud assembly: one template per stack plus file and image assets.
For each deployment stage, the pipeline assumes the target account's bootstrap deploy role. That works only if the target was bootstrapped with trust for the pipeline account.
Separate publishing roles upload file and image assets; the deployment role submits the template as a change set.
CloudFormation assumes the CloudFormation execution role and creates or updates the resources.
Detalhes das caixas (6)
- Source
A commit starts the pipeline. CDK Pipelines can source from GitHub, CodeCommit and other providers.
- Synth build
A
ShellStepruns the install, build andcdk synthcommands and produces the cloud assembly (templates plus assets).- CodePipeline
CDK Pipelines reconfigures itself when application stages or stacks change. Approval before a target stage uses addPre().
- Deploy role
DeploymentActionRole permits deployment into the target. File and image assets use separate publishing roles.
- CFN exec role
CloudFormation provisions resources with this service role. Its execution policies default to AdministratorAccess.
- CloudFormation
Assets go to the bootstrap bucket or ECR repository first, then the template is deployed as a normal CloudFormation stack.
Da documentação da AWS (20)
- CDK Pipelines requires bootstrapping the pipeline environment and each target environment.
- Bootstrap a target with --trust set to the pipeline account ID to permit cross-account deployments.
- --cloudformation-execution-policies selects the policies for future CDK deployments.
- The default CloudFormation execution policy is AdministratorAccess.
- The CDK CLI assumes DeploymentActionRole to submit deployments.
- CloudFormation uses CloudFormationExecutionRole to provision resources.
- FilePublishingRole publishes file assets to the bootstrap S3 bucket.
- --trust-for-lookup permits context lookups without granting deployment permission.
- When updating --trust, include every account to retain; previously trusted accounts omitted from the list lose trust.
- Using --trust also requires --cloudformation-execution-policies.
- Invalid principals in a CDK Pipeline target can indicate missing bootstrap roles; an unbootstrapped target is the most likely cause.
- CDK Pipelines can build and deploy application changes when source code is committed.
- CDK Pipelines reconfigures itself when application stages or stacks change.
- The synth step produces the cloud assembly of templates and deployment artifacts.
- StageDeployment.addPre adds steps before the attached stage deploys.
- StageDeployment.addPost adds steps after the attached stage deploys.
- ManualApprovalStep adds a manual approval step to a CDK Pipeline.
- CDK Pipelines supports sources such as GitHub and CodeCommit.
- A CDK Pipeline can use a ShellStep to run installation, build and synthesis commands.
- An Amazon Resource Name (ARN) uniquely identifies an AWS resource.
Pipelines and approval steps
CDK Pipelines builds and deploys CDK apps through a pipeline that can update its own structure. A stageA group of related stacks deployed together in a CDK application. groups related stacksA group of resource definitions that CDK maps to a CloudFormation stack.; a waveA group of CDK pipeline stages that can deploy in parallel. groups stages that may deploy in parallel.
How it works
- BootstrapProvisioning storage and roles needed for CDK deployment in an AWS account and Region. the environmentsThe AWS account and Region where CDK resources are deployed. and provision the initial pipeline.
- Configure a source and a synthRunning a CDK app to produce CloudFormation templates and deployment artifacts.
ShellStep, a step that runs build commands andcdk synth. - Add application stages with
pipeline.addStage(). The pipeline reconfigures itself when stages or stacks change. - Add
ManualApprovalStepbefore a stage withaddPre(). UseaddPost()for tests after deployment. - Pass stack outputs to a test through
envFromCfnOutputs. UseaddWave()when several stages may deploy in parallel.
Exam cues
- If the question says approval must precede production, think
addPre()on the production stage, because it runs before that stage’s deployment. - If the question says a test needs a newly created endpoint, think a post-deployment
ShellStepwithenvFromCfnOutputs, because the endpoint is available as a deployed stack output.
Remember
addStage()returns aStageDeployment.addPre()means before the attached stage;addPost()means after it.- After initial provisioning, developers can submit changes through the pipeline without direct production credentials.
Trap: An approval attached with
addPost()to production occurs after production deployment. Attach it before the stage that must wait.
A pre-deployment ManualApprovalStep must complete before the application stage deploys.
A post-deployment ShellStep tests the deployed resources and can receive stack outputs.
Da documentação da AWS (13)
- CDK Pipelines automatically reconfigures its pipeline when application stages or stacks are added.
- Bootstrap and provision the initial pipeline before using it to deploy subsequent changes.
- The CodePipeline construct defines the pipeline source and synthesis commands.
- A synth ShellStep can build the app and run cdk synth.
- A CDK Stage groups related stacks.
- pipeline.addStage returns a StageDeployment.
- StageDeployment.addPre runs steps before deployment.
- StageDeployment.addPost runs steps after deployment.
- ManualApprovalStep adds a human approval step to a CDK Pipeline.
- pipeline.addWave groups application stages that can deploy in parallel.
- A post-deployment ShellStep can run validation tests.
- envFromCfnOutputs passes deployed CfnOutput values as environment variables.
- After bootstrapping and initial provisioning, developers can deploy changes through the pipeline without direct production account credentials.
Aspects and synthesis checks
An AspectAn operation CDK applies to constructs in a scope during synthesis. applies a rule across a CDK constructA reusable code component that describes one or more CloudFormation resources and their configuration. tree, such as requiring bucket versioning or adding tags. It visits constructs during synthesisRunning a CDK app to produce CloudFormation templates and deployment artifacts. so a shared rule can inspect resources without being repeated in each definition.
How it works
- Register an Aspect with
Aspects.of(scope).add(...); scopeA construct and its children to which an operation such as an Aspect applies. means the construct and children the operation covers. - CDK calls
visit()on the parent and then its children during preparation. - Inspect or modify each relevant resource. Add
Annotations.of(node).addError(...)when a requirement fails, so synthesis fails. - Apply the Aspect on a
Stage, a group of stacksA group of resource definitions that CDK maps to a CloudFormation stack., or below it when checking that StageA group of related stacks deployed together in a CDK application.’s resources.
Exam cues
- If the question says bucket versioning must be checked during synthesis, think an Aspect with an error annotation, because the annotation prevents producing a deployable assembly.
- If the question says developers must not bypass infrastructure policy, think external CloudFormation Hooks or AWS Config, because developers control code inside the CDK Pipeline.
Remember
- Aspects run during preparation and visit parent before children.
- Aspects do not cross
Stageboundaries. - Hooks provide preventive checks; AWS Config provides reactive checks. The execution roleAn identity that a user, application or service assumes to obtain a set of permissions. must not be able to disable these controls.
Trap: An Aspect is code in the app. It cannot enforce a security boundary against someone who can change that code.
Da documentação da AWS (9)
- A CDK Aspect applies an operation to a construct and its children in a specified scope, such as validation or tagging.
- Aspects.of(scope).add registers an Aspect.
- CDK calls an Aspect's visit method from parent to child during preparation.
- Aspects do not cross Stage boundaries; apply an Aspect on the Stage itself or below it to visit its constructs.
- An Aspect can use Annotations.of(node).addError to fail synthesis and prevent deployment of that cloud assembly.
- CDK Pipelines cannot prevent malicious developers who control its code from bypassing compliance checks.
- CloudFormation Hooks provide preventive compliance checks outside the CDK pipeline.
- AWS Config provides reactive compliance checks outside the CDK pipeline.
- The CloudFormation execution role must not be allowed to disable external compliance controls.
Development and resource management commands
CDK development commands shorten the edit and deploy cycle or manage resources already in an account. DriftA difference between deployed resource configuration and its CloudFormation template. means a deployed resource differs from the configuration CloudFormation records for it.
How it works
- Use
cdk diffto inspect proposed changes. Usecdk importto adopt existing resources into a stackA group of resource definitions that CDK maps to a CloudFormation stack.. - During development, use
--hotswapfor supported direct service updates orcdk watchto deploy on local changes. Hotswap uses current credentials and introduces drift. - Reconcile hotswap drift with
cdk deploy --revert-drift. Choose--hotswap-fallbackwhen unsupported changes should trigger a full deployment. - Set a removal policyA resource setting that determines what happens to it when its stack is destroyed. before destroying a stack.
RETAINkeeps the resource outside the stack;DESTROYrequests deletion.
| Command | Purpose |
|---|---|
cdk drift |
Detect deployed configuration drift |
cdk refactor |
Preserve deployed resources during code refactoring |
cdk orphan |
Detach resources without deleting them |
cdk watch |
Deploy on local changes; hotswap by default |
Exam cues
- If the question says a development update should skip CloudFormation, think hotswap, because it calls service APIs directly and causes drift.
- If the question says data must survive stack destruction, think
RemovalPolicy.RETAIN, because the resource remains outside stack management. - If the question says a disposable bucket must be deleted with its contents, think
DESTROYplusautoDeleteObjects: true, because CloudFormation cannot delete a nonempty bucket.
Remember
- Hotswap is for development only and does not assume bootstrapProvisioning storage and roles needed for CDK deployment in an AWS account and Region. roles.
--hotswapignores unsupported changes;--hotswap-fallbackfalls back to CloudFormation.--no-rollbackleaves changes after failure and cannot replace resources.- Persistent data resources commonly default to
RETAIN; check each resource’s documented default.
Trap:
DESTROYalone does not empty an S3 bucket. Also, retaining a resource preserves it outside the destroyed stack, not inside a stack that still manages it.
Da documentação da AWS (19)
- cdk deploy --hotswap updates supported resources through service APIs using current credentials rather than bootstrap roles.
- Hotswap deliberately introduces CloudFormation drift and is for development only.
- cdk deploy --revert-drift reconciles drift through a drift-aware change set.
- --hotswap ignores changes that it cannot apply directly.
- --hotswap-fallback performs a full CloudFormation deployment when changes require it.
- cdk watch monitors local changes and automatically deploys.
- cdk watch uses hotswap by default.
- cdk import uses CloudFormation resource import to bring existing resources into a CDK stack.
- cdk drift detects configuration drift.
- cdk refactor preserves deployed resources during code refactoring.
- cdk orphan detaches resources without deleting them.
- cdk diff compares infrastructure changes.
- --no-rollback leaves changes in place after a deployment failure.
- Deployments using --no-rollback cannot replace resources.
- RemovalPolicy.RETAIN leaves the resource outside stack management when the stack is destroyed; the resource must be managed or deleted separately.
- RemovalPolicy.DESTROY requests deletion of the resource when its stack is destroyed.
- The CDK resource guide describes RETAIN as the default for persistent data resources, but other resource types can have different removal defaults.
- CloudFormation cannot delete a nonempty S3 bucket with DESTROY alone.
- autoDeleteObjects: true makes CDK delete a bucket's objects before destroying the bucket.
Flashcards
Nada para revisar aqui agora. Escolha outros tópicos ou outro filtro.
·
Todos os 45 flashcards em lista
How do AWS CDK L1, L2 and L3 constructs differ?
L1 maps to a CloudFormation resource; L2 adds defaults and helper methods; L3 combines resources into a pattern.
A platform team wants an approved infrastructure pattern reused in several AWS CDK apps. What should it distribute?
A shared construct library. Consumers import the construct and configure its exposed properties.
Which AWS tool defines infrastructure in programming languages, and how are its resource definitions organized?
AWS CDK. An app contains stacks, which contain constructs. Synthesis produces templates for CloudFormation deployment.
An AWS CDK team needs direct control over the CloudFormation properties of an S3 bucket. Which construct level fits?
L1, such as CfnBucket, because it exposes the CloudFormation resource properties directly.
Which AWS CDK commands synthesize templates, preview changes and deploy stacks?
cdk synth, cdk diff and cdk deploy, respectively.
What does AWS CDK synthesize, and how does cdk deploy use the result?
A cloud assembly of CloudFormation templates and deployment artifacts. Deployment uploads assets and submits templates to CloudFormation, using a change set by default.
What are the AWS CDK synthesis lifecycle phases, and when does deployment start?
Construction, preparation with Aspects, validation, then synthesis. The CDK app exits before CloudFormation deployment; deploy-time code can use a custom resource.
What does the AWS CDK deploy --require-approval option control?
Approval prompts: any-change, broadening or never. The default broadening prompts when permissions or security group rules widen.
An AWS CDK team must inspect a CloudFormation change set with external tooling before execution. Which deployment methods fit?
Use --method prepare-change-set, review the change set, then --method execute-change-set.
An AWS CDK team wants CloudFormation to roll back when application alarms fire. Which deployment options apply?
Use --rollback-trigger-alarm-arns with up to 5 metric alarms. Set --monitoring-time-minutes from 0 to 180 for monitoring after completion; the default is 0.
An AWS CDK app must run custom logic after CloudFormation creates a resource. Can ordinary code following the construct constructor wait for that creation?
No. The app finishes before deployment starts. Represent deploy-time logic with a custom resource.
What resources does AWS CDK bootstrapping create for an environment?
The CDKToolkit stack by default, with an S3 asset bucket, ECR image repository, IAM roles and an SSM bootstrap version parameter. An environment is an account and Region.
What are the five default AWS CDK bootstrap roles used for?
CloudFormationExecutionRole: provision resources. DeploymentActionRole: submit deployments. FilePublishingRole: S3 assets. ImagePublishingRole: ECR assets. LookupRole: read-only context lookups.
An AWS CDK deployment reports a missing bootstrap version SSM parameter. What should the team check?
Check that the intended account and Region are bootstrapped. Without bootstrap resources, only asset-free stacks with templates under 51,200 bytes can deploy.
A CDK Pipeline fails in a target account with a policy containing invalid principals. What bootstrap problem should the team investigate?
Missing target bootstrap roles. The target account and Region may not have been bootstrapped.
Many AWS accounts need identical CDK bootstrap resources. How can a team distribute the template and protect the stacks?
Export it with cdk bootstrap --show-template and deploy with StackSets or Control Tower. Enable --termination-protection and upgrade existing stacks rather than deleting them.
Should an AWS CDK bootstrap stack be deleted and recreated when its template changes?
No. Re-run cdk bootstrap to upgrade it. Deleting it breaks the pipeline and has no general recovery solution.
How should a team check AWS CDK resource properties before deploying infrastructure?
Use assertions-module tests against the synthesized template, such as Template.fromStack and hasResourceProperties. Run them in the pipeline before deployment.
When should an AWS CDK team use fine-grained assertions versus snapshot tests?
Use fine-grained assertions for specific template requirements. Snapshots detect changes against a baseline, but CDK upgrades can change templates too, so do not rely on snapshots alone.
How can a team automate unit tests of specific resource properties in an AWS CDK stack?
Create a template with Template.fromStack and use CDK assertions with a test framework such as Jest or pytest.
An AWS CDK snapshot test changes after a library upgrade. Does that prove the infrastructure is incorrect?
No. CDK upgrades can change synthesized templates. Review the change and keep fine-grained assertions for required behavior.
Does AWS CDK hasResourceProperties require the listed properties to be the resource's only properties?
No. It performs a partial match. Use resourceCountIs separately when the resource count matters.
Why should an AWS CDK team commit cdk.context.json to source control?
It freezes environment lookups such as AMI IDs for repeatable synthesis in CI. Refresh intentionally with cdk context --reset <key-or-number>, then synthesize again.
An AWS CDK team wants to adopt a newer AMI deliberately without refreshing every cached lookup. What should it do?
Reset only the AMI lookup entry with cdk context --reset <key-or-number>, then synthesize to refresh that entry.
An AWS CDK application setting must survive clearing cached lookups. Where should the team store it?
Under the context key in cdk.json. Keep cached lookup values managed by the CLI in cdk.context.json.
What happens when an AWS CDK app requests a context lookup that is not cached?
The CLI queries the account, saves the result in cdk.context.json and runs the app again.
How can a CDK pipeline in account A deploy into account B?
Bootstrap each target account and Region with --trust A and --cloudformation-execution-policies <policy-ARN>. The deployment role submits the template and CloudFormation uses its execution role.
What determines the resource permissions of cross-account CDK deployments?
The CloudFormation execution policies selected at bootstrap. AdministratorAccess is the default; choose narrower policies for the resources the pipeline needs.
A CDK pipeline reports invalid principals in a target account. Does adding account trust alone guarantee that the target is ready?
No. Verify that target bootstrap roles exist. Missing roles often mean the account and Region were never bootstrapped.
An account needs to synthesize CDK stacks using another account's lookups but must not deploy there. Which bootstrap option fits?
--trust-for-lookup, which grants lookup access without deployment permission.
An administrator adds a trusted account to an existing CDK bootstrap stack. What must the --trust list include?
All accounts that must remain trusted. Omitting an existing account removes its trust.
What is a self-updating AWS CDK Pipeline?
A pipeline that reconfigures itself when its app adds stages or stacks. Bootstrap and provision it initially, then deploy subsequent changes through the pipeline.
How does a CDK Pipeline add approvals and tests around a stage and pass deployed URLs to a test?
Use addPre or addPost on the returned StageDeployment with ManualApprovalStep or ShellStep. Use envFromCfnOutputs to expose deployed outputs. addWave groups stages for parallel deployment.
A CDK Pipeline must wait for human approval before its production stage starts. Where should the approval be attached?
Use productionStage.addPre(new ManualApprovalStep(...)). addPost on production runs after that stage has deployed.
A CDK Pipeline smoke test needs the URL created by a deployed stack. How should it receive that value?
Expose it as CfnOutput and pass it through envFromCfnOutputs in a post-deployment ShellStep.
An AWS CDK team wants synthesis to fail when an S3 bucket lacks versioning. What should it use?
An Aspect that inspects bucket constructs and adds an error annotation. Apply it on each Stage or below, because Aspects do not cross Stage boundaries.
Can compliance checks inside a CDK Pipeline prevent a developer who controls the pipeline code from bypassing them?
No. Use external controls such as preventive CloudFormation Hooks or reactive AWS Config checks that the CloudFormation execution role cannot disable.
A CDK Aspect applied above a Stage fails to inspect that Stage's buckets. What should change?
Apply the Aspect to the Stage itself or below it. Aspects do not propagate across Stage boundaries.
When does AWS CDK run an Aspect's visit method?
During preparation, visiting the scope construct and then its children from parent to child.
What do AWS CDK hotswap and watch do, and how should a team reconcile hotswap changes?
They speed development by updating supported resources directly; watch uses hotswap by default. Hotswap uses current credentials and causes drift. Reconcile with cdk deploy --revert-drift.
Which AWS CDK commands handle existing resources, drift, code moves and detaching resources?
cdk import adopts existing resources; cdk drift detects drift; cdk refactor preserves deployed resources during code changes; cdk orphan detaches without deleting; cdk diff compares changes.
An AWS CDK team must preserve a data resource when destroying its stack. Which removal policy fits?
RemovalPolicy.RETAIN. The resource remains but leaves the destroyed stack's management.
An AWS CDK development bucket uses RemovalPolicy.DESTROY but stack deletion fails because the bucket contains objects. What setting is missing?
autoDeleteObjects: true, which deletes the bucket's files before CloudFormation removes the bucket. Use it only when deleting those objects is intended.
An AWS CDK deployment with --no-rollback needs to replace a resource. Can it succeed with that option?
No. --no-rollback deployments that require replacement fail.
What happens to unsupported changes during AWS CDK --hotswap, and how does --hotswap-fallback differ?
--hotswap ignores unsupported changes. --hotswap-fallback performs a full CloudFormation deployment when required.