Skip to content
cdkd

cdkd export: custom resources and policies

CloudFormation cannot import some kinds of resource that CDK stacks often contain: Custom Resources, AWS::IAM::Policy, and the queue and topic policies AWS::SQS::QueuePolicy and AWS::SNS::TopicPolicy. cdkd export migrates them in a second phase. Phase 1 imports everything else. Phase 2 then submits the full template as an UPDATE changeset, and CloudFormation creates these resources itself.

They differ in what you have to do:

Resource Needs a flag What phase 2 costs
Custom Resource --include-non-importable The backing Lambda is invoked with a Create event again.
S3 notifications on a bucket the stack does not own --include-non-importable Events matching them are not delivered for a few seconds to about a minute.
AWS::IAM::Policy no The permission is missing until phase 2 completes.
AWS::SQS::QueuePolicy, AWS::SNS::TopicPolicy no Nothing: phase 2's CREATE replaces the policy in place.
cdkd export MyStack --include-non-importable --dry-run   # preview both phases
cdkd export MyStack --include-non-importable

Assets are published before phase 1

Phase 2 creates resources from the synthesized template, and a Custom Resource can read an asset while it is created: a BucketDeployment copies its files from the asset location the template names. That location is the CDK bootstrap bucket or repository, while cdkd deploy may have published the assets to cdkd's own asset storage.

So when phase 2 creates a Custom Resource, cdkd first publishes the stack's file and image assets to the locations in the app's asset manifest, as cdk deploy does. It first checks that each bucket belongs to your account. An asset already there is skipped.

Case What cdkd does
Phase 2 creates a Custom Resource, and the stack has assets Publishes them after the confirmation, before phase 1.
The publish fails, for example no CDK bootstrap in the region Stops before phase 1 and names each asset and its location.
A bucket is missing or belongs to another account Stops before any upload.
Phase 2 creates no Custom Resource (it re-creates policies or only restores outputs), no assets, --template Publishes nothing and makes no extra call.

A stack synthesized with LegacyStackSynthesizer publishes nothing here: its template's asset parameters already name the bucket cdkd published to.

To fix a refusal, run cdk bootstrap for the account and region, then run the export again.

Custom Resources and --include-non-importable

A Custom Resource is backed by a Lambda function that you or a CDK construct wrote. In the template its type is Custom::* or AWS::CloudFormation::CustomResource. The second is what new cdk.CustomResource(...) synthesizes when no resourceType is passed.

Without --include-non-importable, cdkd refuses a stack that contains one. Under --dry-run the refusal becomes a warning, so you still see the full plan.

With the flag, phase 2 has CloudFormation create the Custom Resources. To do so, CloudFormation invokes each backing Lambda's onCreate handler again, although the resource already exists.

What the handler must do

The handler has to cope with that second Create event:

  1. It must be idempotent: it returns the same PhysicalResourceId and Data on every event type.
  2. It must answer through the response URL: it sends its status payload with an HTTP PUT to event.ResponseURL.

Warning

cdkd's own deploy also accepts a handler that only returns a value. CloudFormation does not. A Custom Resource backed by such a Lambda hangs phase 2, and every later cdk deploy, until CloudFormation's one-hour Custom Resource timeout.

Notifications on a bucket the stack does not own

addEventNotification on a bucket the stack does not own, such as one from s3.Bucket.fromBucketName(...), synthesizes a Custom::S3BucketNotifications resource that writes its rules next to whatever else the bucket holds. Each rule's Id starts with the StackId the resource was created with. The same happens on a bucket the stack owns when the @aws-cdk/aws-s3:keepNotificationInImportedBucket feature flag is on.

Phase 2 creates that resource again under the CloudFormation stack's StackId. Its handler keeps every rule already on the bucket and adds its own, so the rules cdkd's deploy wrote would duplicate the new ones, and S3 refuses two overlapping rules. So, right before phase 2, cdkd takes off the bucket every rule whose Id starts with the StackId that cdkd sent. It keeps every other rule and any EventBridge setting. Phase 2 then writes the rules again. A resource an older cdkd created was sent a StackId that every stack with the same logical ID shares, so for it cdkd takes only the rules whose destination, events and filter match the ones its state records.

Warning

From the moment cdkd takes the rules off until phase 2 has written them again, usually a few seconds and at most about a minute, S3 does not deliver the events those rules match. An event in that window is not delivered later. The plan and the confirmation prompt name each bucket and the rules taken off.

Case What cdkd does
Phase 2 completes Nothing more: the rules are back, under the CloudFormation stack's StackId.
Phase 2 fails, or the export is interrupted Puts back each rule it took off that the bucket no longer holds, as it does for the policies.
Taking the rules off fails Puts back what it took off so far and stops before phase 2.
The bucket holds none of the stack's rules Leaves the bucket alone.

Taking the rules off and putting them back need s3:GetBucketNotification and s3:PutBucketNotification on the bucket. A notification on a bucket the stack owns writes the whole configuration, so cdkd leaves it alone.

To run phase 2 by hand after a failure, first take the rules off again: the error names the bucket and the Id prefix.

AWS::IAM::Policy is deleted and re-created

An AWS::IAM::Policy is an inline policy attached to roles, users or groups. CDK grants emit this type often: a Lambda execution role's inline policy, or an ECS task execution role's ECR pull policy. CloudFormation has no way to look up an existing inline policy, so it cannot import one.

cdkd handles this type without a flag:

  1. Phase 1 leaves the policy out.
  2. cdkd reads each inline policy's document, then deletes the policy from its roles, users and groups.
  3. Phase 2 has CloudFormation create it again from the template.

Warning

Between steps 2 and 3 the permission does not exist. A call that relies on it fails with AccessDenied until phase 2 completes.

If the export fails after step 2, cdkd puts back each policy it deleted, with the document it read, so the roles, users and groups keep their permissions. After a failed phase 2 it first waits until CloudFormation has finished rolling the stack back, because that rollback deletes the policies under the same names.

When reading a document is denied (iam:GetRolePolicy, iam:GetUserPolicy or iam:GetGroupPolicy), cdkd uses the one cdkd state records. If the record holds a redacted value or a dynamic reference, or the read fails for another reason, cdkd stops before it deletes that policy. Putting a policy back needs iam:PutRolePolicy, iam:PutUserPolicy or iam:PutGroupPolicy.

The plan that cdkd prints before the confirmation lists each such policy, and the roles, users and groups it will be removed from. To refuse such a stack instead, pass --no-recreate-import-unsupported.

The policy is checked against the template first

Step 2 and step 3 take their principals from different places. cdkd detaches the policy from the principals recorded in cdkd state. CloudFormation attaches it to the principals named in the template. If the two lists differ, a principal could be detached and not attached again.

cdkd therefore compares the state record with the template before anything changes. When they disagree, it stops the export with no AWS change, and the error tells you what to run:

  • State records a principal the template does not name, or a policy name other than the template's PolicyName. This is usually a template change that has not been deployed. Run cdkd diff, then cdkd deploy. If the value comes from a root Parameter, run the export again with the --parameter values the stack was deployed with.
  • State records no principal list, a value that is not a list of IAM names, or a physical id that is not the policy name. Import the policy again with cdkd import ... --force, so that its record matches the template.
  • State records more than 100 principals. Check the record and the template against AWS. Do not destroy the resource or remove it from the app: that removes the policy from every recorded principal.

Principals cdkd cannot check

cdkd can check a template principal that is one of these:

  • a literal name,
  • a Ref to a role, user or group in the same template,
  • a Ref to a template Parameter.

It cannot check any other value, such as Fn::ImportValue, and it cannot check a missing PolicyName. The plan marks each one it could not check, and the export proceeds.

Important

Under --yes nobody reads those marks. A principal that the template names only through an uncheckable value is detached and may not be re-attached. Read a --dry-run plan before exporting such a stack unattended.

If deleting the policy fails

The export stops between phase 1 and phase 2. cdkd state and the CloudFormation stack that phase 1 created are both kept.

The usual cause is a missing permission: iam:DeleteRolePolicy, iam:DeleteUserPolicy or iam:DeleteGroupPolicy, depending on what the policy is attached to.

cdkd puts back the policies it had already deleted. Running cdkd export again does not resume the export, because the CloudFormation stack now exists. The error gives the steps to finish by hand:

  1. Delete the inline policies.
  2. Right after, run the phase-2 UPDATE yourself.
  3. Remove the state record with cdkd state orphan.

Queue and topic policies are re-created in place

An AWS::SQS::QueuePolicy or AWS::SNS::TopicPolicy writes the one resource policy of each queue or topic it names. CDK emits one for an SNS subscription to an SQS queue (SqsSubscription), and for addToResourcePolicy on a queue or topic. cdkd handles them without a flag:

  1. Phase 1 leaves the policy out.
  2. cdkd reads each queue's or topic's policy. Nothing is deleted.
  3. Phase 2 has CloudFormation create the policy from the template. The create replaces the queue's or topic's policy in place, so the queue or topic keeps a policy throughout.

If phase 2 fails, CloudFormation's rollback deletes the policy it created, which leaves the queue or topic without one. cdkd then puts back the policy it read in step 2, as it does for an AWS::IAM::Policy. Reading needs sqs:GetQueueAttributes or sns:GetTopicAttributes, and putting back needs sqs:SetQueueAttributes or sns:SetTopicAttributes. A denied read falls back to the document cdkd state records, under the same conditions as for an inline policy.

cdkd checks the record against the template first, and stops the export with no AWS change when:

  • State records a queue or topic the template does not name. After the export its policy would be managed by no stack. This is usually a template change that has not been deployed: run cdkd diff, then cdkd deploy.
  • Two policies of the stack write the same queue or topic. It holds one policy, so phase 2 would leave only one of them. Merge them into one in the app and deploy.
  • State does not record which queues or topics the policy wrote. Import the policy again with cdkd import ... --force.

A queue or topic that the template names through a value cdkd cannot resolve, such as Fn::ImportValue, is marked in the plan, and the export proceeds.

If phase 2 fails

cdkd keeps its state record, and the CloudFormation stack from phase 1 stays. Once CloudFormation has rolled the update back, cdkd puts back the inline policies it deleted, the queue and topic policies the rollback removed, and the bucket notification rules it took off. The error says which ones it put back, and names any it could not. The error prints the recovery:

  1. The aws iam delete-*-policy commands for the inline policies cdkd put back. A queue or topic policy needs no delete: phase 2's create replaces it.
  2. An aws cloudformation create-change-set --change-set-type UPDATE command that finishes phase 2, run right after them. Before it, take the bucket notification rules off again; the error names each bucket and Id prefix.
  3. cdkd state orphan, which removes the state record once the update has succeeded.

If CloudFormation is still changing the stack when cdkd stops waiting (30 minutes), cdkd does not put the policies back, and the error says so. If the stack turns out UPDATE_COMPLETE, phase 2 did complete: the error asks only for the cdkd state orphan step. Each policy's document is in the state record, which cdkd state show prints.

If the export is interrupted

Ctrl-C (or SIGTERM) between the first policy delete and the end of phase 2 does not leave the policies deleted. cdkd says it is stopping, then:

When the signal lands What cdkd does
During the deletes, or before the phase-2 update starts Finishes the delete in progress, starts no other and no update, and puts back the policies at once.
While CloudFormation runs the phase-2 update Stops watching it, but does not cancel it. Waits until the stack settles, then puts the policies back unless the update completed.
After the phase-2 update completed Puts nothing back: the policies are CloudFormation's. Finishes the export; in a nested-stack tree it stops before the next stack.

In the first two cases the message then says which policies it put back and prints the same recovery as a failed phase 2, and cdkd exits with code 130. A nested stack that stops before the next stack exits 130 too; an export that finishes exits 0.

Bucket notification rules cdkd took off are put back the same way.

Press Ctrl-C a second time to quit at once. cdkd then puts nothing back. It prints the policies it had removed or replaced so far, how to check the stack's status, and the commands to finish by hand: delete the inline policies, run the phase-2 update (it re-creates them), then run cdkd state orphan. It also prints the cdkd force-unlock command, in case a stack lock is left behind.

Last updated: