toolkit

package
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 2, 2026 License: Apache-2.0 Imports: 53 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package toolkit synthesizes, diffs, deploys and destroys AWS CDK apps: a Go port of @aws-cdk/toolkit-lib, the library behind the AWS CDK CLI.

Upstream features not ported yet are listed in the README's Status section. Where this package deliberately behaves differently from upstream, the section on the action says so. Its design, and how it maps upstream's TypeScript API into Go, are recorded in docs/getting-started/adr-0001-port-toolkit-lib-to-go.md.

Getting started

An action runs on a cloud assembly, the directory a CDK app synthesizes into, and takes three things to run: a Source, which says where the assembly comes from; a Toolkit, which New makes; and the action, a method of the toolkit. The toolkit reports what the action does to a host, which is a field of its Options; the default host writes to the terminal.

This program deploys every stack of the CDK app in ./infra, with the default AWS credentials and region:

package main

import (
	"context"
	"fmt"
	"log"

	"github.com/asteroid-computing/aws-cdk-toolkit/toolkit"
)

func main() {
	ctx := context.Background()

	tk, err := toolkit.New(toolkit.Options{})
	if err != nil {
		log.Fatal(err)
	}

	// The CDK app in ./infra, run as cdk.json's "app" would run it.
	app := toolkit.FromCdkApp("go run .", toolkit.CdkAppOptions{WorkingDir: "infra"})

	res, err := tk.Deploy(ctx, app, toolkit.DeployOptions{})
	if err != nil {
		log.Fatal(err)
	}
	for _, s := range res.Stacks {
		fmt.Println("deployed", s.StackName)
	}
}

The default host answers every request with its default, which includes approving a deployment that broadens permissions; see Messages and requests before a program that nobody watches deploys anything. Synth, List and Diff against a local file need no AWS credentials on a source read from a directory, and the examples for them run under go test; a source that runs an app asks AWS for the app's default account and region unless its options say otherwise.

Sources

A Source produces the cloud assembly an action works on, afresh for each action. It is a value that can be shared and used again, and there are three ways to make one:

  • FromAssemblyDirectory reads an assembly that is already on disk, such as a cdk.out, without running anything or needing Node.
  • FromCdkApp runs a command, as cdk.json's "app" does, and reads the assembly it writes. When the app reports context it lacks, such as the result of a VPC lookup, the toolkit looks it up in AWS, keeps it in a ContextStore, and runs the app again.
  • FromAssemblyBuilder calls a Go function that synthesizes an app in the caller's own process, as an aws-cdk-go app does with awscdk.NewApp and App.Synth.

The *Assembly that Toolkit.Synth returns is a source too, so several actions can work on one synthesis. See Ownership for who closes what.

Actions

Each action is a method of Toolkit that takes a source and its own options, and returns its result; where an option's zero value can stand for upstream's default, it does.

To look at an app:

To change AWS:

The actions that deploy, publish or read from an environment use the roles of its bootstrap stack, as the CDK CLI does, and fail with an error of cdkerr.KindBootstrap when it isn't bootstrapped; Drift, for one, uses the base credentials and assumes no role. Each action's section below describes what it does and where it departs from upstream.

Messages and requests

An action reports its progress as messages sent to the toolkit's host, an iohost.Host, and asks it to decide as requests. A message has a code, such as "CDK_TOOLKIT_I5502", and a payload whose type the code determines; only a message's code and payload are stable, so a host matches on them and never on the text or the level. The iohost package documents that contract and lists every code.

The default host, console.Default, writes lines of text to the terminal, and answers every request with its default: it deploys what it is asked to deploy. A program that must hold back security-sensitive changes supplies its own host. The toolkit asks CDK_TOOLKIT_I5060 before it deploys a stack's changes, with the diff in its payload, and a host answers false to decline; iohost.NeedsApproval applies the CDK CLI's --require-approval policies, so that a host asks a person only about the changes that policy covers. A deployment that is declined fails with an error of cdkerr.KindAborted. A host's errors fail the action that sent the message.

To test code that uses the toolkit, pass a github.com/asteroid-computing/aws-cdk-toolkit/toolkittest.Recorder as the host.

Stack selection

Most actions take a cloudassembly.Selector in their options, which says which stacks to act on. The zero Selector selects every stack, those of nested assemblies included, and adds none; a Selector that has patterns or an expansion must also name its Strategy.

  • A pattern strategy selects the stacks whose hierarchical IDs the glob patterns match: "*" matches the stacks at the top level, "**" any stack, "MyStage/*" a stage's stacks, and "!MyStack" excludes one.
  • An expansion adds stacks beside the selected ones: cloudassembly.ExpandUpstream those they depend on, which cdk deploy adds, and cloudassembly.ExpandDownstream those that depend on them, which cdk destroy adds. The CLI's expansions are not the zero value here, so a caller that wants them asks.

A selection that fails, such as a pattern that matches nothing under cloudassembly.StrategyPatternMustMatch, is an error before the action does anything.

Errors

The toolkit's own failures are *cdkerr.Error values, which have a Kind for their category, a Code for upstream's code of the specific failure, and the details of the failure, such as the environment that isn't bootstrapped. Test for a category with errors.Is and a sentinel such as cdkerr.ErrBootstrap, and reach the details with errors.As. An error from the caller's host, from the context, or from an AWS call that the action's documentation says it returns as it is, comes back without one, so check what errors.As reports. An action that fails after it has done part of its work returns the part it did beside the error, as its documentation says. A cancelled context stops an action; see Cancellation.

AWS access

The toolkit resolves credentials and the region as the AWS CLI and the CDK CLI do: from the environment, the shared config files and AWS_PROFILE, and from the instance or container role. AWSOptions overrides that: a profile, a region, a ready aws.Config, an HTTP client for proxies and CA bundles, a file that caches the default account, and CredentialPlugin values that supply credentials for accounts the default ones aren't for.

Toolkit

A Toolkit runs actions on the cloud assemblies a Source produces. New makes one; its Options choose the host that receives the toolkit's messages, whether their text keeps emojis and colour, and how the toolkit reaches AWS. The toolkit reaches AWS only when an action needs it, such as to give a CDK app its default account or to look up context, and then keeps that access for its life.

Upstream's other toolkit options arrive with the actions that use them. Its plugin host is not ported, because a Go program links its plugins rather than loading them by name. Credential plugins are Go values in AWSOptions.CredentialPlugins. Context-provider plugins, which answer the lookups an app makes with provider "plugin", are Go values in Options.ContextProviderPlugins; as upstream's do, they get no AWS credentials from the toolkit. Neither is its list of unstable features: a feature still being settled says so in its documentation.

Ownership

  • A Toolkit holds nothing that needs releasing, so it has no Close, and it is safe for concurrent use.
  • A Source is a value that can be shared and used again; each action produces its assembly afresh.
  • Every action closes the assembly it produced before returning, failed or not, except Toolkit.Synth, which returns it for the caller to close.
  • The *Assembly that Synth returns is itself a Source, so other actions can work on it without synthesizing again. They borrow it and never close it; closing it while an action is using it is a bug in the caller.
  • The toolkit never closes or reconfigures the caller's host.
  • Cancelling an action's context stops the action, and its cleanup, such as releasing locks and removing temporary directories, still runs; see Cancellation.

Cancellation

Cancelling an action's context, or passing its deadline, stops the action as soon as the step in progress allows, and nothing new starts: no stack, environment or context lookup.

  • A CloudFormation operation already started is left running, as when the CDK CLI is interrupted: the toolkit stops watching it after one last read of its events, and the error names the stack and the status it was last seen in. The toolkit never calls CancelUpdateStack; to undo, roll the stack back once the operation ends.
  • A request that starts an operation, such as executing a change set, is sent whole once begun, so the action always knows whether the operation started.
  • Cleanup runs under context.WithoutCancel and has finished when the action returns: deleting a change set that wasn't executed and the empty stack it created, releasing locks, removing temporary directories, stopping the app, and saving the context values found before the cancellation. It is bounded by CloudFormation, not by the context; a program that must stop at once exits, as the CLI does on a second interrupt, and the lock files it leaves are stale to the next run.
  • The one thing cleanup can't remove is a change set CloudFormation is still computing; it is left, with a warning naming it, and goes when a change set is next executed on the stack.
  • The action's error satisfies errors.Is(err, ctx.Err()); check that before its Kind, since some cancelled errors also carry one, such as a synthesis's cdkerr.KindAssembly. A deployment that was only cancelled is never cdkerr.KindDeployment, which means CloudFormation reported a failure, nor cdkerr.KindAborted, which means a confirmation was declined.
  • No goroutine the action started outlives it, and it makes no AWS call after returning.

Context

A ContextStore holds the context an app is synthesized with, including the values context lookups find. AppContext keeps it as the CLI does, in an app directory's cdk.json and cdk.context.json, and writes cdk.context.json byte for byte as the TypeScript CLI writes it, so the two can take turns on one app without needless changes to the file. It differs from upstream's CdkAppMultiContext in one way: it reads the user's ~/.cdk.json only when the caller names the file, because the library never reads process globals such as the home directory. FileContext writes a final newline, which upstream's does not, so that every file this package writes has the same form.

Flags

Toolkit.Flags returns the feature flags an app's libraries report in the cloud assembly, with the values the app configures, as upstream's flags does. Upstream marks the action unstable, and refuses it unless the toolkit enables the unstable feature "flags"; this package has no unstable features, so Flags runs for any caller, but its result may change as upstream's does (M.6-D3).

Only the top-level assembly's feature flag reports are read, not those of nested assemblies, such as a Stage's, as upstream reads them. The flags keep the order the reports list them in (M.6-D2), and their values are raw JSON (M.6-D1). How the CDK CLI shows them, sorted, with an effective value, and how it sets them in cdk.json, belong to the CLI, not to this package.

Diagnose

Toolkit.Diagnose finds why stacks' deployments failed, from their state in CloudFormation, with the diagnosis a failed deployment's error carries as cdkerr.Error.Diagnosis. Upstream marks it unstable, and refuses it unless the toolkit enables the unstable feature diagnose; here it needs no opt-in, as unstable features need none, so its results and messages may still change (M.9-D2). It works best on a source whose AppSynthOptions set Debug, which records the stack traces of the constructs that define the failed resources; the CDK CLI turns debug mode on for cdk diagnose, and the library leaves that to the caller. Through the stack's lookup role, or its deploy role when the lookup role can't be used, the diagnosis also looks into each failed ECS service and custom resource, and into CloudTrail for the failed calls of the stack's own roles and functions, as upstream's additional diagnostic context does; so does a failed deployment's diagnosis.

It departs from upstream in these places:

  • a zero Concurrency means 10, upstream's default, since Go can't tell an unset field from zero, where upstream's explicit 0 fails after synthesis (M.9-D4);
  • a negative Concurrency is refused before synthesis, where upstream fails after it (M.9-D5);
  • when a stack's environment can't be accessed, no further stack is started, those started finish, and the stacks diagnosed are returned beside the errors, joined, where upstream rejects with the first error while the other stacks run on and their results are lost; a cancelled context does the same, and a diagnosis that finishes once the context is done is neither sent nor returned (M.9-D7);
  • the result's diagnoses keep the error that stopped a diagnosis, beside its message (M.9-D1).

It fixes an upstream defect, as the owner approved: the bootstrap stack whose version a diagnosis reads, for its warning when DescribeEvents is denied, is the toolkit's Options.ToolkitStackName, as upstream's deploy, rollback, bootstrap and destroy name it, and DiagnoseOptions has no name of its own, where upstream's diagnose ignores the toolkit's toolkitStackName and reads CDKToolkit unless each call repeats the name in its own option (M.9-D3, #101).

Notices

Notices fetches the CDK notices, announcements of bugs and security issues that affect particular versions of the CDK, and shows the ones that affect the caller's app, as the CDK CLI does before and after its commands. NewNotices makes one, Notices.Refresh fetches the notices, and Notices.Filter and Notices.Display pick and show the ones that apply. Upstream's Notices is internal to toolkit-lib, and only its CLI uses it; it is public here, for a Go program that drives the toolkit to do what the CLI does (M.7-D1). Upstream keeps one Notices for the whole process, into which every toolkit records the bootstrap versions it checks; here a toolkit records into the Notices passed as Options.Notices, if any (M.7-D2). Deploy, rollback, orphan, publish assets, validate and diff record the bootstrap version of each environment they check, before the check can fail, so that an outdated environment is recorded too; Notices.AddBootstrappedEnvironment records an environment a caller checks itself.

A notice names the components it affects and the node-semver ranges of their versions, and it matches when every component of one of its conjunctions matches one the app uses, as upstream's filter decides:

  • the constructs in the tree.json of NoticesOptions.AssemblyDirectory, by class, such as aws-cdk-lib.aws_s3.Bucket, or by module, as in aws-cdk-lib.;
  • "cli", at CLIVersion;
  • "node", at NodeVersion, when it is set;
  • "language:<Language>", when Language is set;
  • "bootstrap", once for each environment recorded, at its bootstrap version.

A bootstrap version that isn't a number isn't recorded, where upstream records it as NaN, and its filter then warns "While filtering notices, could not coerce bootstrap version 'NaN' into semver" and skips it; the environment matches no bootstrap notice either way, and the owner approved leaving out the warning (M.7-D10, #99).

The caller supplies what upstream reads from its process, because the library never reads process globals (M.7-D5):

  • CLIVersion stands in for the CLI's own version, which upstream's caller supplies too (M.7-D3). The notices' cli ranges describe releases of the TypeScript CLI, and this module follows the TypeScript CLI 2.1149.0, the release cut from the commit it is ported from; a caller that wants the notices that release would see passes "2.1149.0". Empty matches no range, so no notice about the CLI matches.
  • NodeVersion stands in for process.version, the Node that upstream runs in; a Go program has none, though a Go CDK app synthesizes with one through jsii (M.7-D4). A leading "v", as node --version prints, is removed, as upstream removes it from process.version. Empty means no node component at all, so no notice about Node matches, where upstream always has one, at the version of the Node it runs in; the owner approved this divergence (M.7-D4, #99).
  • AssemblyDirectory stands in for cdk.out under the working directory; empty reads no tree.
  • CacheDirectory stands in for $CDK_HOME/cache or ~/.cdk/cache; empty caches nothing, so every Refresh asks the website.
  • Timeout stands in for CDK_NOTICES_TIMEOUT, and its default, 3 seconds, is upstream's outside its own integration tests.
  • HTTPClient stands in for Node's global agent, which the CLI replaces with its proxy agent; its default, http.DefaultClient, honours HTTPS_PROXY and NO_PROXY.

The cache directory holds the CDK CLI's two files, in its formats, so a caller that names ~/.cdk/cache shares them with the CLI:

  • notices.json, {"expiration": <milliseconds since the epoch>, "notices": [...]}, keeps the notices for an hour, each as it was received; after a failed refresh it keeps no notices for a minute, in place of what it held, so that the next refresh in that minute doesn't ask again (M.7-D7);
  • connection.json, {"expiration": ..., "hasConnectivity": true}, keeps the answer to the check that the website can be reached, which comes before every fetch, for an hour, whether the answer was yes or no (M.7-D6). The check asks for URL's headers; upstream's always asks the official website, whatever its URL.

A cancelled refresh changes neither file (M.7-D11). Notices never fail an action: a refresh's error is the caller's to show or ignore, as the CLI ignores it.

Bootstrap

Toolkit.Bootstrap deploys the bootstrap stack the CDK CLI at the pinned commit deploys, or a template of one's own, to each environment, as cdk bootstrap does, so that either tool can bootstrap again what the other bootstrapped. It departs from upstream where upstream is wrong or where Go idiom differs:

  • ApplyPermissionsBoundaryToAllRoles turned on is warned of as having no effect only when no boundary is in effect, neither given nor deployed, where upstream warns whenever none is given, though a deployed one is kept;
  • a template that doesn't declare ApplyPermissionsBoundaryToAllRoles, when the option is set, is refused before any IAM call, where upstream's creates the example boundary first;
  • BootstrapEnvironmentsFromSource bootstraps an environment that several stacks share once, where upstream bootstraps it once for each, concurrently;
  • the results are in the order the environments were given, where upstream's are in the order they finished;
  • a failure doesn't leave the other environments running unwatched: the action waits for every environment it started, and starts none still queued once its context is done, where upstream's returns at the first failure while the others carry on (G.10-D3);
  • a legacy bootstrap template, one without a bootstrap version, is refused, because bootstrapping with it is left to the CDK CLI;
  • an environment's span ends when it fails, where upstream's is left open, so that a host timing it waits for an end that never comes.

Deploy

Toolkit.Deploy deploys the selected stacks, each after the stacks it depends on, as cdk deploy does, with the stacks' deploy roles and execution roles, through a change set it prepares and, once approved, executes, or directly, or by executing a change set an earlier command prepared, so that it can deploy what either tool deployed, and either can execute a change set the other prepared. It builds and publishes the stacks' assets first, the template every stack aws-cdk-lib's default synthesizer writes publishes included, through the same glue and publisher as Toolkit.PublishAssets, leaving out those published already unless forced, and uploads a template too large to pass to CloudFormation directly to the staging bucket, as cdk deploy does, so that either tool finds published what the other published (K.7); with ExecuteChangeSetDeployment it publishes nothing, as upstream's doesn't. Before a stack's changes are deployed, CDK_TOOLKIT_I5060 asks to deploy them, with the stack's diff, its nested stacks' included, in the question and the payload, as upstream's does; a host applies an approval policy with iohost.NeedsApproval, the CDK CLI's rule for its --require-approval, since the toolkit asks whatever the policy, as upstream's does. The approval's diff marks no moved resources, as upstream's doesn't. It departs from upstream where upstream is wrong or where Go idiom differs:

  • a negative stack or asset build concurrency is refused, and an asset build concurrency of zero means 1, where upstream's run never settles;
  • a failure returns the stacks deployed until then beside every stack's error, where upstream rejects with the last error only;
  • each deployed stack's environment is resolved, where upstream's is the manifest's, unknown for an environment-agnostic stack;
  • the request to approve a stack's deployment carries the change set it will execute, a field upstream's lacks, and its diffs as a tree of the stack and its nested stacks, where upstream's are a map by name;
  • the approval's diff of a nested stack goes through the change set the stack's change set created for it, where upstream diffs nested stacks by their templates alone;
  • after a rollback the deployment performs first, the new change set, a hotswap's fallback's too, is approved again before it is executed, where upstream asks once, before the rollback, so that changes the approved diff didn't show are deployed unasked; a direct retry, or a hotswap the retry attempts again, isn't asked again, as upstream's isn't;
  • a REVIEW_IN_PROGRESS stack's deployed template is empty, without a GetTemplate call, where upstream calls it, though such a stack has never been deployed; a diff of such a stack shows every resource as an addition;
  • the deployed templates the approval diffs are read through the stack's deploy role, and for a change set once, after the skip check, where upstream reads them through the lookup role before it; a direct or hotswap deployment, asked before its skip check as upstream's is, reads them with a lookup of its own;
  • a stack's error is "<stack name> failed: " and its cause, which errors.Is and errors.As find, such as a deployment's or a bootstrap stack's error, where upstream's is a new error named after the cause's code;
  • the outputs file is written once, however the deployment ends, a file that can't be written is joined with the deployment's error, and two selected stacks with one name are refused before anything is deployed, where upstream writes the file after each stack, replaces the deployment's error with the file's, and writes the outputs of whichever of the two finished last;
  • every message of a rollback the deployment performs first carries the deploy action, where upstream's work sends its own with the rollback action;
  • a stack's span ends when it fails, and an asset's when its build or publish fails, where upstream's are left open;
  • a replacement in a deployment with rollback disabled executes the change set approved again, with rollback enabled, where upstream removes it and executes a new one nobody approved;
  • a stack with no resources is deleted polling at the deployment's interval, where upstream polls at the defaults;
  • leaving out the assets published already follows each environment's cross-account rule, so that an object in another account's bucket isn't taken as published where that is forbidden, where upstream's check reads no rule.

Rollback

Toolkit.Rollback rolls back the selected stacks, one at a time, that a failed deployment left paused, or whose rollback failed, as cdk rollback does, with the stacks' deploy roles and execution roles. It departs from upstream where upstream is wrong:

  • a failure returns the stacks rolled back until then beside the error, where upstream returns none;
  • each stack's environment is resolved, where upstream's is the manifest's;
  • the polling interval is an option, where upstream always polls at its defaults;
  • a stack's span ends when it fails, where upstream's is left open.

Destroy

Toolkit.Destroy deletes the selected stacks, each after the stacks that depend on it, as cdk destroy does, with the stacks' deploy roles and execution roles, so that it can destroy what either tool deployed. It departs from upstream where upstream is wrong:

  • declining the confirmation is an error of cdkerr.KindAborted, as the CDK CLI makes it, where upstream's library returns success with no stacks;
  • a negative concurrency is refused, where upstream's run never settles;
  • a failure returns the stacks destroyed until then beside every stack's error, where upstream rejects with the last error only;
  • each destroyed stack's environment is resolved, where upstream's is the manifest's, unknown for an environment-agnostic stack;
  • only a deletion that fails is cdkerr.KindDeployment; an AWS error, such as a refused DeleteStack for a stack with termination protection, is returned as it is, where upstream wraps every error as a failed destroy;
  • a stack's span ends when it fails, where upstream's is left open.

Drift

Toolkit.Drift checks the selected stacks, one at a time, for drift, as cdk drift does, with CloudFormation's drift detection and the base credentials for each stack's environment, assuming no role, as upstream does. Its formatted sections carry no colour: ADR 0001's translation of coloured strings inside results into structured results, rendered separately, applied (K.5-D4). Every page of each stack's drift records is read, as upstream reads them since toolkit-lib 1.44.0 (K.5-D1). It departs from upstream where upstream is wrong, where Go idiom differs, or where an approved rule applies:

  • the result is a slice of the stacks in the order they were selected, where upstream's is an object keyed by display name, and each entry carries the stack's name, its environment, resolved, and its drift records, besides upstream's counts and sections (K.5-D2, K.5-D3);
  • a failure returns the stacks checked until then beside the error, as rollback's does, where upstream returns none (K.5-D5);
  • a stack's error names the stack, where upstream's doesn't say which stack failed (K.5-D6);
  • the span ends when the checks fail, where upstream's is left open (K.3-D10).

Publish assets

Toolkit.PublishAssets builds and publishes the file assets and container images of the selected stacks' asset manifests, without deploying the stacks, as cdk publish-assets does, with each destination's role and the cross-account rule of each stack's environment, so that either tool finds published what the other published. It leaves out the destinations that have their assets already, unless forced, and ignores a stack's CDK v1 metadata assets, as upstream does. The glue between the work graph's asset nodes and the publisher is shared with deploy's asset publishing (H.5-D3). It departs from upstream where upstream is wrong, or where an approved rule applies:

  • it runs for every caller, where upstream refuses it unless the toolkit enables the unstable feature publish-assets, since this toolkit has no list of unstable features (H.5-D2);
  • a negative concurrency is refused, and zero means 4, where upstream's run never settles for either (I.1-D4);
  • a failure returns the assets published until then beside every asset's error, where upstream rejects with the last error only and returns none (H.5-D4);
  • leaving out the destinations that have their assets already follows each environment's cross-account rule, read from its toolkit stack, so that an object in another account's bucket isn't taken as published where that is forbidden, where upstream's check reads no rule and takes it as published (H.2-D5);
  • an asset's span ends when its build or publish fails, where upstream's is left open (K.3-D10).

Validate

Toolkit.Validate returns the selected stacks' validation report, as cdk validate does: the app's own report and the stacks' annotations, which synth and deploy enforce, here returned rather than failing the action, and, unless ValidateOptions says Offline, CloudFormation's early validation of each stack. The zero options validate online, as upstream's default does, so Validate with no options reaches AWS, and creates and deletes a change set in every selected stack's account, through its deploy role (M.10-D1). An app writes its validation report despite errors only when it is synthesized with the context value @aws-cdk/core:failSynthOnValidationErrors false, which the CLI sets for cdk validate and a caller sets in its source's context.

Online validation creates a change set for each stack, publishing its template first, as deploy does (M.10-D5); it never executes the change set, and deletes it again, with the stack it created, as upstream's validation does, keeping a stack that existed before in any state (M.10-D3). The change set's preparation is shared with the diff's change set, Toolkit.Diff (M.10-D2). An error in one stack's online validation is a warning, CDK_TOOLKIT_W9602, and the next stack is validated, as upstream's is. It departs from upstream where upstream is wrong:

  • the change set gets the parameters a deployment would send, every deployed value kept and the template's defaults for the rest, where upstream's gets the defaults alone, so that an existing stack is validated with its defaults, and one with a parameter without a default can't be validated online at all (M.10-D4);
  • an error from the host while a stack is validated online fails the action, as in every other action, where upstream's becomes CDK_TOOLKIT_W9602, sent to the same host (M.10-D7);
  • a template too large to pass directly, of a stack without a template asset, is uploaded to the staging bucket before the change set is created, where upstream adds it to an asset manifest it discards, so that the change set names an object never uploaded and the stack can't be validated online;
  • a violation's template path is the stack's template file, where upstream's is "<stack name>.template.json", which names no file for a stack in a stage (M.10-D8).

It departs from upstream where Go idiom differs: cancelling the context stops the action with an error and no result, after deleting the change set in progress, where upstream can't be cancelled, and a report cut short would conclude in a success it hasn't established (M.10-D6).

Orphan

Toolkit.Orphan detaches the resources under construct paths from their stack without deleting them, as cdk orphan does, a feature upstream marks unstable, in up to three change-set deployments of the stack's deployed template: one that resolves the resources' attributes through temporary outputs, one that sets Retain on them and replaces every reference to them with its value, and one that removes them. Nothing is removed until the second deployment has set Retain and succeeded, and no step starts once one has failed, as upstream orders them. Each step is a change-set deployment as deploy makes one (M.5-D2), so a failed step rolls back, and its error carries the deployment's diagnosis.

What a failure leaves, which upstream doesn't say:

  • a failed step 1 or step 2 rolls the stack back to what it was before that step, which after step 1 holds at most step 1's temporary outputs, CdkOrphan<logical ID><attribute>, until the next deployment of the app removes them;
  • a failed step 3 leaves the resources in the stack, retained and decoupled; running the action again completes it, since its plan finds them, and step 1 finds nothing left to resolve;
  • a cancellation stops the action before the next step starts, with the stack as the last finished step left it.

It fixes upstream defects, as the owner approved (#97):

  • a stack whose creation failed, ROLLBACK_COMPLETE or ROLLBACK_FAILED, is refused after the plan, before CDK_TOOLKIT_I8810 and before anything changes, since there is nothing to orphan, where upstream's first step deletes it and creates it afresh from the deployed template, as every deployment does (M.5-D4);
  • each step sends the parameters the template it deploys declares, each keeping its deployed value, where upstream's are those the app's template declares, so a parameter only the deployed template declares takes its default, updating what reads it, and one only the app's declares makes the step fail (M.5-D3);
  • a resolved value written into an Fn::Sub string is written as it is, where upstream's is read as a JavaScript replacement pattern, so "$&", "$$", "$`" and "$'" in it are substituted (M.5-D5);
  • a construct path names the resource at the path itself as well as those below it, and paths that overlap list each resource once, where upstream's names only those below it, so an L1 construct's path matches nothing, and lists a resource once for each path (M.5-D6).

It departs from upstream where Go idiom differs, or where an approved rule applies:

  • the result names the stack, the resources orphaned and the mapping an import of them needs, where upstream's returns nothing and writes the mapping into its final message only (M.5-D1);
  • it runs for every caller, where upstream refuses it unless the toolkit enables the unstable feature orphan, since this toolkit has no list of unstable features (K.1-D6);
  • OrphanOptions has no toolkit stack name option, where upstream's has one that deployStack never reads, so that upstream's steps always read the toolkit's bootstrap stack, as these do, named by Options.ToolkitStackName;
  • the role option is documented as CloudFormation's execution role, which is what upstream passes it as, where upstream documents it as a role to assume (M.5-D7);
  • a step's error is "orphan step <n>: " and its cause, which errors.As finds, such as the deployment's error and its diagnosis (M.5-D9);
  • cancelling the context stops the action between steps, and once step 3 has finished the result is returned beside the error, where upstream can't be cancelled (M.5-D9);
  • an attribute named by anything but a string, such as Fn::GetAtt's dynamic form, isn't resolved.

Diff

Toolkit.Diff diffs each selected stack's new template against its deployed one, with its CDK-managed nested stacks', or against a template file, as cdk diff does: with a change set CloudFormation computes and the toolkit deletes again, falling back to the templates alone when it can't be created, or with the templates alone, or against a local file, without reaching AWS (J.6-D1). The change set is created as a deployment's would be, through the stack's deploy role, after its templates are published as its asset manifests publish them, and the change sets CloudFormation creates for its nested stacks are used for theirs; its preparation is shared with online validation's (M.10-D2). The diffs are rendered by cfndiff's Format and FormatSecurity, without colour, as every toolkit message is; a host that wants colour renders the payload's diffs itself (J.6-D11). The diffs in the result and the payloads encode as JSON, with encoding/json or encoding/json/v2, as cfndiff's TemplateDiff says, so that a host can forward them. Each stack's entry lists the destructive changes of the diffs shown, its nested stacks' included: the resources they replace, may replace, destroy or orphan, without the AWS::CDK::Metadata resource, as upstream's do, and so does the deploy approval's payload (CDK_TOOLKIT_I5060). With DiffOptions.IncludeMoves, each added or removed resource that is one end of a move between the deployed stacks and the selected ones, as upstream's refactor command detects moves, carries the move, which the text shows as "(OR move from <stack>.<logical ID> via refactoring)" or "(OR move to …)"; nested stacks get their root's moves, which never name them, as upstream's do. The deployed stacks are listed and read with the base credentials of each environment and no role, as upstream's are, so the diff fails for an environment those credentials aren't for, as it does for any other failure to detect the moves. It departs from upstream where upstream is wrong, or where Go idiom differs (#76):

  • the result, and the payloads, hold the diffs as a tree of each stack and its nested stacks, in selection order, where upstream's is one map by name, in which names collide (J.6-D2);
  • each nested stack's diff is computed and shown for itself, where upstream caches diffs by name, so two undeployed nested stacks with one logical ID under different parents both show the first one's (J.6-D3);
  • only the CheckBootstrapVersion rule is hidden from a diff that isn't strict, where upstream hides every change to Rules beside it, so that cdk diff omits a changed rule and counts the stack as unchanged (J.6-D4);
  • the re-diff that hides likely mangled characters keeps the import marking, and the diffs returned are those shown, where upstream's re-diff drops the import, and its result keeps the unfiltered, unmangled diff (J.6-D5);
  • the change set is cleaned up as a deployment's is, so that a REVIEW_IN_PROGRESS stack holding change sets someone prepared is kept, where upstream deletes it with them (J.6-D7);
  • the change sets CloudFormation created for nested stacks are described before the stack's change set is deleted, since deleting it deletes them, where upstream deletes it first, so that its nested descriptions race the deletion and can find them gone (J.6-D13);
  • the change set gets the parameters a deployment with the same StackParameters would send, deployed values kept by default, where upstream's gets the template's defaults, so that a parameter deployed with another value shows as changing back, and one without a default makes the change set fail (J.6-D8);
  • FormattedDiff.Security is the security diff, empty without security changes, where upstream's is the whole diff (J.6-D10);
  • the span ends when the diff fails, where upstream's is left open (K.3-D10);
  • a cancelled context stops the diff, after deleting the change set in progress, where upstream can't be cancelled, and a change set cut short by the cancellation doesn't fall back to the templates; one CloudFormation is still computing is left, with a warning naming it, as the Cancellation section says;
  • a change set that can't be deleted is a warning naming what is left, as a deployment's is, where upstream's error is hidden by the fallback to the templates;
  • with IncludeMoves, an environment-agnostic stack's moves are found, by its resolved environment, where upstream looks them up by the manifest's environment, which is never the one they are found in;
  • with IncludeMoves, a resource's location is its stack's CloudFormation name and its logical ID, as the moves name it, where upstream's uses the display name, so that a stack in a stage or with its own stack name never has its moves marked; the header still shows the display name.

A stack without a template asset whose template is too large to pass directly has it uploaded to the staging bucket before its change set is created, as a deployment's is, and so does online validation's, where upstream adds it to an asset manifest it discards, so that the change set names an object never uploaded, fails, and the diff falls back to the templates. It doesn't read migrate.json, which upstream's reads to diff the resources it names as an import.

Hotswap

HotswapDeployment deploys a stack's changes by updating the affected resources through their own APIs instead of through CloudFormation, as cdk deploy --hotswap and --hotswap-fallback do, for development only: the stack drifts from its template until a deployment through CloudFormation with --revert-drift reconciles it. The stack's synthesized template is diffed against the templates deployed, nested stacks' included, or against the CDK CLI's hotswap template cache in the assembly's directory when a hotswap deployed last, which it reads and writes as the CLI does, so that either tool picks up where the other left off (M.1-D8). A Lambda function's changed Code, Environment or Description is updated through Lambda, each update waited for, for at most 600 s, until the function has finished updating; a version referring to the function is then published, and each alias referring to such a version updated to it. An S3 bucket deployment's change is applied by invoking its handler with the event CloudFormation would send, and a change to an IAM policy used only by bucket deployments' handlers is ignored. Changed resources of the types upstream hotswaps through Cloud Control are updated by a JSON patch of their changed properties, except their create-only ones; changed outputs, resources created, deleted or retyped, and resources of other types can't be hotswapped. An ECS task definition's changed ContainerDefinitions are registered as a new revision, and each ECS service that refers to it is updated to the revision with a forced new deployment and waited for until it is stable, as HotswapDeployment's ECS properties set. An AppSync resolver's, function's or schema's changed mapping templates, code or definition, inline or in S3, and an API key's expiry are updated through AppSync, and a schema's creation waited for. A CodeBuild project's changed Source, Environment or SourceVersion is updated through CodeBuild. The template's values are decoded into the services' typed inputs, matched by name ignoring case, and a value whose type doesn't fit fails its update before it is sent. With a fallback, any change that can't be hotswapped deploys the stack through the fallback instead; without one, such changes are listed, skipped and left undeployed, and the synthesized templates are written to the cache all the same, as upstream writes them (M.1-D9). The deployment is the HOTSWAP span, CDK_TOOLKIT_I5400 to CDK_TOOLKIT_I5410, with the plan in CDK_TOOLKIT_I5401, and CDK_TOOLKIT_I5402 and CDK_TOOLKIT_I5403 around each update. A wait that times out, or whose resource reports a failed update, fails the stack with Code "HotswapWaiterFailed".

It departs from upstream where upstream is wrong:

  • each Cloud Control update is waited for until it succeeds, bounded only by the context, and one that fails or is cancelled fails the stack with Code "HotswapFailed", where upstream reports success once the update is accepted, and never reports one that fails (M.1-D6);
  • each update's calls carry its own user agent, cdk-hotswap/success-<service>, where upstream adds it to the client every update shares, so that updates running at once carry each other's (M.1-D12);
  • every update runs to its end before the stack fails, where upstream fails at the first error while the others carry on unwatched;
  • a changed nested stack that isn't CDK-managed, one without aws:asset:path metadata, can't be hotswapped, where upstream fails reading it;
  • the HOTSWAP span ends, with the error, when the deployment fails before applying any update, such as on a template expression that can't be evaluated, where upstream leaves it open;
  • a Lambda function whose update failed, or an ECS service that is missing, draining or inactive, fails the stack with Code "HotswapWaiterFailed", where upstream's error has no code and its message is the waiter's result as JSON;
  • an ECS task definition whose family can't be found, in the template or among the deployed resources, can't be hotswapped, so fall-back mode deploys it through CloudFormation, where upstream fails the stack with a TypeError.

A deployment through CloudFormation deletes the cache only once a change set is executed, or a direct deployment changes the stack, where upstream deletes it when the deployment starts, before approval (G.6-D5). So after a hotswap is reverted in the app, a deployment whose change set is empty keeps the cache, since the resources are still as the hotswap left them, and the next deployment isn't skipped either, until one deploys through CloudFormation with --revert-drift or changes the stack.

Cancelling the context stops the waits, and the deployment, with no cache written and no fallback started; an update already sent goes on.

Example

A toolkit runs an action on the cloud assembly a source produces, and sends what the action does to its host. Here the host writes warnings, errors and results to standard output, the source is a cloud assembly already on disk, and the action lists the app's stacks, which is its result.

package main

import (
	"context"
	"log"
	"os"

	"github.com/asteroid-computing/aws-cdk-toolkit/iohost"
	"github.com/asteroid-computing/aws-cdk-toolkit/iohost/console"
	"github.com/asteroid-computing/aws-cdk-toolkit/toolkit"
)

func main() {
	ctx := context.Background()

	tk, err := toolkit.New(toolkit.Options{
		Host: &console.NonInteractive{Stdout: os.Stdout, Stderr: os.Stdout, Level: iohost.LevelWarn},
	})
	if err != nil {
		log.Fatal(err)
	}

	src := toolkit.FromAssemblyDirectory("testdata/example/cdk.out", toolkit.AssemblyDirectoryOptions{})
	if _, err := tk.List(ctx, src, toolkit.ListOptions{}); err != nil {
		log.Fatal(err)
	}
}
Output:
Network
Service

Index

Examples

Constants

View Source
const TransientContextKey = "$dontSaveContext"

TransientContextKey marks a context value that must not be saved: a value that is an object whose member of this name is truthy is returned by ContextStore.Read but never written to a file. Context providers return their errors as such values.

Variables

This section is empty.

Functions

This section is empty.

Types

type AWSOptions

type AWSOptions struct {
	// Profile is the shared config profile to use, which beats credentials in the environment; empty means the default resolution, which honours AWS_PROFILE.
	Profile string

	// Region overrides the resolved region.
	// When no region is configured anywhere, the toolkit uses us-east-1, as the CDK CLI does.
	Region string

	// Config, when set, is used instead of the default resolution: upstream's BaseCredentials.custom.
	// The toolkit's own client settings still apply to a copy of it: its retries, its user agent, and the logging of SDK calls to the host.
	Config *aws.Config

	// HTTPClient is the client every AWS call goes through, for proxies, CA bundles and timeouts; nil means the SDK's default, which honours HTTPS_PROXY, NO_PROXY and AWS_CA_BUNDLE.
	HTTPClient aws.HTTPClient

	// AccountCacheFile, when set, caches the default account by access key ID, in the CDK CLI's format, so a short-lived process saves an STS call.
	// The CDK CLI uses ~/.cdk/cache/accounts_partitions.json; the toolkit uses no file unless it is named here.
	AccountCacheFile string

	// CredentialPlugins supply credentials for accounts the default credentials aren't for, asked in order; see [CredentialPlugin].
	CredentialPlugins []CredentialPlugin
}

AWSOptions say how the toolkit reaches AWS: upstream's SdkConfig. The zero value resolves credentials and region as the AWS CLI and the CDK CLI do.

The toolkit makes no AWS call until an action needs one, such as to give a CDK app its default account or to look up context.

type AppContextOptions

type AppContextOptions struct {
	// CommandLine is context that overrides every file, such as the CLI's --context values.
	// It is never saved.
	CommandLine map[string]jsontext.Value

	// UserFile is the user's own settings file, whose "context" member applies under every other source.
	// The CLI reads ~/.cdk.json; this store reads no such file unless it is named here, because the toolkit never looks up the home directory itself.
	UserFile string
}

AppContextOptions are the options for AppContext.

type AppSynthOptions

type AppSynthOptions struct {
	// Debug sets CDK_DEBUG, so the app records more, such as the stack traces that created tokens, and runs slower.
	// It also sets JSII_HOST_STACK_TRACES=1, unless the app's environment sets it already.
	Debug bool

	// DisablePathMetadata leaves out the aws:cdk:path metadata of each resource in the templates.
	DisablePathMetadata bool

	// DisableVersionReporting turns off the reporting of the library versions an app uses.
	DisableVersionReporting bool

	// DisableAssetMetadata leaves out the aws:asset:* metadata of resources that use assets.
	DisableAssetMetadata bool

	// DisableAssetStaging turns off copying assets into the output directory; their metadata then holds absolute paths.
	DisableAssetStaging bool

	// DisableValidation sets CDK_VALIDATION=false, so the app skips its own validation of the stacks.
	DisableValidation bool

	// BundlingStacks are patterns for the stacks whose assets are bundled; empty means every stack.
	BundlingStacks []string
}

AppSynthOptions are the settings an app is synthesized with, which reach it through context and environment variables: upstream's AppSynthOptions. The zero value is upstream's default.

type Assembly

type Assembly struct {
	*cloudassembly.Assembly
	// contains filtered or unexported fields
}

Assembly is a cloud assembly a Source produced, which Toolkit.Synth returns: upstream's CachedCloudAssembly. It holds a read lock on its directory, so that nothing synthesizes into the directory while it is in use, until Close.

An Assembly is itself a Source, so other actions can work on what Synth produced without synthesizing again. Those actions borrow it: they never close it, and closing it while one is using it is a bug in the caller. An action given an Assembly that is already closed fails.

func (*Assembly) Close

func (a *Assembly) Close() error

Close releases the assembly's lock, and removes its directory if it was a temporary one. Closing again does nothing.

type AssemblyBuilder

type AssemblyBuilder func(ctx context.Context, p BuilderProps) (dir string, err error)

AssemblyBuilder synthesizes a CDK app in process, as an aws-cdk-go app does with awscdk.NewApp and App.Synth, and returns the directory it wrote the cloud assembly to.

It must pass p.Outdir and p.Context to the app, as awscdk.AppProps's Outdir and Context, because the toolkit does not set them in the process's environment. A cdkerr.Error it returns is passed on as it is; any other error is wrapped in one of Kind cdkerr.KindAssembly and Code "AssemblyError". It runs in process, so the toolkit can't stop it: it should watch ctx and return early once ctx is done, as upstream's builder watches its abort signal. One that returns successfully once ctx is done fails all the same, as upstream's does, with an error of Kind cdkerr.KindAssembly and Code "AssemblyError" wrapping ctx.Err(), the shape of a cancelled synthesis under G.10-D2, where upstream rethrows a bare AbortError. It isn't called for a round of synthesis that would start once ctx is done; producing then fails with the bare ctx.Err().

type AssemblyBuilderOptions

type AssemblyBuilderOptions struct {
	// Outdir is the directory the builder synthesizes into; empty means a new temporary directory, which is removed when the assembly is closed.
	Outdir string

	// DisposeOutdir removes Outdir when the assembly is closed.
	DisposeOutdir bool

	// ContextStore holds the app's context; nil means a MemoryContext of the source's own, which starts empty and keeps the values lookups find for as long as the source is used.
	ContextStore ContextStore

	// DisableLookups fails a synthesis that needs context the store lacks, rather than looking it up and building again.
	DisableLookups bool

	// DisableDefaultEnvironment leaves CDK_DEFAULT_REGION and CDK_DEFAULT_ACCOUNT out of [BuilderProps].Env, and saves the STS call that finds the account: upstream's resolveDefaultEnvironment false.
	DisableDefaultEnvironment bool

	// SkipVersionCheck loads an assembly whose schema version is newer than this module reads.
	SkipVersionCheck bool

	Synth AppSynthOptions
}

AssemblyBuilderOptions are the options for FromAssemblyBuilder. The zero value is upstream's default.

type AssemblyDirectoryOptions

type AssemblyDirectoryOptions struct {
	// SkipVersionCheck loads an assembly whose schema version is newer than this module reads, which it may then not fully understand.
	SkipVersionCheck bool

	// AllowMissingContext accepts an assembly whose manifest still lists missing context, which would otherwise fail.
	AllowMissingContext bool
}

AssemblyDirectoryOptions are the options for FromAssemblyDirectory. The zero value is upstream's default.

type AssetBuildTime

type AssetBuildTime int

AssetBuildTime is when Toolkit.Deploy builds the assets: upstream's AssetBuildTime.

const (
	// AssetBuildAllBeforeDeploy builds every asset before any stack is deployed, so that a failed build fails the deployment before it changes anything: upstream's ALL_BEFORE_DEPLOY, its default.
	AssetBuildAllBeforeDeploy AssetBuildTime = iota

	// AssetBuildJustInTime builds each asset once the stacks its stack depends on are deployed, just before its stack needs it: upstream's JUST_IN_TIME.
	AssetBuildJustInTime
)

type BootstrapEnvironments

type BootstrapEnvironments struct {
	// contains filtered or unexported fields
}

BootstrapEnvironments are the environments Toolkit.Bootstrap bootstraps: upstream's BootstrapEnvironments. Make them with BootstrapEnvironmentsFromList or BootstrapEnvironmentsFromSource.

func BootstrapEnvironmentsFromList

func BootstrapEnvironmentsFromList(envs ...string) (BootstrapEnvironments, error)

BootstrapEnvironmentsFromList returns the environments named, each in the form aws://<account>/<region>, or <account>/<region>. The account or region may be unknown-account or unknown-region, which bootstrapping resolves to the default account or region.

It fails with a cdkerr.KindToolkit error with Code "InvalidEnvironmentFormat" for a name in another form.

func BootstrapEnvironmentsFromSource

func BootstrapEnvironmentsFromSource(src Source) BootstrapEnvironments

BootstrapEnvironmentsFromSource returns the environments of every stack in the cloud assembly src produces, which it produces when Toolkit.Bootstrap is called. An environment that several stacks share is bootstrapped once, where upstream bootstraps it once for each stack, concurrently.

type BootstrapOptions

type BootstrapOptions struct {
	// Parameters are the bootstrap template's parameters; the zero value keeps every deployed value.
	Parameters BootstrapStackParameters

	// TemplateFile is a bootstrap template of one's own, in YAML or JSON; empty means the template the CDK CLI at the pinned commit deploys.
	// A template without a bootstrap version is a legacy template, which the toolkit can't deploy (EE-3).
	TemplateFile string

	// NoExecute creates the change set and leaves it for someone to execute: upstream's execute false.
	NoExecute bool

	// Tags are the bootstrap stack's tags.
	Tags []Tag

	// TerminationProtection, when set, turns the bootstrap stack's termination protection on or off; nil keeps the deployed stack's, or off for a new stack.
	TerminationProtection *bool

	// ForceDeployment deploys over a bootstrap stack of another variant, or of a higher version, which bootstrapping otherwise leaves alone.
	ForceDeployment bool

	// Express deploys in CloudFormation's express mode.
	Express bool
}

BootstrapOptions are the options for Toolkit.Bootstrap. The zero value is upstream's default.

type BootstrapParameters

type BootstrapParameters struct {
	// BucketName is the name of the staging bucket; empty means one the template generates.
	BucketName string

	// KMSKeyID is the KMS key that encrypts the staging bucket.
	KMSKeyID string

	// CreateCustomerMasterKey, when set, creates a customer managed key for the staging bucket, or uses the AWS managed key; nil keeps the deployed stack's choice, or the AWS managed key for a new stack.
	// It can't be set with KMSKeyID.
	CreateCustomerMasterKey *bool

	// TrustedAccounts may deploy to the environment, and TrustedAccountsForLookup may look values up in it.
	TrustedAccounts          []string
	TrustedAccountsForLookup []string

	// UntrustedAccounts are removed from the trusted accounts.
	UntrustedAccounts []string

	// CloudFormationExecutionPolicies are the ARNs of the managed policies CloudFormation deploys with; they are required with TrustedAccounts.
	CloudFormationExecutionPolicies []string

	// Qualifier tells apart several bootstrap stacks in one environment; empty means the deployed stack's, or the template's default.
	Qualifier string

	// NoPublicAccessBlockConfiguration turns off the staging bucket's public access block, which is on unless this is set: upstream's publicAccessBlockConfiguration false.
	NoPublicAccessBlockConfiguration bool

	// ExamplePermissionsBoundary applies the example permissions boundary, cdk-<qualifier>-permissions-boundary, to the bootstrap roles, creating it if it doesn't exist.
	// The boundary created is upstream's, which denies creating roles and users without the boundary, as the bootstrap template's copy of it does (E.2-D3).
	ExamplePermissionsBoundary bool

	// CustomPermissionsBoundary is the name of a permissions boundary of one's own to apply to the bootstrap roles.
	CustomPermissionsBoundary string

	// ApplyPermissionsBoundaryToAllRoles, when set, applies the permissions boundary to every bootstrap role, not only the CloudFormation execution role, or to that one alone; nil keeps the deployed stack's choice, except that [ExactParameters] resets it to the template's default, off, as upstream's exactly does; a new stack takes that default too.
	// Setting it, either way, needs a template that declares the ApplyPermissionsBoundaryToAllRoles parameter, as bootstrap templates from version 33 do; with one that doesn't, bootstrapping fails with a [cdkerr.KindToolkit] error with Code "PermissionsBoundaryAllRolesNotSupported", before any boundary is created.
	// Turned on with no boundary given, and none deployed or the deployed one dropped by [ExactParameters], it has no effect, and bootstrapping warns so.
	ApplyPermissionsBoundaryToAllRoles *bool
}

BootstrapParameters are the bootstrap template's parameters that bootstrapping sets: upstream's BootstrapParameters. A nil list leaves the deployed stack's value as it is, where an empty one sets none.

type BootstrapResult

type BootstrapResult struct {
	// Environments are the environments bootstrapped, in the order given.
	Environments []EnvironmentBootstrapResult

	// Duration is how long bootstrapping took.
	Duration time.Duration
}

BootstrapResult is what Toolkit.Bootstrap did: upstream's BootstrapResult.

type BootstrapStackParameters

type BootstrapStackParameters struct {
	// contains filtered or unexported fields
}

BootstrapStackParameters say which parameters bootstrapping sets, and what happens to the others: upstream's BootstrapStackParameters. The zero value sets none, and keeps every deployed value, as OnlyExistingParameters.

func ExactParameters

ExactParameters sets p, and gives every other parameter the template's default: upstream's exactly.

func OnlyExistingParameters

func OnlyExistingParameters() BootstrapStackParameters

OnlyExistingParameters keeps every deployed value: upstream's onlyExisting.

func ParametersWithExisting

func ParametersWithExisting(p BootstrapParameters) BootstrapStackParameters

ParametersWithExisting sets p, and keeps the deployed values of the others: upstream's withExisting.

type BootstrapStatus

type BootstrapStatus string

BootstrapStatus is what bootstrapping did to an environment.

const (
	// BootstrapSuccess means the bootstrap stack was deployed.
	BootstrapSuccess BootstrapStatus = "success"

	// BootstrapNoOp means nothing changed: the stack was up to date, or of another variant or a higher version.
	BootstrapNoOp BootstrapStatus = "no-op"
)

type BootstrapTemplate

type BootstrapTemplate struct {
	// contains filtered or unexported fields
}

BootstrapTemplate is a bootstrap template, to show: upstream's BootstrapTemplate.

func LoadBootstrapTemplate

func LoadBootstrapTemplate(name string) (*BootstrapTemplate, error)

LoadBootstrapTemplate reads the bootstrap template in the named file, in YAML or JSON, or, when name is empty, the template the CDK CLI at the pinned commit deploys: upstream's BootstrapTemplate.fromSource.

func (*BootstrapTemplate) JSON

func (b *BootstrapTemplate) JSON() (string, error)

JSON returns the template as JSON, indented by two spaces, as the CDK CLI writes it.

func (*BootstrapTemplate) YAML

func (b *BootstrapTemplate) YAML() (string, error)

YAML returns the template as YAML, as the CDK CLI writes it.

type BootstrappedEnvironment

type BootstrappedEnvironment struct {
	Version     int
	Environment cloudassembly.Environment
}

BootstrappedEnvironment is an environment and its bootstrap version, for notices about bootstrap versions: upstream's BootstrappedEnvironment.

type BuilderProps

type BuilderProps struct {
	// Outdir is the directory to synthesize into, which the toolkit holds a write lock on.
	Outdir string

	// Context is the app's context: the context store's, with the synthesis settings' over it.
	Context map[string]any

	// Env holds the environment variables a CDK app run by a toolkit would see on top of the process's own, such as CDK_OUTDIR and those the synthesis settings call for.
	Env map[string]string
}

BuilderProps are what an AssemblyBuilder synthesizes with: upstream's AssemblyBuilderProps.

type CdkAppOptions

type CdkAppOptions struct {
	// WorkingDir is the app's directory, which it runs in; empty means the process's directory.
	WorkingDir string

	// Outdir is the directory the app synthesizes into; empty means WorkingDir/cdk.out.
	// A relative Outdir is relative to the process's directory, as upstream resolves it.
	Outdir string

	// DisposeOutdir removes Outdir when the assembly is closed.
	DisposeOutdir bool

	// Env holds environment variables to set for the app.
	// The app also inherits the process's environment, which it needs for PATH, HOME and AWS credentials; ADR 0001 names this as one of the two places the toolkit reads process globals, with AWS credential resolution.
	// Env overrides the CDK_DEFAULT_REGION and CDK_DEFAULT_ACCOUNT the toolkit sets.
	Env map[string]string

	// UnsetEnv names environment variables of the process's that the app must not see.
	UnsetEnv []string

	// ContextStore holds the app's context; nil means AppContext(WorkingDir), as the CLI keeps it.
	ContextStore ContextStore

	// DisableLookups fails a synthesis that needs context the store lacks, rather than looking it up and synthesizing again.
	DisableLookups bool

	// DisableDefaultEnvironment leaves out CDK_DEFAULT_REGION and CDK_DEFAULT_ACCOUNT, which otherwise give the app the default region and account of the toolkit's AWS access, and saves the STS call that finds the account: upstream's resolveDefaultEnvironment false.
	DisableDefaultEnvironment bool

	// SkipVersionCheck loads an assembly whose schema version is newer than this module reads.
	SkipVersionCheck bool

	Synth AppSynthOptions
}

CdkAppOptions are the options for FromCdkApp. The zero value is upstream's default.

type ChangeSetDeployment

type ChangeSetDeployment struct {
	// Name is the change set's name; empty means cdk-deploy-change-set, the CDK CLI's.
	Name string

	// NoExecute prepares the change set and leaves it for someone to execute: upstream's execute false.
	NoExecute bool

	// ImportExistingResources has CloudFormation import resources that already exist, rather than fail to create them.
	ImportExistingResources bool

	// RevertDrift has CloudFormation bring resources that drifted back to the template.
	RevertDrift bool
}

ChangeSetDeployment deploys a stack through a change set, which is prepared, approved and then executed: upstream's ChangeSetDeployment.

type ChangeSetDiff

type ChangeSetDiff struct {
	// ProcessedTemplate diffs against the deployed template after CloudFormation processed its transforms, rather than the original: upstream's compareAgainstProcessedTemplate.
	ProcessedTemplate bool

	// NoFallback fails with a [cdkerr.KindToolkit] error with Code "ChangeSetCreationFailed" when the change set can't be created, rather than diffing the templates alone: upstream's fallbackToTemplate false, inverted so that the zero value is upstream's default, as ADR 0001 inverts default-true flags (J.6-D1).
	NoFallback bool

	// Parameters are the change set's parameter values, resolved as a deployment with the same parameters resolves them, so that the diff shows what [Toolkit.Deploy] would do; the zero value keeps every deployed value (J.6-D8).
	Parameters StackParameters

	// ImportExistingResources has CloudFormation import resources that already exist, rather than fail to create them.
	ImportExistingResources bool

	// ChangeSetName is the change set's name; empty means a unique name, cdk-diff-change-set-<uuid>.
	ChangeSetName string
}

ChangeSetDiff diffs each stack's deployed template against its new one with a change set, which CloudFormation computes and the toolkit deletes again, for the most accurate replacement information: upstream's DiffMethod.ChangeSet. The change set is created through the stack's deploy role.

type ContextProviderPlugin

type ContextProviderPlugin interface {
	// Value returns the value of the lookup, which the toolkit encodes as JSON and gives the app.
	// An error doesn't fail the synthesis: its message becomes the value, which the app reports and which is never saved.
	Value(ctx context.Context, q ContextQuery) (any, error)
}

ContextProviderPlugin answers the context lookups an app makes with provider "plugin" and this plugin's name: upstream's ContextProviderPlugin, as a Go value in Options.ContextProviderPlugins rather than an npm module loaded by name (Epic C's C.9).

An aws-cdk-go app reaches the plugin registered as "build-info" with a lookup such as:

awscdk.ContextProvider_GetValue(stack, &awscdk.GetContextValueOptions{
	Provider:   jsii.String("plugin"),
	Props:      &map[string]any{"pluginName": "build-info", "component": "web"},
	DummyValue: "dummy",
})

It is experimental upstream, as here.

The toolkit gives a plugin no AWS credentials, as upstream gives its plugins none: a plugin that calls AWS is constructed with the configuration it should use. The toolkit may call a plugin from several goroutines at once, since a Toolkit is safe for concurrent use.

Example

A context-provider plugin answers the lookups an app makes with provider "plugin" and the plugin's name. The builder here stands in for an aws-cdk-go app that makes the lookup shown on toolkit.ContextProviderPlugin with IncludeEnvironment false, so the query names no account or region.

package main

import (
	"context"
	"encoding/json/v2"
	"fmt"
	"log/slog"
	"os"
	"path/filepath"

	"github.com/asteroid-computing/aws-cdk-toolkit/cloudassembly"
	"github.com/asteroid-computing/aws-cdk-toolkit/iohost"
	"github.com/asteroid-computing/aws-cdk-toolkit/toolkit"
)

// buildInfo answers lookups of a component's latest build, as a plugin backed by a build server might.
type buildInfo struct {
	versions map[string]string // versions by component
}

func (b buildInfo) Value(_ context.Context, q toolkit.ContextQuery) (any, error) {
	var props struct {
		Component string `json:"component"`
	}
	if err := json.Unmarshal(q.Props, &props); err != nil {
		return nil, err
	}
	v, ok := b.versions[props.Component]
	if !ok {
		return nil, fmt.Errorf("no build of %q", props.Component)
	}
	return map[string]string{"version": v}, nil
}

// A context-provider plugin answers the lookups an app makes with provider "plugin" and the plugin's name.
// The builder here stands in for an aws-cdk-go app that makes the lookup shown on [toolkit.ContextProviderPlugin] with IncludeEnvironment false, so the query names no account or region.
func main() {
	tk, err := toolkit.New(toolkit.Options{
		Host:                   iohost.NewSlogHost(slog.New(slog.DiscardHandler)),
		ContextProviderPlugins: map[string]toolkit.ContextProviderPlugin{"build-info": buildInfo{versions: map[string]string{"web": "1.2.3"}}},
	})
	if err != nil {
		panic(err)
	}

	const key = "plugin:component=web:pluginName=build-info"
	app := func(_ context.Context, p toolkit.BuilderProps) (string, error) {
		manifest := `{"version": "54.0.0", "artifacts": {}, "missing": [{"key": "` + key + `", "provider": "plugin", "props": {"pluginName": "build-info", "component": "web"}}]}`
		if v, ok := p.Context[key]; ok {
			fmt.Println("the app was sent", v)
			manifest = `{"version": "54.0.0", "artifacts": {}}`
		}
		return p.Outdir, os.WriteFile(filepath.Join(p.Outdir, "manifest.json"), []byte(manifest), 0o644)
	}
	src := toolkit.FromAssemblyBuilder(app, toolkit.AssemblyBuilderOptions{DisableDefaultEnvironment: true})
	a, err := tk.Synth(context.Background(), src, toolkit.SynthOptions{Stacks: cloudassembly.Selector{Strategy: cloudassembly.StrategyAllStacks, AllowEmpty: true}})
	if err != nil {
		panic(err)
	}
	defer a.Close()
}
Output:
the app was sent map[version:1.2.3]

type ContextQuery

type ContextQuery struct {
	// Key is the context key the value is saved under.
	Key string

	// Props is the app's query, a JSON object: what upstream passes to getValue.
	// It holds pluginName, and account, region and lookupRoleArn when the app included its environment, the role's placeholders, such as ${AWS::Partition}, replaced.
	Props jsontext.Value

	// Environment is the query's account and region, resolved, or "?" for each when the query names none.
	Environment cloudassembly.Environment
}

ContextQuery is one lookup a ContextProviderPlugin answers.

type ContextStore

type ContextStore interface {
	// Read returns the context: the stored values, and every update made so far, transient values included.
	Read(ctx context.Context) (map[string]jsontext.Value, error)

	// Update applies updates, in order, and saves them, except for transient values (see [TransientContextKey]).
	Update(ctx context.Context, updates []ContextUpdate) error
}

ContextStore holds the context a CDK app is synthesized with: upstream's IContextStore. Implementations must be safe for concurrent use.

func AppContext

func AppContext(dir string, opts AppContextOptions) ContextStore

AppContext returns the context store of the CDK app in dir, as the CLI keeps it: upstream's CdkAppMultiContext.

Context comes from, highest precedence first:

  1. opts.CommandLine;
  2. the "context" member of dir/cdk.json;
  3. dir/cdk.context.json;
  4. the "context" member of opts.UserFile, when it is set.

Where an object value is under the same key in more than one source, the objects are merged, member by member; other values come whole from the highest source. Updates are written to dir/cdk.context.json, the only source written, exactly as the TypeScript CLI writes it, so the two can take turns without changing the file needlessly. The files are read once, on first use; a missing file counts as empty.

func FileContext

func FileContext(file string) ContextStore

FileContext returns a context store kept in one JSON file: upstream's FileContext. The file is read once, on first use, and a missing file counts as empty. Updates are written to it as AppContext writes cdk.context.json.

func MemoryContext

func MemoryContext(initial map[string]jsontext.Value) ContextStore

MemoryContext returns a context store that is never saved: upstream's MemoryContext.

type ContextUpdate

type ContextUpdate struct {
	Key string

	// Value is the new value, or nil to remove the key.
	Value jsontext.Value
}

ContextUpdate is one change to a ContextStore.

type CredentialPlugin

type CredentialPlugin interface {
	// Name names the plugin in messages.
	Name() string

	// Available reports whether the plugin can be used at all, such as whether its own configuration is present.
	Available(ctx context.Context) (bool, error)

	// CanProvide reports whether the plugin has credentials for the account.
	CanProvide(ctx context.Context, account string) (bool, error)

	// Credentials returns the credentials for the account, for mode.
	// The toolkit caches them, and fetches them again shortly before they expire; static credentials are credentials.StaticCredentialsProvider.
	Credentials(ctx context.Context, account string, mode Mode) (aws.CredentialsProvider, error)
}

CredentialPlugin supplies credentials for accounts the default credentials aren't for: upstream's credential provider plugin, as a Go value rather than an npm module loaded by name (Epic D's D.5).

For each account and mode, the toolkit uses the default credentials when they are for the account; otherwise it asks each plugin in AWSOptions.CredentialPlugins, in order, and uses the first that is available and can provide credentials, keeping that answer, or that none could, for the toolkit's life. An error from Available or CanProvide is reported as CDK_TOOLKIT_W0100 and the plugin skipped; an error from Credentials, or a nil provider, fails the action. When no plugin can, the default credentials are used anyway, as for an account they aren't for, and the error that follows names the plugins.

A user of an npm credential plugin can keep it by running it as a credential_process in their AWS profile, which the toolkit's default credential resolution honours.

Example

A credential plugin supplies credentials for accounts the default credentials aren't for. An npm credential plugin can instead be run as a credential_process in an AWS profile, which the toolkit's default resolution honours:

[profile deploy]
credential_process = /usr/local/bin/my-credential-helper --account 123456789012
package main

import (
	"context"
	"os"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/credentials"

	"github.com/asteroid-computing/aws-cdk-toolkit/toolkit"
)

// vaultPlugin gives credentials for the accounts its environment names, as a credential plugin backed by a secrets store might.
type vaultPlugin struct {
	accounts map[string]string // access key IDs by account
}

func (vaultPlugin) Name() string { return "vault" }

func (vaultPlugin) Available(context.Context) (bool, error) {
	return os.Getenv("VAULT_ADDR") != "", nil
}

func (v vaultPlugin) CanProvide(_ context.Context, account string) (bool, error) {
	_, ok := v.accounts[account]
	return ok, nil
}

func (v vaultPlugin) Credentials(_ context.Context, account string, mode toolkit.Mode) (aws.CredentialsProvider, error) {
	// A real plugin would fetch short-lived credentials here, perhaps read-only ones for toolkit.ForReading.
	return credentials.NewStaticCredentialsProvider(v.accounts[account], "secret", ""), nil
}

// A credential plugin supplies credentials for accounts the default credentials aren't for.
// An npm credential plugin can instead be run as a credential_process in an AWS profile, which the toolkit's default resolution honours:
//
//	[profile deploy]
//	credential_process = /usr/local/bin/my-credential-helper --account 123456789012
func main() {
	tk, err := toolkit.New(toolkit.Options{
		AWS: toolkit.AWSOptions{
			CredentialPlugins: []toolkit.CredentialPlugin{vaultPlugin{accounts: map[string]string{"123456789012": "AKIAEXAMPLE"}}},
		},
	})
	if err != nil {
		panic(err)
	}
	_ = tk
}

type DeployOptions

type DeployOptions struct {
	// Stacks selects the stacks to deploy; the zero Selector selects every stack, those in nested assemblies included, with no expansion.
	// cdk deploy adds the stacks the ones named depend on, ExpandUpstream, which the default doesn't.
	Stacks cloudassembly.Selector

	// Method is how each stack is deployed: [*ChangeSetDeployment], [*DirectDeployment], [*ExecuteChangeSetDeployment] or [*HotswapDeployment]; nil means a change set, prepared and then executed, as cdk deploy does (EG-3).
	Method DeploymentMethod

	// RoleARN is the role CloudFormation deploys the stacks with, in place of each stack's execution role; placeholders such as ${AWS::AccountId} are replaced.
	RoleARN string

	// Force deploys a stack even when nothing changed: upstream's forceDeployment.
	Force bool

	// Rollback is whether a failed deployment rolls back.
	Rollback RollbackMode

	// OrphanFailedResourcesDuringRollback skips the resources that fail a rollback the deployment performs first, of a stack paused in a failed state: upstream's orphanFailedResourcesDuringRollback.
	// Upstream documents it as having no effect when rollback is off, but a stack paused in a failed state whose change set replaces a resource is rolled back first whatever the setting, and the option applies to that rollback too (K.3-D7).
	OrphanFailedResourcesDuringRollback bool

	// Concurrency is how many stacks are deployed at once; zero means 1, and a negative value is refused (G.8-D5).
	Concurrency int

	// Express deploys the stacks in CloudFormation's express mode.
	Express bool

	// StackEventPollingInterval is how long to wait between reads of a stack's events, and of its status; zero means each one's default, 2 s and 5 s.
	StackEventPollingInterval time.Duration

	// NotificationARNs are SNS topics to notify of the stacks' events, before each stack's own.
	NotificationARNs []string

	// ManageNotificationARNs sets each stack's topics to NotificationARNs and the stack's own even when both are empty, which removes every topic; otherwise a stack with neither keeps the topics it has (G.5-D4).
	ManageNotificationARNs bool

	// Parameters are the stacks' parameter values; the zero value keeps every deployed value (G.5-D2).
	Parameters StackParameters

	// Tags are the stacks' tags, in place of each stack's own (EG-7).
	Tags []Tag

	// OutputsFile, when set, is where the outputs of the stacks deployed are written, as JSON, in the format of the CDK CLI's --outputs-file (G.11).
	// The file is written once, when Deploy returns, however it returns, once the stacks are selected, with the outputs of the stacks that deployed.
	OutputsFile string

	// ForceAssetPublishing publishes every file asset, even those whose destinations have them already, without checking first: upstream's forceAssetPublishing.
	// A container image whose repository has its tag is still left as it is, as upstream's is, since the bootstrap repository's tags are immutable.
	ForceAssetPublishing bool

	// NoAssetParallelism builds and publishes one asset at a time: upstream's assetParallelism false.
	// Otherwise AssetBuildConcurrency assets are built at once, and 8 published at once, as upstream's are.
	NoAssetParallelism bool

	// AssetBuildConcurrency is how many assets are built at once, unless NoAssetParallelism is set; zero means 1, and a negative value is refused (I.1-D4).
	AssetBuildConcurrency int

	// AssetBuildTime is when the assets are built; the zero value builds every asset before any stack is deployed.
	AssetBuildTime AssetBuildTime
}

DeployOptions are the options for Toolkit.Deploy: upstream's DeployOptions, without traceLogs and reuseAssets (K.3-D3).

type DeployResult

type DeployResult struct {
	// Stacks are the stacks deployed, or left unchanged, in the order they finished; a stack with no resources has no entry.
	Stacks []DeployedStack
}

DeployResult is what Toolkit.Deploy deployed: upstream's DeployResult.

type DeployedStack

type DeployedStack struct {
	// StackName is the name the stack is deployed as.
	StackName string

	// HierarchicalID is the stack's hierarchical ID, such as "Stage/Stack".
	HierarchicalID string

	// Environment is the stack's environment, resolved, so that an environment-agnostic stack's names the account and region it was deployed to, where upstream's is the manifest's (G.8-D6).
	Environment cloudassembly.Environment

	// StackARN is the stack's ARN.
	StackARN string

	// Outputs are the stack's outputs, by key; empty, not nil, when it has none.
	Outputs map[string]string

	// DeleteFailures are the resources CloudFormation failed to delete during an update, and skipped.
	DeleteFailures []iohost.ResourceDeleteFailure
}

DeployedStack is one stack Toolkit.Deploy deployed, or left unchanged: upstream's DeployedStack.

type DeploymentMethod

type DeploymentMethod interface {
	// contains filtered or unexported methods
}

DeploymentMethod is how a stack is deployed: *ChangeSetDeployment, *DirectDeployment, *ExecuteChangeSetDeployment or *HotswapDeployment: upstream's DeploymentMethod.

type DestroyOptions

type DestroyOptions struct {
	// Stacks selects the stacks to destroy; the zero Selector selects every stack, those in nested assemblies included, with no expansion.
	// cdk destroy adds the stacks that depend on the ones named, ExpandDownstream, which the default doesn't, so that destroying a stack another imports from fails with CloudFormation's "export in use" unless the dependent stack is selected too.
	Stacks cloudassembly.Selector

	// RoleARN is the role CloudFormation deletes the stacks with, in place of each stack's execution role; placeholders such as ${AWS::AccountId} are replaced.
	RoleARN string

	// Concurrency is how many stacks are destroyed at once; zero means 1, and a negative value is refused (G.8-D5).
	Concurrency int

	// Express deletes the stacks in express mode.
	Express bool

	// StackEventPollingInterval is how long to wait between reads of a stack's events, and of its status; zero means each one's default, 2 s and 5 s.
	StackEventPollingInterval time.Duration
}

DestroyOptions are the options for Toolkit.Destroy: upstream's DestroyOptions.

type DestroyResult

type DestroyResult struct {
	// Stacks are the stacks destroyed, or found not to exist, in the order they finished (G.8-D6).
	Stacks []DestroyedStack
}

DestroyResult is what Toolkit.Destroy destroyed: upstream's DestroyResult.

type DestroyedStack

type DestroyedStack struct {
	// StackName is the name the stack is deployed as.
	StackName string

	// Environment is the stack's environment, resolved, so that an environment-agnostic stack's names the account and region it was destroyed in, as upstream documents and doesn't do (G.8-D6).
	Environment cloudassembly.Environment

	// StackARN is the stack's ARN, or empty when it didn't exist.
	StackARN string

	// StackExisted reports whether the stack existed.
	StackExisted bool
}

DestroyedStack is one stack Toolkit.Destroy destroyed, or found not to exist: upstream's DestroyedStack.

type DiagnoseOptions

type DiagnoseOptions struct {
	// Stacks selects the stacks to diagnose; the zero Selector selects every stack, those in nested assemblies included.
	// A Selector with patterns or an expansion must also name its Strategy.
	Stacks cloudassembly.Selector

	// Concurrency is how many stacks are diagnosed at once; zero means 10, and a negative value is refused (M.9-D4, M.9-D5).
	Concurrency int
}

DiagnoseOptions are the options for Toolkit.Diagnose: upstream's DiagnoseOptions, without toolkitStackName, since the bootstrap stack is the toolkit's Options.ToolkitStackName (M.9-D3). The zero value is upstream's default.

type DiagnoseResult

type DiagnoseResult struct {
	// Stacks are the stacks diagnosed, in the order they were selected.
	Stacks []iohost.DiagnosedStack
}

DiagnoseResult is what Toolkit.Diagnose found: upstream's DiagnoseResult.

type DiffMethod

type DiffMethod interface {
	// contains filtered or unexported methods
}

DiffMethod is how a stack's diff is computed: *ChangeSetDiff, *TemplateOnlyDiff or *LocalFileDiff: upstream's DiffMethod.

type DiffOptions

type DiffOptions struct {
	// Stacks selects the stacks to diff; the zero Selector selects every stack, those in nested assemblies included, with no expansion.
	Stacks cloudassembly.Selector

	// Method is how each stack's diff is computed; nil means a change set, falling back to the templates when it can't be created, as upstream's default does (J.6-D1).
	Method DiffMethod

	// Strict shows the AWS::CDK::Metadata resource, the CheckBootstrapVersion rule and changes that are likely mangled characters, which are otherwise hidden.
	Strict bool

	// ContextLines is the number of unchanged lines shown around a change inside a JSON value; zero means 3, as upstream's does.
	ContextLines int

	// IncludeMoves marks each added or removed resource that is one end of a move between the deployed stacks and the selected ones, a rename or a move to another stack, as upstream's refactor command detects them: upstream's includeMoves.
	// The deployed stacks are those with a selected stack's name in its resolved environment, listed and read with that environment's base credentials and no role, so the diff fails for an environment those credentials aren't for, as it does when the moves can't be detected for any other reason.
	// A diff against a local file ignores it.
	IncludeMoves bool
}

DiffOptions are the options for Toolkit.Diff: upstream's DiffOptions.

type DiffResult

type DiffResult struct {
	// Stacks are the diffs of the selected stacks, in the order they were selected, each with its nested stacks' diffs.
	Stacks []iohost.StackDiff
}

DiffResult is what Toolkit.Diff found: upstream's map of every stack's and nested stack's diff by name, as a tree (J.6-D2).

type DirectDeployment

type DirectDeployment struct{}

DirectDeployment deploys a stack without a change set, by CreateStack or UpdateStack: upstream's DirectDeployment.

type DriftOptions

type DriftOptions struct {
	// Stacks selects the stacks to check for drift; the zero Selector selects every stack, those in nested assemblies included, with no expansion.
	Stacks cloudassembly.Selector
}

DriftOptions are the options for Toolkit.Drift: upstream's DriftOptions.

type DriftResult

type DriftResult struct {
	// Stacks are the drift of the stacks checked, in the order they were selected; a stack for which CloudFormation returned no drift results has no entry.
	Stacks []iohost.StackDrift
}

DriftResult is what Toolkit.Drift found: upstream's map of DriftResult by stack display name, as a slice (K.5-D2).

type ECSHotswapProperties added in v0.2.0

type ECSHotswapProperties struct {
	// MinimumHealthyPercent is the lower limit on the service's running tasks during the deployment, as a percentage of its desired count; zero, upstream's default, replaces every task at once.
	MinimumHealthyPercent int

	// MaximumHealthyPercent is the upper limit on the service's running and pending tasks during the deployment, as a percentage of its desired count; zero leaves the service's own.
	MaximumHealthyPercent int

	// StabilizationTimeout is how long each service is waited for to become stable; zero means 600 s.
	StabilizationTimeout time.Duration
}

ECSHotswapProperties are how an ECS service is redeployed when its task definition is hotswapped: upstream's EcsHotswapProperties. Their zero values are upstream's defaults, and a negative value is refused before the app is synthesized.

type EnvironmentBootstrapResult

type EnvironmentBootstrapResult struct {
	// Environment is the environment, as given.
	Environment cloudassembly.Environment

	Status   BootstrapStatus
	Duration time.Duration
}

EnvironmentBootstrapResult is what bootstrapping did to one environment: upstream's EnvironmentBootstrapResult.

type ExecuteChangeSetDeployment

type ExecuteChangeSetDeployment struct {
	// Name is the change set's name or ARN; empty means cdk-deploy-change-set.
	Name string
}

ExecuteChangeSetDeployment executes a change set an earlier command prepared, as the CDK CLI's --method=execute-change-set does: upstream's ExecuteChangeSetDeployment. The stacks' assets are taken to be published already, as the command that prepared the change set publishes them.

type FeatureFlag

type FeatureFlag struct {
	// Module is the library whose flag it is, such as "aws-cdk-lib".
	Module string

	// Name is the flag's name, such as "@aws-cdk/core:newStyleStackSynthesis".
	Name string

	// RecommendedValue is the value the library recommends, or nil when the report gives none.
	RecommendedValue jsontext.Value

	// UserValue is the value the app configures, or nil when it doesn't configure the flag; a JSON null is nil too.
	UserValue jsontext.Value

	// Explanation describes the flag; it is empty when the report gives none.
	Explanation string

	// UnconfiguredBehavesLike is the value that behaves as the flag does when the app doesn't configure it: upstream's unconfiguredBehavesLike.v2.
	// It is nil when no flag of the library's report says, and otherwise never nil: false when this flag doesn't say.
	UnconfiguredBehavesLike jsontext.Value
}

FeatureFlag is one feature flag of a library an app uses, as the library's feature flag report describes it: upstream's FeatureFlag. Its values are raw JSON, because a flag can take any JSON value.

type FilteredNotice

type FilteredNotice struct {
	Notice Notice

	// DynamicValues are the values the notice's placeholders resolve to, by name, such as "ENVIRONMENTS".
	DynamicValues map[string]string
	// contains filtered or unexported fields
}

FilteredNotice is a notice that matched: upstream's FilteredNotice.

func (FilteredNotice) Format

func (f FilteredNotice) Format() string

Format returns the notice as Notices.Display shows it: its number and title, its overview wrapped at 60 characters, the versions it affects and a link to its issue, with its placeholders resolved.

type HotswapDeployment

type HotswapDeployment struct {
	// Fallback deploys the stack when a change can't be hotswapped, or the template can't be resolved; nil skips such changes, leaving them undeployed: upstream's fallback.
	Fallback HotswapFallback

	// ECS is how an ECS service is redeployed when its task definition is hotswapped: upstream's properties.ecs.
	ECS ECSHotswapProperties
}

HotswapDeployment deploys a stack's changes by updating the affected resources through their own APIs, short-circuiting CloudFormation, where it can: upstream's HotswapDeployment. It deliberately introduces drift, so it is for development only; see the toolkit's Hotswap section.

type HotswapFallback

type HotswapFallback interface {
	DeploymentMethod
	// contains filtered or unexported methods
}

HotswapFallback is how a HotswapDeployment deploys a stack it can't hotswap: *ChangeSetDeployment or *DirectDeployment (M.1-D4).

type ListOptions

type ListOptions struct {
	// Stacks selects the stacks to list; the zero value selects every stack, those in nested assemblies included.
	// A Selector with patterns or an expansion must also name its Strategy.
	Stacks cloudassembly.Selector
}

ListOptions are the options for Toolkit.List. The zero value is upstream's default.

type LocalFileDiff

type LocalFileDiff struct {
	// Path is the template file, JSON or YAML.
	Path string
}

LocalFileDiff diffs the one selected stack's new template against a template file, without reaching AWS: upstream's DiffMethod.LocalFile.

type MinimumSeverity

type MinimumSeverity string

MinimumSeverity is the least severe finding that fails an action: upstream's MinimumSeverity.

const (
	// SeverityError fails on a validation report that concludes in failure, such as one with an error annotation.
	SeverityError MinimumSeverity = "error"

	// SeverityWarning also fails on any violation of severity warning, as the CDK CLI's --strict does.
	SeverityWarning MinimumSeverity = "warn"

	// SeverityNone never fails, as the CDK CLI's --ignore-errors does.
	SeverityNone MinimumSeverity = "none"
)

The minimum severities.

type Mode

type Mode int

Mode is what credentials are wanted for, which a CredentialPlugin is told: upstream's Mode.

const (
	// ForReading is for reading, such as looking up context or diffing.
	ForReading Mode = iota

	// ForWriting is for changing an account, such as deploying.
	ForWriting
)

type Notice

type Notice struct {
	Title       string
	IssueNumber int
	Overview    string

	// Components are the components the notice affects, in disjunctive normal form, as the filter reads them: the notice matches when every component of one conjunction does.
	Components [][]NoticeComponent

	SchemaVersion string

	// Severity is "warning", "error", or anything else for information.
	Severity string

	// DynamicValues say how to render each {resolve:NAME} placeholder, by name.
	DynamicValues map[string]NoticeDynamicValue
}

Notice is a CDK notice: upstream's Notice.

type NoticeComponent

type NoticeComponent struct {
	Name, Version string
}

NoticeComponent is a component a notice affects, such as "cli" or "aws-cdk-lib.", and the node-semver range of its versions that are affected.

type NoticeDynamicValue

type NoticeDynamicValue struct {
	// Separator joins the values found for the placeholder, such as the names of several environments; it is "," when the notice gives none.
	Separator string
}

NoticeDynamicValue says how to render one placeholder.

type Notices

type Notices struct {
	// contains filtered or unexported fields
}

Notices fetches, filters and displays CDK notices: upstream's Notices, without its process-wide instance (M.7-D2). Make one with NewNotices, and pass it as Options.Notices for the toolkit to record the bootstrap versions it checks. It is safe for concurrent use.

func NewNotices

func NewNotices(ctx context.Context, opts NoticesOptions) (*Notices, error)

NewNotices returns notices with the given options, which has none until Notices.Refresh fetches them. It reads the acknowledged issue numbers from opts.Context once, as upstream's constructor does (M.7-D8), and fails with the store's error, or with a cdkerr.Error of Kind cdkerr.KindToolkit when the value isn't a list.

func (*Notices) AddBootstrappedEnvironment

func (n *Notices) AddBootstrappedEnvironment(e BootstrappedEnvironment)

AddBootstrappedEnvironment records an environment's bootstrap version, which notices about bootstrap versions match, naming the environment for {resolve:ENVIRONMENTS}. An environment recorded again with the same version is recorded once. The toolkit records the environments it checks into its Options.Notices; this is for the environments a caller checks itself.

func (*Notices) Display

func (n *Notices) Display(ctx context.Context, opts NoticesDisplayOptions) error

Display sends the notices Notices.Filter returns to the host, as upstream's display does: when there are any, a header, each notice formatted, and a footer saying how to acknowledge one, all with code CDK_TOOLKIT_I0100 but the notices, which have CDK_TOOLKIT_W0101, CDK_TOOLKIT_E0101 or CDK_TOOLKIT_I0101 by their severity; then, with opts.ShowTotal, their number. None of the messages has a payload. It fails only with the host's error.

func (*Notices) Filter

func (n *Notices) Filter(ctx context.Context, opts NoticesFilterOptions) ([]FilteredNotice, error)

Filter returns the notices that affect the app, in the order they were fetched: those whose components match the app's constructs, the CLI and Node versions, the language and the environments recorded, as upstream's filter does. It leaves out the acknowledged notices unless opts.IncludeAcknowledged is set. It fails only with the host's error.

func (*Notices) Refresh

func (n *Notices) Refresh(ctx context.Context, opts NoticesRefreshOptions) error

Refresh fetches the notices, from the cache while it is fresh, as upstream's refresh does. A program that shouldn't wait for it, as the CDK CLI doesn't, runs it in the background and ignores its error.

When fetching fails, it caches no notices for a minute and fails with a cdkerr.Error of Kind cdkerr.KindToolkit and Code "NoticesFetchFailed", whose cause says why; the notices it had are kept. When ctx is cancelled, the cache is left as it was, and the error satisfies errors.Is(err, ctx.Err()) (M.7-D11).

type NoticesDisplayOptions

type NoticesDisplayOptions struct {
	// IncludeAcknowledged shows the notices the user has acknowledged too.
	IncludeAcknowledged bool

	// ShowTotal ends with the number of notices shown.
	ShowTotal bool
}

NoticesDisplayOptions are the options for Notices.Display.

type NoticesFilterOptions

type NoticesFilterOptions struct {
	// IncludeAcknowledged keeps the notices the user has acknowledged.
	IncludeAcknowledged bool
}

NoticesFilterOptions are the options for Notices.Filter.

type NoticesOptions

type NoticesOptions struct {
	// Host receives the notices' messages; nil means [console.Default].
	Host iohost.Host

	// Context holds the issue numbers the user has acknowledged, under "acknowledged-issue-numbers", whose notices are left out; nil means none are (M.7-D8).
	Context ContextStore

	// AssemblyDirectory is the cloud assembly whose tree.json gives the constructs the app uses, such as "cdk.out"; empty means none (M.7-D5).
	AssemblyDirectory string

	// CLIVersion is the version of the cli component, which notices about the CDK CLI match; empty matches none (M.7-D3).
	// The notices' cli ranges describe releases of the TypeScript CLI: this module follows the TypeScript CLI 2.1149.0.
	CLIVersion string

	// NodeVersion is the version of the node component, such as the output of node --version, which notices about Node releases match; empty means no node component at all, so none matches (M.7-D4).
	NodeVersion string

	// Language is the CDK app's language, such as "go", which adds the component language:<Language>; empty adds none.
	Language string

	// URL is the notices document; empty means the official notices.
	URL string

	// HTTPClient makes the requests; nil means [http.DefaultClient], whose transport honours HTTPS_PROXY and NO_PROXY (M.7-D5).
	HTTPClient *http.Client

	// Timeout limits each request; zero means 3 seconds (M.7-D5).
	Timeout time.Duration

	// CacheDirectory, when set, holds notices.json and connection.json, the cached notices and the answer to the connectivity check, in the CDK CLI's formats; empty means no cache (M.7-D5).
	// The CDK CLI uses ~/.cdk/cache.
	CacheDirectory string
}

NoticesOptions are the options for NewNotices. The zero value fetches the official notices, caches nothing, and matches only the environments the toolkit records; see the Notices section of the package documentation for what each option stands in for.

type NoticesRefreshOptions

type NoticesRefreshOptions struct {
	// Force fetches the notices even when the cache is fresh.
	Force bool
}

NoticesRefreshOptions are the options for Notices.Refresh.

type Options

type Options struct {
	// Host receives the toolkit's messages and answers its requests; nil means [console.Default].
	// The toolkit never closes or reconfigures it.
	Host iohost.Host

	// NoEmojis removes emojis from the text of every message and request: upstream's emojis false.
	NoEmojis bool

	// NoColor removes ANSI escape sequences from the text of every message and request, such as those in a CDK app's output: upstream's color false.
	// It doesn't stop a host colouring its output by level; console.NonInteractive has its own Color setting for that.
	NoColor bool

	// AWS says how the toolkit reaches AWS.
	AWS AWSOptions

	// ToolkitStackName is the name of the bootstrap stack in each environment; empty means CDKToolkit, the CDK CLI's.
	ToolkitStackName string

	// AssemblyFailureAt is the least severe finding in a cloud assembly's validation report, or among its stacks' annotations, that fails an action: upstream's assemblyFailureAt.
	// The zero value means [SeverityError].
	AssemblyFailureAt MinimumSeverity

	// Notices, when set, records the bootstrap version of every environment whose version the toolkit checks, for notices about bootstrap versions: upstream's Notices.get() (M.7-D2).
	// An outdated environment is recorded before its check fails.
	// Deploy, rollback, orphan, publish assets, validate and diff record into it, the actions whose checks read a bootstrap version.
	Notices *Notices

	// ContextProviderPlugins answer the context lookups an app makes with provider "plugin", by the plugin name the query gives; see [ContextProviderPlugin].
	// The toolkit keeps a copy of the map for its life.
	ContextProviderPlugins map[string]ContextProviderPlugin
}

Options are the options for New. The zero value is upstream's default.

type OrphanOptions

type OrphanOptions struct {
	// ConstructPaths are the paths of the constructs whose resources to orphan, such as "MyStack/MyTable", or "MyStage/MyStack/MyTable" for a stack in a stage; they must all be in one stack.
	ConstructPaths []string

	// RoleARN is the role CloudFormation deploys the steps with, in place of the stack's execution role; placeholders such as ${AWS::AccountId} are replaced.
	// Upstream documents its roleArn as the role to assume in the target environment, but passes it to CloudFormation as the execution role, as this does; the stack's deploy role is still the one its artifact names (M.5-D7).
	RoleARN string
}

OrphanOptions are the options for Toolkit.Orphan: upstream's OrphanOptions (M.5-D1). Upstream's toolkitStackName is left out: deployStack never reads it, so its orphan always reads the toolkit's bootstrap stack, as this does through Options.ToolkitStackName.

type OrphanResult

type OrphanResult struct {
	// StackName is the name of the stack the resources were orphaned from.
	StackName string

	// Resources are the resources orphaned, as the plan listed them.
	Resources []OrphanedResource

	// ResourceMapping is what an import of the resources needs to find them: logical IDs to their import identifiers' values; empty, not nil, when there are none.
	ResourceMapping map[string]map[string]string
}

OrphanResult is what Toolkit.Orphan did, where upstream's returns nothing and writes the import mapping into its final message (M.5-D1).

type OrphanedResource

type OrphanedResource struct {
	// LogicalID is the resource's logical ID in the stack.
	LogicalID string

	// Type is the resource's type, or "Unknown" when the deployed template gives none.
	Type string

	// ConstructPath is the path of the resource's construct, such as "/MyStack/MyTable/Resource".
	ConstructPath string
}

OrphanedResource is a resource Toolkit.Orphan orphaned: upstream's OrphanedResource.

type PublishAssetsOptions

type PublishAssetsOptions struct {
	// Stacks selects the stacks whose assets to publish; the zero Selector selects every stack, those in nested assemblies included, with no expansion.
	// cdk publish-assets adds the stacks the ones named depend on, ExpandUpstream, unless given --exclusively, which the default doesn't.
	Stacks cloudassembly.Selector

	// Force publishes every file asset, even those whose destinations have them already, without checking first.
	// A container image whose repository has its tag is still left as it is, as upstream's is, since the bootstrap repository's tags are immutable.
	Force bool

	// Concurrency is how many assets are built, and how many published, at once; zero means 4, and a negative value is refused (I.1-D4).
	Concurrency int
}

PublishAssetsOptions are the options for Toolkit.PublishAssets: upstream's PublishAssetsOptions.

type PublishAssetsResult

type PublishAssetsResult struct {
	// Assets are the assets published, one entry per asset and destination, in the order the work graph has them: upstream's publishedAssets.
	// An asset its destination had already isn't among them, unless Force was set.
	Assets []cloudassembly.AssetEntry
}

PublishAssetsResult is what Toolkit.PublishAssets published: upstream's PublishAssetsResult.

type RollbackMode

type RollbackMode int

RollbackMode is whether a failed deployment rolls back (G.1-D4).

const (
	// RollbackDefault rolls back, except in express mode, where CloudFormation doesn't unless told to.
	RollbackDefault RollbackMode = iota

	// RollbackEnabled rolls back, in express mode too.
	RollbackEnabled

	// RollbackDisabled leaves a stack as the failure left it, the CLI's --no-rollback.
	RollbackDisabled
)

type RollbackOptions

type RollbackOptions struct {
	// Stacks selects the stacks to roll back; the zero Selector selects every stack, those in nested assemblies included, with no expansion.
	Stacks cloudassembly.Selector

	// RoleARN is the role CloudFormation rolls the stacks back with, in place of each stack's execution role; placeholders such as ${AWS::AccountId} are replaced.
	RoleARN string

	// OrphanFailedResources skips the resources that fail a continued rollback, the CLI's --force: CloudFormation picks them, nested stacks' included, and a warning names those it skipped.
	// It can't be combined with OrphanLogicalIDs.
	OrphanFailedResources bool

	// OrphanLogicalIDs are the logical IDs of the resources a continued rollback skips, the CLI's --orphan; a nested stack's resource is <nested stack name>.<logical ID>.
	OrphanLogicalIDs []string

	// NoBootstrapVersionCheck skips checking that each environment's bootstrap stack is at least version 23, which rolling back needs: upstream's validateBootstrapStackVersion false.
	NoBootstrapVersionCheck bool

	// StackEventPollingInterval is how long to wait between reads of a stack's events, and of its status; zero means each one's default, 2 s and 5 s.
	// Upstream's rollback has no such option, and always polls at the defaults (K.3-D8).
	StackEventPollingInterval time.Duration
}

RollbackOptions are the options for Toolkit.Rollback: upstream's RollbackOptions.

type RollbackResult

type RollbackResult struct {
	// Stacks are the stacks rolled back, or found stable, in the order they were selected.
	Stacks []RolledBackStack
}

RollbackResult is what Toolkit.Rollback rolled back: upstream's RollbackResult.

type RolledBackStack

type RolledBackStack struct {
	// StackName is the name the stack is deployed as.
	StackName string

	// Environment is the stack's environment, resolved, so that an environment-agnostic stack's names the account and region it was rolled back in, where upstream's is the manifest's (G.8-D6).
	Environment cloudassembly.Environment

	// StackARN is the stack's ARN, or empty when it doesn't exist.
	StackARN string

	// Result is what rolling back did to the stack.
	Result StackRollbackResult
}

RolledBackStack is one stack Toolkit.Rollback rolled back, or found stable: upstream's RolledBackStack.

type Source

type Source interface {
	// contains filtered or unexported methods
}

Source produces the cloud assembly an action works on: upstream's ICloudAssemblySource. Make one with FromAssemblyDirectory, FromCdkApp or FromAssemblyBuilder; the *Assembly that Toolkit.Synth returns is one too.

Its one method is unexported, so code outside this package cannot implement it; a source of one's own is a builder.

func FromAssemblyBuilder

func FromAssemblyBuilder(builder AssemblyBuilder, opts AssemblyBuilderOptions) Source

FromAssemblyBuilder returns a source that synthesizes an app in process by calling builder: upstream's fromAssemblyBuilder. An aws-cdk-go builder still needs Node, which aws-cdk-go runs aws-cdk-lib in through jsii.

Unlike upstream, it never sets the process's environment variables, which other goroutines share, so builders may run concurrently; upstream's clobberEnv is always false. While the assembly reports context missing, the toolkit looks it up, saves it in the context store, and calls the builder again, unless opts.DisableLookups is set.

Producing the assembly fails with the builder's error, wrapped as AssemblyBuilder describes, or with the errors of FromAssemblyDirectory when the result cannot be loaded.

Example

A source made from a builder synthesizes an app in the caller's own process, as an aws-cdk-go app does with awscdk.NewApp and App.Synth. The builder passes p.Outdir and p.Context to the app and returns the directory it wrote the assembly to.

package main

import (
	"context"
	"log"
	"os"
	"path/filepath"

	"github.com/asteroid-computing/aws-cdk-toolkit/toolkit"
)

func main() {
	ctx := context.Background()
	tk, err := toolkit.New(toolkit.Options{})
	if err != nil {
		log.Fatal(err)
	}

	builder := func(ctx context.Context, p toolkit.BuilderProps) (string, error) {
		manifest := `{"version": "55.0.0", "artifacts": {}}`
		return p.Outdir, os.WriteFile(filepath.Join(p.Outdir, "manifest.json"), []byte(manifest), 0o644)
	}
	asm, err := tk.Synth(ctx, toolkit.FromAssemblyBuilder(builder, toolkit.AssemblyBuilderOptions{}), toolkit.SynthOptions{})
	if err != nil {
		log.Fatal(err)
	}
	defer asm.Close()
}

func FromAssemblyDirectory

func FromAssemblyDirectory(dir string, opts AssemblyDirectoryOptions) Source

FromAssemblyDirectory returns a source that reads the cloud assembly already in dir, such as a cdk.out, without synthesizing: upstream's fromAssemblyDirectory. It runs no lookups and needs no Node.

Producing the assembly fails with a cdkerr.Error of Kind cdkerr.KindLock if something is synthesizing into dir, of Code cdkerr.CodeAssemblyVersionMismatch if the assembly is newer than this module reads, and of Kind cdkerr.KindAssembly if it cannot be loaded or still lists missing context.

Example

A source made from a directory reads a cloud assembly that was synthesized earlier, such as a cdk.out, without running an app or needing Node.

package main

import (
	"context"
	"fmt"
	"io"
	"log"

	"github.com/asteroid-computing/aws-cdk-toolkit/iohost"
	"github.com/asteroid-computing/aws-cdk-toolkit/iohost/console"
	"github.com/asteroid-computing/aws-cdk-toolkit/toolkit"
)

// quiet is a host that discards every message, so that an example prints only what it chooses to.
func quiet() iohost.Host {
	return &console.NonInteractive{Stdout: io.Discard, Stderr: io.Discard}
}

func main() {
	ctx := context.Background()
	tk, err := toolkit.New(toolkit.Options{Host: quiet()})
	if err != nil {
		log.Fatal(err)
	}

	src := toolkit.FromAssemblyDirectory("testdata/example/cdk.out", toolkit.AssemblyDirectoryOptions{})

	// Synth returns the assembly, which holds a lock on its directory until it is closed.
	asm, err := tk.Synth(ctx, src, toolkit.SynthOptions{})
	if err != nil {
		log.Fatal(err)
	}
	defer asm.Close()

	// The assembly is itself a source, so another action can work on it without synthesizing again.
	stacks, err := tk.List(ctx, asm, toolkit.ListOptions{})
	if err != nil {
		log.Fatal(err)
	}
	for _, s := range stacks {
		fmt.Println(s.ID, s.Environment.Account, s.Environment.Region)
	}
}
Output:
Network 123456789012 us-east-1
Service 123456789012 us-east-1

func FromCdkApp

func FromCdkApp(app string, opts CdkAppOptions) Source

FromCdkApp returns a source that synthesizes the CDK app the command app runs, such as "go run ." or cdk.json's "app": upstream's fromCdkApp.

The command runs in a shell, /bin/sh or cmd.exe, in opts.WorkingDir. If app, or its first word, names a file there, the file is quoted for the shell, and a JavaScript file that is not executable is run with node.

The app receives its context and output directory through the environment variables aws-cdk-lib reads; context too large for the environment goes to a temporary file. While the app reports context missing, the toolkit looks it up, saves it in the context store, and runs the app again, unless opts.DisableLookups is set. Each line of its output is sent to the host as it comes, standard output as CDK_ASSEMBLY_I1001 and standard error as CDK_ASSEMBLY_E1002. Cancelling the context kills the app and everything it started.

Producing the assembly fails with a cdkerr.Error of Kind cdkerr.KindAssembly and Code "AssemblyError" when the app cannot be run or fails, with the app's error code, if it wrote one, as its SynthesisCode, and with the other errors of FromAssemblyDirectory when the result cannot be loaded.

Example

A source made from a command runs a CDK app as cdk.json's "app" would, and reads the assembly it writes. The app runs in its working directory, and when it needs context it doesn't have, such as a VPC lookup, the toolkit looks it up in AWS and runs the app again.

package main

import (
	"context"
	"log"

	"github.com/asteroid-computing/aws-cdk-toolkit/toolkit"
)

func main() {
	ctx := context.Background()
	tk, err := toolkit.New(toolkit.Options{})
	if err != nil {
		log.Fatal(err)
	}

	src := toolkit.FromCdkApp("go run .", toolkit.CdkAppOptions{
		WorkingDir: "infra",
		Env:        map[string]string{"STAGE": "dev"},
		Synth:      toolkit.AppSynthOptions{Debug: true},
	})
	asm, err := tk.Synth(ctx, src, toolkit.SynthOptions{})
	if err != nil {
		log.Fatal(err)
	}
	defer asm.Close()
}

type StackParameters

type StackParameters struct {
	// Values are the values to set, keyed by "Param" for every stack, or "Stack:Param" for the stack named Stack, whose values override those for every stack.
	Values map[string]string

	// ReplaceExisting drops the deployed values of the parameters Values doesn't set, so that they take the template's defaults: with Values, upstream's exactly.
	ReplaceExisting bool
}

StackParameters are the parameter values a deployment sets, and what happens to the parameters it doesn't set: upstream's StackParameters (G.5-D3). The zero value keeps every parameter's deployed value, upstream's onlyExisting, which upstream documents as the default and the CDK CLI uses (G.5-D2).

type StackRollbackResult

type StackRollbackResult string

StackRollbackResult is what rolling back did to a stack.

const (
	// StackRolledBack means the stack was rolled back.
	StackRolledBack StackRollbackResult = "rolled-back"

	// StackAlreadyStable means nothing was sent: the stack needed no rollback, had an operation in progress, doesn't exist, or is in ROLLBACK_FAILED, from which it can't be rolled back, with a warning to recreate it.
	StackAlreadyStable StackRollbackResult = "already-stable"
)

type SynthOptions

type SynthOptions struct {
	// Stacks selects the stacks to report; the zero value selects every stack, those in nested assemblies included.
	// A Selector with patterns or an expansion must also name its Strategy.
	Stacks cloudassembly.Selector

	// DisableValidateOnSynth checks only the selected stacks' validation findings, not also those of every stack whose ValidateOnSynth is set: upstream's validateStacks false.
	// Upstream documents validateStacks as true by default but treats it as false; the toolkit does what upstream documents, as the CDK CLI does.
	DisableValidateOnSynth bool
}

SynthOptions are the options for Toolkit.Synth. The zero value is upstream's default.

type Tag

type Tag struct {
	Key   string
	Value string
}

Tag is a tag to apply to a stack (EG-7).

type TemplateOnlyDiff

type TemplateOnlyDiff struct {
	// ProcessedTemplate diffs against the deployed template after CloudFormation processed its transforms, rather than the original: upstream's compareAgainstProcessedTemplate.
	ProcessedTemplate bool
}

TemplateOnlyDiff diffs each stack's deployed template against its new one without a change set, faster and needing no permission to create one, but less accurate: upstream's DiffMethod.TemplateOnly.

type Toolkit

type Toolkit struct {
	// contains filtered or unexported fields
}

Toolkit runs AWS CDK actions on the cloud assemblies Source values produce: upstream's Toolkit. Make one with New.

A Toolkit holds nothing that needs releasing, so it has no Close. It is safe for concurrent use.

func New

func New(opts Options) (*Toolkit, error)

New returns a toolkit with the given options. It does no I/O.

It fails with a cdkerr.Error of Kind cdkerr.KindToolkit when an option has an unknown value, and with Code "InvalidContextProvider" when a context-provider plugin is nil.

Example

New makes a toolkit, and does no I/O: it reaches AWS only when an action needs to. Its options choose the host that receives the toolkit's messages, whether their text keeps emojis and colour, and how the toolkit reaches AWS.

package main

import (
	"log"
	"os"

	"github.com/asteroid-computing/aws-cdk-toolkit/iohost"
	"github.com/asteroid-computing/aws-cdk-toolkit/iohost/console"
	"github.com/asteroid-computing/aws-cdk-toolkit/toolkit"
)

func main() {
	tk, err := toolkit.New(toolkit.Options{
		Host:     &console.NonInteractive{Stdout: os.Stdout, Stderr: os.Stderr, Level: iohost.LevelWarn},
		NoEmojis: true,
		AWS:      toolkit.AWSOptions{Profile: "deploy", Region: "eu-west-2"},
	})
	if err != nil {
		log.Fatal(err)
	}
	_ = tk
}

func (*Toolkit) Bootstrap

Bootstrap deploys the bootstrap stack to each environment, up to 20 at once: upstream's bootstrap action.

For each environment, the parameters are merged with the deployed stack's and validated, and the template is deployed through a change set, as the CDK CLI's cdk bootstrap does, so that either can bootstrap again what the other bootstrapped (E.2-D2). Each environment is a span, CDK_TOOLKIT_I9100 to CDK_TOOLKIT_I9000, and ends with CDK_TOOLKIT_I9900 on success or CDK_TOOLKIT_E9900 on failure, and CDK_TOOLKIT_W9902 when express mode left resources stabilizing. The span ends on failure too, after CDK_TOOLKIT_E9900, where upstream's is left open (K.3-D10). The first environment to fail fails the action, once the others have finished.

Validation fails with a cdkerr.KindToolkit error whose Code is upstream's, such as "MissingExecutionPoliciesForTrust" or "AccountBothTrustedAndUntrusted". A legacy template, one without a bootstrap version, fails with Code "LegacyBootstrapNotSupported", because bootstrapping with it needs the CDK CLI (EE-3).

Example

Bootstrap deploys the bootstrap stack to each environment, as cdk bootstrap does.

package main

import (
	"context"
	"fmt"
	"log"

	"github.com/asteroid-computing/aws-cdk-toolkit/toolkit"
)

func main() {
	ctx := context.Background()
	tk, err := toolkit.New(toolkit.Options{})
	if err != nil {
		log.Fatal(err)
	}

	envs, err := toolkit.BootstrapEnvironmentsFromList("aws://123456789012/us-east-1", "aws://123456789012/eu-west-2")
	if err != nil {
		log.Fatal(err)
	}
	res, err := tk.Bootstrap(ctx, envs, toolkit.BootstrapOptions{})
	if err != nil {
		log.Fatal(err)
	}
	for _, e := range res.Environments {
		fmt.Println(e.Environment)
	}
}

func (*Toolkit) Deploy

func (t *Toolkit) Deploy(ctx context.Context, src Source, opts DeployOptions) (*DeployResult, error)

Deploy produces the cloud assembly from src and deploys the selected stacks, each after the stacks it depends on, Concurrency at once: upstream's deploy.

The selected stacks' validation findings are checked first, as Toolkit.Synth checks them; a selection of no stacks gets CDK_TOOLKIT_E5001 and an empty result.

The stacks' assets, those of their asset manifests, the template asset aws-cdk-lib's default synthesizer gives every stack included, are built and published as Toolkit.PublishAssets builds and publishes them, each one before the stack that needs it: every build before any stack, unless AssetBuildTime says just in time, AssetBuildConcurrency builds and 8 publishes at once, or one of each with NoAssetParallelism. Unless ForceAssetPublishing is set, the destinations that have their assets already are left out first, as I.2's pruning leaves them out, following the cross-account rule of each stack's environment, read from its toolkit stack once per environment, so that where publishing to another account's bucket is forbidden an object in such a bucket isn't taken as published, where upstream's check reads no rule and takes it as published (H.2-D5). Each build and publish is a span, CDK_TOOLKIT_I5210 and CDK_TOOLKIT_I5220, around the publisher's messages, and container images are built and pushed with the docker CLI that CDK_DOCKER names, or docker, run with the process's environment (H.3-D2). ExecuteChangeSetDeployment builds and publishes nothing, as upstream's doesn't, since the command that prepared the change set published them; the destinations are still checked unless forced, as upstream's are. A template too large to pass to CloudFormation directly, from a stack that doesn't publish its template as an asset, is uploaded to the environment's staging bucket before its stack's change set is created, outside any span, unforced, with the cross-account rule of the stack's environment, as the CDK CLI uploads it. It is built and then published, as H.2 has it, so its messages are a build's and a publish's, where upstream's legacy publishAssets sends one start and one success for both; and the toolkit stack is read for the cross-account rule once per environment, when assets are checked or published or such a template is uploaded, where upstream reads it for every stack it deploys.

Each stack is deployed as upstream's deploy action deploys it. A stack with no resources is skipped, with CDK_TOOLKIT_W5021, or, when it exists, deleted, with CDK_TOOLKIT_W5022, as Toolkit.Destroy deletes it, asking CDK_TOOLKIT_I7010, whose decline fails the stack with Code "DestroyAborted"; it is deleted with opts.RoleARN and StackEventPollingInterval, where upstream's polls at the defaults (K.3-D9). Otherwise the stack is looked up with its deploy role assumed, its bootstrap stack's version checked, and deployed with its execution role, or opts.RoleARN, both with their placeholders replaced, by the method opts.Method names. A change set is prepared first, unless the deployment would change nothing, which is skipped, unless forced; then CDK_TOOLKIT_I5060 asks to deploy it, unless it has no changes. Its question is the stack's diff, its nested stacks' included, through the change set and the change sets it created for them, then the motivation: the security diff and "Stack includes security-sensitive updates" when the diff changes permissions, and the stack diff and "Stack includes updates" otherwise, as upstream's are. Its payload carries the permission change, the diffs shown as a tree, their destructive changes and the change set; a host applies an approval policy, such as the CDK CLI's --require-approval, with iohost.NeedsApproval. The deployed templates are read through the deploy role, once, after the skip check and before the change set is prepared. A direct deployment asks before it starts, with the diff of the templates, which it reads then, and no change set, as upstream's does. An existing change set, for ExecuteChangeSetDeployment, is waited for and checked, then CDK_TOOLKIT_I5060 asks to deploy it even when it has no changes, and it is described again when it is executed, failing then unless it can be, as upstream's is. CDK_TOOLKIT_I5060 defaults to yes, so that a host that doesn't answer requests, console.Default() included, deploys without asking, as upstream's non-interactive host does; a decline fails the stack with a cdkerr.KindAborted error with Code "DeployAborted".

HotswapDeployment sends CDK_TOOLKIT_W5400 once, before any stack, and asks CDK_TOOLKIT_I5060 for each stack before it starts, as a direct deployment does, and its fallback doesn't ask again (M.1-D5). Each stack is then looked up, its parameters resolved, and skipped when nothing changed, with "hotswap deployment skipped - no changes were detected (use --force to override)", its template body prepared and published as for any method, and its changes hotswapped, as the toolkit's Hotswap section describes. A stack hotswapped gets a recommendation to include --revert-drift in its next deployment that isn't a hotswap; one that can't be is deployed by the fallback, whose CloudFormation calls carry the user agent cdk-hotswap/fallback, or, without a fallback, left as it is, a no-op. A failed hotswap fails the stack, and isn't deployed by the fallback.

The deployment is a span, CDK_TOOLKIT_I5100 to CDK_TOOLKIT_I5001. A stack paused in a failed state is rolled back first, as Toolkit.Rollback rolls it back, with opts.RoleARN and the polling interval, once CDK_TOOLKIT_I5050 confirms it, and deployed again with rollback enabled: through a new change set, the deployment's or a hotswap's fallback's, which CDK_TOOLKIT_I5060 asks about again, with the rolled-back stack's diff, unless it has no changes, or directly or by a hotswap, without asking again. A change set that replaces a resource with rollback disabled, in express mode too, asks CDK_TOOLKIT_I5050 too, and a standard one is then executed again, the change set approved, with rollback enabled, where upstream prepares a new one and executes it. An express change set's rollback is fixed when it is created, so for one a new change set is prepared with rollback enabled, as upstream's is, and CDK_TOOLKIT_I5060 asks again before it is executed; an existing express change set, for ExecuteChangeSetDeployment, can't be prepared again, so it fails at once, before CDK_TOOLKIT_I5050, with a cdkerr.KindToolkit error with Code "ExpressReplacementRequiresRollback" (K.3-D5, as amended). A stack an express deployment left UPDATE_FAILED refuses a change set that would roll back or replaces a resource, whatever mode is asked for, with upstream's cdkerr.KindToolkit error with Code "ExpressStackFailPaused", before anything is executed or rolled back. Declining CDK_TOOLKIT_I5050 fails the stack with Code "RollbackAborted", or "ReplacementRollbackAborted". Every message of the rollback carries the deploy action, its work's included, the event monitor's among them, where upstream's work sends its own with the rollback action (K.3-D8). A deployed stack gets CDK_TOOLKIT_I5900, with "(no changes)" when nothing changed, CDK_TOOLKIT_I5000, CDK_TOOLKIT_W5902 for the resources express mode left stabilizing, and CDK_TOOLKIT_I5901 with its outputs and its ARN. A change set that was executed, or a direct deployment that wasn't a no-op, also deletes the CDK CLI's hotswap cache for the stack, in the stack's assembly's directory (G.6-D5).

A stack's error is "<stack name> failed: " and its cause, which errors.Is and errors.As find, as they do a cancellation's (K.3-D11); the errors of stacks that failed together are joined. A change set the deployment prepared and didn't execute is deleted on every way out, and with it a stack that was only its shell.

It departs from upstream in sixteen places:

  • a negative Concurrency or AssetBuildConcurrency is refused before synthesis, and an AssetBuildConcurrency of zero means 1, where upstream's work graph never settles for either (G.8-D5, I.1-D4);
  • when a stack fails, the stacks deployed until then are returned beside the errors of every stack that failed, joined, where upstream rejects with the last error only (EI-1, EI-4);
  • each result's environment is resolved (G.8-D6);
  • the CDK_TOOLKIT_I5060 request carries the change set, which upstream's lacks, and its diffs as a tree of the stack and its nested stacks, where upstream's are a map by name;
  • the approval's diff of a nested stack goes through the change set the stack's change set created for it, where upstream diffs nested stacks by their templates alone;
  • after a rollback the deployment performs first, the new change set is approved again before it is executed, where upstream asks once, before the rollback, so that changes the approved diff didn't show are deployed unasked;
  • a REVIEW_IN_PROGRESS stack's deployed template is empty, without a GetTemplate call, where upstream calls it, though such a stack has never been deployed;
  • the deployed templates are read through the deploy role, and for a change set after the skip check, where upstream reads them through the lookup role before it;
  • a stack's error wraps its cause, so that errors.As finds a deployment's or a bootstrap stack's error directly, where upstream's is a new error naming the cause's code (K.3-D11);
  • the outputs file is written once, when Deploy returns, however it returns, where upstream writes it after each stack that gets far enough; a file that can't be written is joined with the deployment's error, or returned beside the result of a deployment that succeeded, where upstream's write error replaces the deployment's; and two selected stacks with one name fail the action before anything is deployed, where upstream writes the outputs of whichever finished last (G.11-D3, G.11-D4, G.11-D6);
  • every message of a rollback the deployment performs first carries the deploy action, where upstream's work sends its own with the rollback action (K.3-D8);
  • a stack's span ends when the stack fails, with its usual "Total time" text, where upstream leaves it open (K.3-D10), and so does an asset's when its build or publish fails;
  • a standard change set that replaces a resource, in a deployment with rollback disabled, is executed again with rollback enabled once CDK_TOOLKIT_I5050 confirms it, so that the change set executed is the one approved, where upstream removes it and executes a new one nobody approved; an express one, whose rollback can't change, is replaced by a new one that CDK_TOOLKIT_I5060 asks about again, and an existing express one fails at once, where upstream describes it again and fails with DeployLoopUnstable (K.3-D5, as amended);
  • a stack with no resources is deleted polling at StackEventPollingInterval, where upstream polls at the defaults whatever the option says (K.3-D9);
  • leaving out the destinations that have their assets already follows the cross-account rule, as publishing does, where upstream's check doesn't (H.2-D5);
  • each asset event's payload carries its asset, the entry's own progress and the stack name of the call's own entry, where upstream's carries no asset, a percentage that passes 100, and the first caller's stack name (H.2-D8).

Cancelling ctx stops new deployments, builds and publishes; a CloudFormation operation already started goes on, and an upload already started is stopped, as the toolkit's Cancellation section says.

Example

Deploy deploys each selected stack after the stacks it depends on, and asks its host to approve the changes first. A deployment goes through a change set unless its method says otherwise, and its outputs can be written to a file.

package main

import (
	"context"
	"fmt"
	"log"

	"github.com/asteroid-computing/aws-cdk-toolkit/cloudassembly"
	"github.com/asteroid-computing/aws-cdk-toolkit/toolkit"
)

func main() {
	ctx := context.Background()
	tk, err := toolkit.New(toolkit.Options{})
	if err != nil {
		log.Fatal(err)
	}

	src := toolkit.FromCdkApp("go run .", toolkit.CdkAppOptions{WorkingDir: "infra"})
	res, err := tk.Deploy(ctx, src, toolkit.DeployOptions{
		Stacks:      cloudassembly.Selector{Strategy: cloudassembly.StrategyPatternMustMatch, Patterns: []string{"Service"}, Expand: cloudassembly.ExpandUpstream},
		Method:      &toolkit.ChangeSetDeployment{},
		OutputsFile: "outputs.json",
	})
	if err != nil {
		log.Fatal(err)
	}
	for _, s := range res.Stacks {
		fmt.Println(s.StackName, s.StackARN, s.Outputs)
	}
}

func (*Toolkit) Destroy

func (t *Toolkit) Destroy(ctx context.Context, src Source, opts DestroyOptions) (*DestroyResult, error)

Destroy produces the cloud assembly from src and destroys the selected stacks, each after the stacks that depend on it: upstream's destroy.

Patterns that match no stack get CDK_TOOLKIT_W7010, with the stacks they match when case is ignored; a selection of no stacks gets CDK_TOOLKIT_W7011 and destroys nothing. Then it asks CDK_TOOLKIT_I7010 to confirm, which defaults to yes, so that a host that doesn't answer requests, console.Default() included, destroys without asking, as upstream's non-interactive host does. Each stack is deleted with deploy.Destroy, with its deploy role assumed and its execution role, or opts.RoleARN, both with their placeholders replaced, Concurrency stacks at once, in the order I.1's work graph gives.

It departs from upstream in five places:

  • declining the confirmation sends CDK_TOOLKIT_E7010 and fails with a cdkerr.KindAborted error with Code "DestroyAborted", the CDK CLI's, where upstream's library returns success with no stacks (G.8-D4);
  • a negative Concurrency is refused before synthesis, where upstream's work graph never settles (G.8-D5);
  • when a stack fails to delete, the stacks destroyed until then are returned beside the errors of every stack that failed, joined, where upstream rejects with the last error only (EI-1, EI-4);
  • each result's environment is resolved (G.8-D6);
  • a stack's span ends when the stack fails, after CDK_TOOLKIT_E7900, where upstream leaves it open (K.3-D10).

Cancelling ctx stops new deletions; a deletion already started goes on in CloudFormation, as the toolkit's Cancellation section says.

Example

Destroy deletes each selected stack after the stacks that depend on it, and asks its host to confirm first.

package main

import (
	"context"
	"fmt"
	"log"

	"github.com/asteroid-computing/aws-cdk-toolkit/toolkit"
)

func main() {
	ctx := context.Background()
	tk, err := toolkit.New(toolkit.Options{})
	if err != nil {
		log.Fatal(err)
	}

	src := toolkit.FromCdkApp("go run .", toolkit.CdkAppOptions{WorkingDir: "infra"})
	res, err := tk.Destroy(ctx, src, toolkit.DestroyOptions{})
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("destroyed", len(res.Stacks), "stacks")
}

func (*Toolkit) Diagnose

func (t *Toolkit) Diagnose(ctx context.Context, src Source, opts DiagnoseOptions) (*DiagnoseResult, error)

Diagnose produces the cloud assembly from src and finds why the selected stacks' deployments failed: upstream's diagnose.

Each stack is diagnosed from its current state: a failed or rolled-back stack from its events, any other from its change sets that failed, other than for having no changes. Its environment is accessed with its lookup role, or, when that fails, with a warning and its deploy role, for reading. As each stack's diagnosis finishes, it is sent as CDK_TOOLKIT_I9500 when there is no problem, CDK_TOOLKIT_E9500 with the problem when there is one, and CDK_TOOLKIT_W9501 when the stack couldn't be diagnosed, such as one that doesn't exist or is being updated, each with the iohost.DiagnosedStack as payload. A stack with a problem doesn't fail the action; it is in the result.

A source whose AppSynthOptions set Debug gives the diagnosis the stack traces of the constructs that define the failed resources, which is why the CDK CLI's cdk diagnose turns on debug mode.

It closes the assembly before returning. It fails with a cdkerr.Error of Kind cdkerr.KindToolkit when Concurrency is negative, with the errors of src, with those of cloudassembly.Assembly.SelectStacks when the selection cannot be made, and with those of AWS authentication when a stack's environment can't be accessed. When a stack's environment can't be accessed, or the host fails to take a stack's message, no further stack is started, those started finish, and the stacks diagnosed and reported are returned beside the errors, joined (M.9-D7). Cancelling ctx does the same, with an error that satisfies errors.Is(err, ctx.Err()); a diagnosis that finishes once ctx is done is neither sent nor returned, since a diagnosis cut short isn't the stack's state.

func (*Toolkit) Diff

func (t *Toolkit) Diff(ctx context.Context, src Source, opts DiffOptions) (*DiffResult, error)

Diff produces the cloud assembly from src and diffs each selected stack's new template against its deployed one, or against a file, with its nested stacks': upstream's diff.

The diffs are a span, CDK_TOOLKIT_I4000 to CDK_TOOLKIT_I4001, which ends with "✨ Number of stacks with differences: <n>" and the totals and diffs in iohost.DiffResult. Each stack's diff is CDK_TOOLKIT_I4002, its text the stack's diff and its nested stacks', and a diff that broadens permissions is preceded by a warning and its security diff, at info. The text has no colour, as every toolkit message has none; a host renders the payload's diffs with cfndiff.Format for colour (J.6-D11). The selected stacks' validation findings aren't checked, and a selection of no stacks gets no message, as upstream's diff has none.

With a change set or template only, each stack's deployed template, and its CDK-managed nested stacks', are read through its lookup role, or, when that fails, after a warning, through its deploy role, as upstream reads them, and the header names the stack's environment, resolved. The change set is created as upstream's createDiffChangeSet creates it, after the stack's templates are published as its asset manifests publish them, and the change sets CloudFormation creates for its nested stacks are described and used for theirs. When it can't be created, the diff falls back to the templates, with upstream's info line and the reason at debug level, unless NoFallback is set. A local file diffs exactly one stack, without nested stacks or an environment; another selection fails with Code "SingleStackRequired", and a missing file with Code "TemplateFileNotFound", upstream's.

It departs from upstream in these places (#76):

  • the result, and the payloads, hold the diffs as a tree of each stack and its nested stacks, in selection order, where upstream's is one map by name, in which names collide (J.6-D2);
  • each nested stack's diff is computed and shown for itself, where upstream's two undeployed nested stacks with one logical ID under different parents both show the first one's (J.6-D3);
  • only the CheckBootstrapVersion rule is hidden, where upstream hides every change to Rules beside it (J.6-D4);
  • the re-diff that hides mangled characters keeps the import marking, and the diffs in the result and the payloads are those shown, where upstream's re-diff drops the import, and its result keeps the unfiltered, unmangled diff (J.6-D5);
  • the change set is cleaned up as a deployment's is, so that a REVIEW_IN_PROGRESS stack holding change sets someone prepared is kept, where upstream deletes it (J.6-D7);
  • the nested stacks' change sets are described before the stack's change set is deleted, which deletes them, where upstream deletes it first and its descriptions race the deletion;
  • the change set gets the parameters a deployment with the same StackParameters would send, deployed values kept by default, where upstream's gets the template's defaults, so that a parameter deployed with another value shows as changing back, and one without a default makes the change set fail (J.6-D8);
  • FormattedDiff.Security is the security diff, empty without security changes, where upstream's is the whole diff (J.6-D10);
  • with IncludeMoves, an environment-agnostic stack's moves are found, by its resolved environment, where upstream looks them up by the manifest's and finds none;
  • with IncludeMoves, a resource's location is its stack's CloudFormation name and its logical ID, where upstream's uses the display name, so that a stack in a stage or with its own stack name has its moves marked; the header still shows the display name;
  • a template too large to pass directly, of a stack without a template asset, is uploaded to the staging bucket before the change set is created, as a deployment's is, where upstream adds it to an asset manifest it discards, so that the change set names an object never uploaded, fails, and the diff falls back to the templates;
  • the span ends when the diff fails, where upstream leaves it open (K.3-D10).

It doesn't read migrate.json, which upstream's reads to diff the resources it names as an import.

Cancelling ctx stops the action before the next stack, after deleting the change set in progress, without falling back to the templates; a change set CloudFormation is still computing can't be deleted, and is left, with a warning naming it, and the REVIEW_IN_PROGRESS stack it created for a new stack, as the toolkit's Cancellation section says. A change set that can't be deleted for another reason is left with the same warning, and the diff goes on.

Example (ChangeSet)

Diff, without a method, asks CloudFormation to compute a change set, and falls back to the templates when it can't create one.

package main

import (
	"context"
	"fmt"
	"log"

	"github.com/asteroid-computing/aws-cdk-toolkit/toolkit"
)

func main() {
	ctx := context.Background()
	tk, err := toolkit.New(toolkit.Options{})
	if err != nil {
		log.Fatal(err)
	}

	src := toolkit.FromCdkApp("go run .", toolkit.CdkAppOptions{WorkingDir: "infra"})
	res, err := tk.Diff(ctx, src, toolkit.DiffOptions{
		Method: &toolkit.ChangeSetDiff{},
		Strict: true,
	})
	if err != nil {
		log.Fatal(err)
	}
	for _, d := range res.Stacks {
		fmt.Println(d.Stack.DisplayName, "changes:", d.NumStacksWithChanges, "destructive:", len(d.DestructiveChanges))
	}
}
Example (LocalFile)

Diff compares each selected stack's new template with its deployed one. A diff against a local file needs no AWS credentials, and diffs exactly one stack.

package main

import (
	"context"
	"fmt"
	"io"
	"log"

	"github.com/asteroid-computing/aws-cdk-toolkit/cloudassembly"
	"github.com/asteroid-computing/aws-cdk-toolkit/iohost"
	"github.com/asteroid-computing/aws-cdk-toolkit/iohost/console"
	"github.com/asteroid-computing/aws-cdk-toolkit/toolkit"
)

// quiet is a host that discards every message, so that an example prints only what it chooses to.
func quiet() iohost.Host {
	return &console.NonInteractive{Stdout: io.Discard, Stderr: io.Discard}
}

func main() {
	ctx := context.Background()
	tk, err := toolkit.New(toolkit.Options{Host: quiet()})
	if err != nil {
		log.Fatal(err)
	}

	src := toolkit.FromAssemblyDirectory("testdata/example/cdk.out", toolkit.AssemblyDirectoryOptions{})
	res, err := tk.Diff(ctx, src, toolkit.DiffOptions{
		Stacks: cloudassembly.Selector{Strategy: cloudassembly.StrategyPatternMustMatchSingle, Patterns: []string{"Network"}},
		Method: &toolkit.LocalFileDiff{Path: "testdata/example/deployed/Network.template.json"},
	})
	if err != nil {
		log.Fatal(err)
	}
	for _, d := range res.Stacks {
		fmt.Println(d.FormattedDiff.Diff)
	}
}
Output:
Stack Network
Resources
[~] AWS::S3::Bucket LogsBucket
 └─ [+] VersioningConfiguration
     └─ {"Status":"Enabled"}

func (*Toolkit) Drift

func (t *Toolkit) Drift(ctx context.Context, src Source, opts DriftOptions) (*DriftResult, error)

Drift produces the cloud assembly from src and checks the selected stacks, one at a time, for drift: upstream's drift.

The checks are a span, CDK_TOOLKIT_I4000 to CDK_TOOLKIT_I4592, whose start code is the diff's, as upstream's is (A.3-D2). Each stack is checked with the base credentials for its environment, resolved, and no role, as upstream checks it, so that a stack in another account needs credentials for that account, and others fail with Code "IncorrectDefaultCredentials" (K.5-D8). CloudFormation's drift detection is started, waited for, and its records read, as the internal drift package's Detect does, failing with Code "DriftDetectionFailed" when CloudFormation reports the detection failed (K.5-D9), or "DriftDetectionTimeout" after 5 minutes (K.5-D10); every page of records is read, as upstream reads them since toolkit-lib 1.44.0 (K.5-D1). A stack for which CloudFormation returns no drift results gets CDK_TOOLKIT_W4591 and no entry in the result; the others get their header at info, their sections in sync and unchecked at debug, modified and deleted at info, and CDK_TOOLKIT_I4590 with the summary. The span ends with the number of resources with drift, and of those unchecked, and a warning follows when any stack had no drift results.

The selected stacks' validation findings aren't checked, as upstream's drift doesn't check them, unlike Toolkit.Synth, Toolkit.Deploy and Toolkit.Rollback, so that an app with error annotations can still be checked for drift (K.5-D7).

A stack's error is "<display name>: " and its cause, which errors.Is and errors.As find; the stacks after it aren't checked.

The formatted sections carry no colour, as ADR 0001 translates coloured strings inside results into structured results, rendered separately (K.5-D4).

It departs from upstream in four places:

  • the result is a slice in selection order, where upstream's is an object keyed by display name, and each entry carries the stack's name, display name, resolved environment and drift records besides upstream's counts and sections (K.5-D2, K.5-D3);
  • when a stack fails, the stacks checked until then are returned beside the error, where upstream returns none (K.5-D5);
  • a stack's error names the stack, where upstream's doesn't say which stack failed (K.5-D6);
  • the span ends when the checks fail, with the counts so far, where upstream leaves it open (K.3-D10).

Cancelling ctx stops the wait for a detection, which goes on in CloudFormation, and no further stack is checked.

Example

Drift checks each selected stack for resources that were changed outside CloudFormation.

package main

import (
	"context"
	"fmt"
	"log"

	"github.com/asteroid-computing/aws-cdk-toolkit/toolkit"
)

func main() {
	ctx := context.Background()
	tk, err := toolkit.New(toolkit.Options{})
	if err != nil {
		log.Fatal(err)
	}

	src := toolkit.FromCdkApp("go run .", toolkit.CdkAppOptions{WorkingDir: "infra"})
	res, err := tk.Drift(ctx, src, toolkit.DriftOptions{})
	if err != nil {
		log.Fatal(err)
	}
	for _, s := range res.Stacks {
		fmt.Println(s.StackName)
	}
}

func (*Toolkit) Flags

func (t *Toolkit) Flags(ctx context.Context, src Source) ([]FeatureFlag, error)

Flags produces the cloud assembly from src and returns the feature flags its feature flag reports describe: upstream's flags.

The flags are those of the assembly's own reports, not those of nested assemblies, as upstream reads them: every report's flags in turn, in the order cloudassembly.Assembly.FeatureFlagReports gives. It neither synthesizes inside a span nor selects or validates stacks, and sends no messages of its own, as upstream's doesn't; the source may send its own. It closes the assembly before returning.

It fails with the errors of src, and with those of cloudassembly.Assembly.FeatureFlagReports when a report is malformed.

func (*Toolkit) List

func (t *Toolkit) List(ctx context.Context, src Source, opts ListOptions) ([]iohost.StackDetails, error)

List produces the cloud assembly from src, and reports and returns the selected stacks with their dependencies: upstream's list.

It sends CDK_TOOLKIT_I2901, whose text is the stacks' display names, one per line. It closes the assembly before returning.

It fails with the errors of src, with those of cloudassembly.Assembly.SelectStacks when the selection cannot be made, and with a cdkerr.Error of Kind cdkerr.KindAssembly when the stacks' dependencies form a cycle.

Example

List reports the selected stacks, each with the stacks it depends on. A selector that names patterns names its strategy too, and its expansion adds the stacks the selection depends on.

package main

import (
	"context"
	"fmt"
	"io"
	"log"

	"github.com/asteroid-computing/aws-cdk-toolkit/cloudassembly"
	"github.com/asteroid-computing/aws-cdk-toolkit/iohost"
	"github.com/asteroid-computing/aws-cdk-toolkit/iohost/console"
	"github.com/asteroid-computing/aws-cdk-toolkit/toolkit"
)

// quiet is a host that discards every message, so that an example prints only what it chooses to.
func quiet() iohost.Host {
	return &console.NonInteractive{Stdout: io.Discard, Stderr: io.Discard}
}

func main() {
	ctx := context.Background()
	tk, err := toolkit.New(toolkit.Options{Host: quiet()})
	if err != nil {
		log.Fatal(err)
	}

	src := toolkit.FromAssemblyDirectory("testdata/example/cdk.out", toolkit.AssemblyDirectoryOptions{})
	stacks, err := tk.List(ctx, src, toolkit.ListOptions{
		Stacks: cloudassembly.Selector{
			Strategy: cloudassembly.StrategyPatternMustMatch,
			Patterns: []string{"Service"},
			Expand:   cloudassembly.ExpandNone,
		},
	})
	if err != nil {
		log.Fatal(err)
	}
	for _, s := range stacks {
		fmt.Print(s.ID, ":")
		for _, d := range s.Dependencies {
			fmt.Print(" ", d.ID)
		}
		fmt.Println()
	}
}
Output:
Service: Network

func (*Toolkit) Orphan

func (t *Toolkit) Orphan(ctx context.Context, src Source, opts OrphanOptions) (*OrphanResult, error)

Orphan produces the cloud assembly from src and detaches the resources under opts.ConstructPaths from their stack without deleting them, in up to three change-set deployments of the stack's deployed template: upstream's orphan, which upstream marks unstable.

Every stack is synthesized, and the stack is the one the paths are in, by the longest hierarchical ID that prefixes them. The deployed template is read through the stack's lookup role, or, when that fails, with a warning, through its deploy role for reading (M.5-D8). The resources are those whose construct paths are at or under the paths given and whose logical IDs the deployed template has, each once, where upstream's are only those under them, listed once for each path (M.5-D6); the plan lists them, and CDK_TOOLKIT_I8810 asks to go on, defaulting to yes; a decline fails with a cdkerr.KindAborted error with Code "OrphanAborted", before anything changes. A stack whose creation failed is refused before the plan is shown, with a cdkerr.KindToolkit error with no Code, since there is nothing to orphan, where upstream deletes it and creates it afresh (M.5-D4).

Then, as upstream's ResourceOrphaner executes the plan:

  1. the resources' physical IDs are listed, and the attributes the deployed template references are resolved by deploying it with a temporary output for each, read back from the stack; with none, nothing is deployed;
  2. the deployed template is deployed with every reference to the resources replaced by its value, every DependsOn naming them removed, and their DeletionPolicy and UpdateReplacePolicy set to Retain;
  3. that template is deployed without the resources, which CloudFormation then leaves where they are.

Nothing is removed until step 2 has set Retain and succeeded, and no step starts once one has failed. Each step is a deployment as Toolkit.Deploy makes it through a change set (M.5-D2), named cdk-orphan-step<n>-<operation ID>, forced, with rollback, with the stack's execution role or opts.RoleARN, with the parameters the template it deploys declares, each keeping its deployed value, where upstream's are the app's template's (M.5-D3), and with no CDK_TOOLKIT_I5060, which CDK_TOOLKIT_I8810 covers. A step's error is "orphan step <n>: " and its cause, which errors.As finds, such as a deployment's; a step that didn't deploy, as for a stack paused in a failed state, fails with Code "OrphanDeployFailed", and a step 3 that changed nothing with Code "OrphanNoOp".

The result carries the import mapping, from the template summary of the stack's template, which is published first (M.5-D8); a failure to read it is a warning and an empty mapping. The final message names the next steps, with the mapping for cdk import.

Cancelling ctx stops the action before the next step starts, leaving the stack as the last step left it. Once step 3 has finished, the resources are orphaned, so an error after it, such as a cancellation or the host's, is returned beside the result; one while the mapping is read leaves the mapping empty. The errors before anything changes are cdkerr.KindToolkit errors with Code "MissingConstructPath", "StackNotFound", "InvalidConstructPath", "MultipleStacks", "OrphanNoResources" or "OrphanMissingPhysicalId".

func (*Toolkit) PublishAssets

func (t *Toolkit) PublishAssets(ctx context.Context, src Source, opts PublishAssetsOptions) (*PublishAssetsResult, error)

PublishAssets produces the cloud assembly from src and builds and publishes the assets of the selected stacks, without deploying them: upstream's publishAssets.

Upstream marks the action unstable, and refuses it unless the toolkit enables the publish-assets feature; this toolkit has no list of unstable features, so the action runs for every caller, and its options may change as upstream's do (H.5-D2).

The selected stacks' validation findings are checked first, as Toolkit.Synth checks them; a selection of no stacks gets CDK_TOOLKIT_E5001 and an empty result. The assets are those of the stacks' asset manifests, every one built before any stack would need it, as I.1's work graph builds them; a stack's CDK v1 metadata assets, which aren't in an asset manifest, are ignored, as upstream ignores them. Unless Force is set, the destinations that have their assets already are left out, as I.2's pruning leaves them out, following the cross-account rule of each stack's environment, as publishing does; when none is left, CDK_TOOLKIT_I9400 says so and the result is empty. Otherwise CDK_TOOLKIT_I9401 lists the assets to publish, they are built and published, Concurrency builds and Concurrency publishes at once, and CDK_TOOLKIT_I9402 lists them again. Each build checks first that the environment's bootstrap stack is at least the version the asset manifest requires, read through the stack's deploy role, and each publish follows the cross-account rule of the stack's environment, read once per environment from its toolkit stack. Each build and publish is a span, CDK_TOOLKIT_I5210 and CDK_TOOLKIT_I5220, around the publisher's messages. Container images are built and pushed with the docker CLI that CDK_DOCKER names, or docker, run with the process's environment, as upstream runs it (H.3-D2).

It departs from upstream in five places:

  • it runs without opting in to an unstable feature, where upstream refuses it (H.5-D2);
  • a negative Concurrency is refused before synthesis, and zero means 4, where upstream's work graph never settles for either (I.1-D4);
  • when an asset fails, the assets published until then are returned beside the errors of every asset that failed, joined, where upstream rejects with the last error only (H.5-D4, EI-1, EI-4);
  • where the cross-account rule forbids publishing to another account's bucket, an object in such a bucket isn't counted as published, so that its publish runs and refuses the bucket, where upstream's check reads no rule and counts it published (H.2-D5);
  • an asset's span ends when its build or publish fails, where upstream leaves it open (K.3-D10).

Cancelling ctx stops new builds and publishes; an upload already started is stopped too, and a multipart upload aborted, as the toolkit's Cancellation section says.

Example

PublishAssets builds and publishes the assets of the selected stacks, without deploying the stacks.

package main

import (
	"context"
	"fmt"
	"log"

	"github.com/asteroid-computing/aws-cdk-toolkit/toolkit"
)

func main() {
	ctx := context.Background()
	tk, err := toolkit.New(toolkit.Options{})
	if err != nil {
		log.Fatal(err)
	}

	src := toolkit.FromCdkApp("go run .", toolkit.CdkAppOptions{WorkingDir: "infra"})
	res, err := tk.PublishAssets(ctx, src, toolkit.PublishAssetsOptions{Concurrency: 4})
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("published", len(res.Assets), "assets")
}

func (*Toolkit) Rollback

func (t *Toolkit) Rollback(ctx context.Context, src Source, opts RollbackOptions) (*RollbackResult, error)

Rollback produces the cloud assembly from src and rolls back the selected stacks, one at a time, that a failed deployment left paused, or whose rollback failed: upstream's rollback.

The selected stacks' validation findings are checked first, as Toolkit.Synth checks them; a selection of no stacks gets CDK_TOOLKIT_E6001 and an empty result. Each stack is rolled back in its own span, CDK_TOOLKIT_I6100 to CDK_TOOLKIT_I6000, with deploy.RollbackStack, its deploy role assumed and its execution role, or opts.RoleARN, both with their placeholders replaced, once the environment's bootstrap stack is found to be at least version 23, unless opts.NoBootstrapVersionCheck is set. OrphanFailedResources with OrphanLogicalIDs fails with Code "ConflictingRollbackOptions" before the environment is reached.

A stack that fails to roll back gets CDK_TOOLKIT_E6900, and the action fails with a cdkerr.KindToolkit error with Code "RollbackFailed" wrapping the stack's error, with upstream's message. When no selected stack could be rolled back, it fails with Code "NoRollbackableStacks", and returns no result.

It departs from upstream in four places:

  • each result's environment is resolved (G.8-D6);
  • when a stack fails, the stacks rolled back until then are returned beside the error, where upstream returns none (K.3-D4);
  • StackEventPollingInterval is an option of its own (K.3-D8);
  • a stack's span ends when the stack fails, after CDK_TOOLKIT_E6900, where upstream leaves it open (K.3-D10).
Example

Rollback rolls back stacks that a failed deployment left paused, or whose rollback failed.

package main

import (
	"context"
	"fmt"
	"log"

	"github.com/asteroid-computing/aws-cdk-toolkit/toolkit"
)

func main() {
	ctx := context.Background()
	tk, err := toolkit.New(toolkit.Options{})
	if err != nil {
		log.Fatal(err)
	}

	src := toolkit.FromCdkApp("go run .", toolkit.CdkAppOptions{WorkingDir: "infra"})
	res, err := tk.Rollback(ctx, src, toolkit.RollbackOptions{OrphanFailedResources: true})
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("rolled back", len(res.Stacks), "stacks")
}

func (*Toolkit) Synth

func (t *Toolkit) Synth(ctx context.Context, src Source, opts SynthOptions) (*Assembly, error)

Synth produces the cloud assembly from src and reports the selected stacks: upstream's synth.

It first checks the assembly's validation report and the stacks' annotations, for the selected stacks and, unless opts.DisableValidateOnSynth is set, every stack whose ValidateOnSynth is set. When there are findings, it sends them as CDK_TOOLKIT_E9600, and it fails when they reach Options.AssemblyFailureAt.

With one stack selected, it sends CDK_TOOLKIT_I1901 with the stack's template; with several, CDK_TOOLKIT_I1902 with their IDs, and a message saying how to see a template.

It returns the assembly, which the caller must close. The assembly is also a Source, for working on the same synthesis with other actions. If Synth fails, it closes the assembly itself.

It fails with the errors of src, with those of cloudassembly.Assembly.SelectStacks when the selection cannot be made, and with a cdkerr.Error of Kind cdkerr.KindAssembly and Code "AssemblyError" when the validation findings reach Options.AssemblyFailureAt; that error's SynthesisCode is "AnnotationErrors" or "StrictAnnotationWarnings", and its cause is a *cloudassembly.StacksError naming the stacks checked.

Example

Synth produces the cloud assembly and reports the stacks it selects. The assembly it returns holds a lock on its directory, and its caller closes it.

package main

import (
	"context"
	"fmt"
	"io"
	"log"

	"github.com/asteroid-computing/aws-cdk-toolkit/iohost"
	"github.com/asteroid-computing/aws-cdk-toolkit/iohost/console"
	"github.com/asteroid-computing/aws-cdk-toolkit/toolkit"
)

// quiet is a host that discards every message, so that an example prints only what it chooses to.
func quiet() iohost.Host {
	return &console.NonInteractive{Stdout: io.Discard, Stderr: io.Discard}
}

func main() {
	ctx := context.Background()
	tk, err := toolkit.New(toolkit.Options{Host: quiet()})
	if err != nil {
		log.Fatal(err)
	}

	src := toolkit.FromAssemblyDirectory("testdata/example/cdk.out", toolkit.AssemblyDirectoryOptions{})
	asm, err := tk.Synth(ctx, src, toolkit.SynthOptions{})
	if err != nil {
		log.Fatal(err)
	}
	defer asm.Close()

	for _, s := range asm.Stacks() {
		fmt.Print(s.StackName, ":")
		for _, d := range s.Dependencies {
			fmt.Print(" ", d.Info().ID)
		}
		fmt.Println()
	}
}
Output:
Network:
Service: Network

func (*Toolkit) Validate

func (t *Toolkit) Validate(ctx context.Context, src Source, opts ValidateOptions) (*iohost.ValidateResult, error)

Validate produces the cloud assembly from src and returns the selected stacks' validation report, with CloudFormation's early validation unless opts.Offline is set: upstream's validate.

The report is the app's own validation report, filtered to the selected stacks, and the stacks' annotations unless the app's report holds them, as Toolkit.Synth reads them, but Validate doesn't fail on what it finds: the result's Conclusion says whether any report failed. Upstream's deprecated title, which it never sets, is left empty.

Online validation creates a change set for each selected stack, one at a time, in the order they were selected, waits for CloudFormation to compute it, never executes it, and deletes it again, with the stack it created; it reaches the stack through its deploy role, and publishes the stack's template first when its asset manifest publishes it, as upstream's does (M.10-D5). The problems CloudFormation's early validation finds become the violations of one more report, named CloudFormation, which concludes in failure; it is added only when there are violations. Any error in a stack's online validation, such as missing credentials or a refused request, is sent as CDK_TOOLKIT_W9602 and validation goes on with the next stack, as upstream's is, so that it doesn't change the conclusion; but an error from the host fails the action, as in every other action, where upstream's is sent as CDK_TOOLKIT_W9602 too (M.10-D7). The change set gets the parameters a deployment with the zero StackParameters would send, every deployed value kept and the template's defaults for the rest, where upstream's gets the defaults alone; so a new stack with a parameter without a default gets CDK_TOOLKIT_W9602, as a deployment of it would fail, but an existing one that has a value is validated (M.10-D4). A violation's template path is the stack's template file, where upstream's is "<stack name>.template.json", which names no file for a stack in a stage (M.10-D8). A template too large to pass directly, of a stack without a template asset, is uploaded to the staging bucket before its change set is created, as a deployment's is, where upstream adds it to an asset manifest it discards, so that the change set names an object never uploaded.

When no report has a violation, CDK_TOOLKIT_I9600 carries the result, even when a report concludes in failure without one; otherwise CDK_TOOLKIT_E9600 does, with the reports' text.

Cancelling ctx stops the action with an error that satisfies errors.Is(err, ctx.Err()), and no result, where upstream can't be cancelled; the change set in progress is deleted first, as the toolkit's Cancellation section says (M.10-D6).

Example

Validate returns the selected stacks' validation report, and by default asks CloudFormation to validate each stack's template too. With Offline set it reaches no AWS account.

package main

import (
	"context"
	"fmt"
	"log"

	"github.com/asteroid-computing/aws-cdk-toolkit/toolkit"
)

func main() {
	ctx := context.Background()
	tk, err := toolkit.New(toolkit.Options{})
	if err != nil {
		log.Fatal(err)
	}

	src := toolkit.FromAssemblyDirectory("cdk.out", toolkit.AssemblyDirectoryOptions{})
	report, err := tk.Validate(ctx, src, toolkit.ValidateOptions{Offline: true})
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("%+v\n", report)
}

type ValidateOptions

type ValidateOptions struct {
	// Stacks selects the stacks to validate; the zero Selector selects every stack, those in nested assemblies included.
	Stacks cloudassembly.Selector

	// Offline leaves out CloudFormation's early validation, so that only the app's own report and the stacks' annotations are read, and AWS isn't reached: upstream's online false, inverted so that the zero value is upstream's default, as ADR 0001 inverts default-true flags (M.10-D1).
	Offline bool
}

ValidateOptions are the options for Toolkit.Validate: upstream's ValidateOptions.

The zero value validates online, as upstream's default does: it reaches AWS, and creates and deletes a change set in every selected stack's account (M.10-D1).

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL