Skip to content

feat(core): embed structured design context in synthesized templates (MetadataContext) - #38381

Merged
mergify[bot] merged 20 commits into
aws:mainfrom
satyakigh:context-constructs
Nov 13, 2026
Merged

mergify[bot] merged 20 commits into
aws:mainfrom
satyakigh:context-constructs

Conversation

@satyakigh

@satyakigh satyakigh commented Jul 22, 2026 •

Copy link
Copy Markdown
Contributor

Issue # (if applicable)

RFC tracking issue: aws/aws-cdk-rfcs#994

Accepted RFC: aws/aws-cdk-rfcs#981

Reason for this change

CloudFormation templates preserve deployed configuration but usually lose the rationale, invariants, change-safety guidance, and provenance available in CDK source. CloudFormation defines the advisory com.aws.cloudformation.Context metadata schema for preserving that information, but CDK users need a typed authoring API.

Description of changes

  • Adds CfnResourceMetadataContext for setting or clearing Context on selected CfnResource constructs during synthesis.
  • Adds CfnTemplateMetadataContext for setting or clearing template-level Context.
  • Mirrors the published resource, template, mutability, reference, and trust fields without adding another vocabulary.
  • Uses IConstructSelector for explicit resource targeting. The default selects a CfnResource scope or its immediate CfnResource default child.
  • Uses complete-value replacement rather than implicit merging. Aspect priority and scope determine which overlapping operation applies last.
  • Preserves NestedStack behavior and does not cross Stage assembly boundaries.
  • Rejects invalid trust data, redundant sparse mutability entries, selectors that match no CfnResource, and unresolved values in top-level template Context.
  • Adds public API documentation, README examples, unit coverage, and an integration snapshot.

The public API and stable-release plan were approved in RFC 994. The approved surface keeps resource Context separate from targeting options. jsii generates Python as set(context, *, priority=None, selector=None) and Java as set(context) or set(context, options). RFC 994 also requires rejecting a mutability entry that repeats the resource-level mutable default so the map remains sparse. Existing applications synthesize unchanged unless they call the new APIs.

Checklist


By submitting this pull request, I confirm that my contribution is made under the terms of the Apache-2.0 license

@satyakigh
satyakigh requested a review from a team as a code owner July 22, 2026 23:46
@github-actions github-actions Bot added p2 beginning-contributor [Pilot] contributed between 0-2 PRs to the CDK labels Jul 22, 2026
@aws-cdk-automation
aws-cdk-automation requested a review from a team July 22, 2026 23:47

@aws-cdk-automation aws-cdk-automation left a comment •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(This review is outdated)

@satyakigh satyakigh changed the title feat(core): Add MetadataContext for structured template context feat(core): add MetadataContext for structured template context Jul 22, 2026
@aws-cdk-automation
aws-cdk-automation dismissed their stale review July 22, 2026 23:51

✅ Updated pull request passes all PRLinter validations. Dismissing previous PRLinter review.

@satyakigh
satyakigh force-pushed the context-constructs branch from 8da308b to 517cab1 Compare July 22, 2026 23:51

@mrgrain mrgrain left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey, since the feature is already stable, the Mixin should go straight into aws-cdk-lib as well. The preview package is being phased out.

@mergify
mergify Bot dismissed mrgrain’s stale review July 23, 2026 04:10

Pull request has been modified.

@aws-cdk-automation aws-cdk-automation added the pr/needs-community-review This PR needs a review from a Trusted Community Member or Core Team Member. label Jul 23, 2026
@satyakigh
satyakigh force-pushed the context-constructs branch from b362a0a to b6106b6 Compare July 23, 2026 14:28
@satyakigh

Copy link
Copy Markdown
Contributor Author

Hey, since the feature is already stable, the Mixin should go straight into aws-cdk-lib as well. The preview package is being phased out.

Sounds good, updated

@satyakigh
satyakigh force-pushed the context-constructs branch from b6106b6 to 5caa8fa Compare July 26, 2026 19:47
@github-actions

github-actions Bot commented Nov 2, 2026

Copy link
Copy Markdown
Contributor

👋 It looks like your PR description follows the template but is missing a valid issue number in the first section.

PRs without a linked issue will receive lower priority for review and merging. Please update the description to include a reference like Closes #123. If no existing issue matches your change, create one first.

@maintainer-for-aws maintainer-for-aws Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

See the review summary comment for the overview; the notes below are inline.

Comment on lines +19 to +28
}
if (context.mutability !== undefined) {
if (Token.isUnresolved(context.mutability)) {
out.mutability = context.mutability;
} else {
const entries = Object.entries(context.mutability);
const deviations = entries.filter(([, level]) => level !== context.mutable);
if (entries.length === 0 || deviations.length > 0) {
out.mutability = Object.fromEntries(deviations);
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Recommended — renderResourceContext has a dedicated branch for an unresolved mutability map that passes the token through verbatim and short-circuits the entries/deviations filtering, because iterating a token map with Object.entries() would be wrong. The unit suite exercises token/Lazy inputs only for the list fields (must, deps), never for mutability, so this is the one branch of renderResourceContext with no asserting test. If the guard regressed — falling through to Object.entries() on the token and throwing, or silently dropping the map — the suite would stay green. A Token.isUnresolved guard owes a test that passes an unresolved token through it (AGENTS.md#unit-tests).

Suggested change: Add a resource-level test alongside the existing Lazy test that sets mutability to an unresolved token (e.g. Lazy.any({ produce: () => ({ QueueName: 'must-never-change' }) })) and asserts the rendered Metadata contains the resolved map unchanged (including an entry that would otherwise be filtered as redundant), locking in that the token is passed through without the sparse-deviation filtering.

Comment thread packages/aws-cdk-lib/README.md Outdated
Comment on lines +1624 to +1637
CDK can embed structured, advisory context into the
`Metadata["com.aws.cloudformation.Context"]` sections of synthesized CloudFormation
templates. It captures the *why* behind your infrastructure — rationale, hard
invariants, change-safety and provenance — so that humans and
automated tools working with the deployed template later can act on the author's
intent instead of guessing it. The structural source of truth is the published
[AWS CloudFormation `Metadata` Context schema](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-attribute-metadata.html#aws-attribute-metadata-context-schema):
every field it defines is optional, and it sets no `minLength`/`minItems`, so
blank strings and empty arrays are structurally valid. The schema is advisory —
CloudFormation does not validate or enforce `Metadata` fields. CDK property names
are the schema's field names (`why`, `must`, `mutable`, `mutability`, `trust.src`,
`trust.conf`, `trust.cite`, `trust.note`, `deps`; `arch`, `must`, `ref`, `owner`),
so code and template use one vocabulary. CDK adds typed enums, targeting, and
the validation described below.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No need.

Suggested change
CDK can embed structured, advisory context into the
`Metadata["com.aws.cloudformation.Context"]` sections of synthesized CloudFormation
templates. It captures the *why* behind your infrastructure — rationale, hard
invariants, change-safety and provenance — so that humans and
automated tools working with the deployed template later can act on the author's
intent instead of guessing it. The structural source of truth is the published
[AWS CloudFormation `Metadata` Context schema](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-attribute-metadata.html#aws-attribute-metadata-context-schema):
every field it defines is optional, and it sets no `minLength`/`minItems`, so
blank strings and empty arrays are structurally valid. The schema is advisory —
CloudFormation does not validate or enforce `Metadata` fields. CDK property names
are the schema's field names (`why`, `must`, `mutable`, `mutability`, `trust.src`,
`trust.conf`, `trust.cite`, `trust.note`, `deps`; `arch`, `must`, `ref`, `owner`),
so code and template use one vocabulary. CDK adds typed enums, targeting, and
the validation described below.
CDK offers structured API to populate the [CloudFormation Metadata Context attribute](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-attribute-metadata.html#aws-attribute-metadata-context-schema)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All the functions in this file are only imported by metadata-context.ts - move them over there.

out.mutability = context.mutability;
} else {
const entries = Object.entries(context.mutability);
const deviations = entries.filter(([, level]) => level !== context.mutable);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this to save maybe 1 or 2 redundant declarations the customer made (explicitly) by mistake? Not worth it - leave as is.

export const METADATA_CONTEXT_KEY = 'com.aws.cloudformation.Context';

export function renderResourceContext(context: CfnResourceMetadataContextProps): Record<string, any> {
const out: Record<string, any> = {};

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why did you decide to copy the entire props object? We don't usually do that, there are plenty of structs being passed by references to the underlying L1. Not to mention that all the properties are readonly so a mutation is not expected.

}
if (context.trust !== undefined) {
const trust: Record<string, any> = {};
if (context.trust.src !== undefined) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How can context.trust.src be undefined if src is required? Feels like your coding against the compiler here.

Please simplify, this entire function can be dropped - just pass the struct as is.

Comment thread packages/aws-cdk-lib/README.md Outdated
omitted. Both fields record what the team considers safe to change, not what
CloudFormation can change in place.

### Targeting: exactly what receives context

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reduce this entire section to:

  1. Specify the default selection (defaultChild).
  2. Mention there is a selector property to select other resources.

Thats it. Please do not repeat or list all the available APIs - thats why we have ref docs.

Comment thread packages/aws-cdk-lib/README.md Outdated
resources are inside Stages selects nothing and fails. Set context inside each
Stage; this also lets environments carry different guidance:

```typescript

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This example is trivial because it just sets a context of two different scopes. Not needed.

Comment thread packages/aws-cdk-lib/README.md Outdated

Context can be set or cleared on resources in a `NestedStack`. Calls do not apply
across a `Stage`: each Stage is synthesized as its own cloud assembly and Aspects
are invoked separately for each assembly, so a call on an `App` whose only

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

so a call on an App whose only

Maybe this is the example you wanted to show, but don't think its necessary - too much of an edge case

Comment thread packages/aws-cdk-lib/README.md Outdated
});

// A helper the L2 exposes; set when the function was created with a dead-letter queue.
if (lambdaFunction.deadLetterQueue) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I know I asked you for this example before but I think its not needed now, its obvious.

Comment thread packages/aws-cdk-lib/README.md Outdated
});
```

For an L3 pattern (or any multi-resource construct) with no `defaultChild`,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not needed as a new example, just say the same mechanism can be used for an L2 and L3.

@mergify

mergify Bot commented Nov 10, 2026

Copy link
Copy Markdown
Contributor

Tick the box to add this pull request to the merge queue (same as @mergifyio queue). If it does not match the queue conditions yet, it enters the queue once it does.

  • Queue this pull request

1 similar comment
@mergify

mergify Bot commented Nov 11, 2026

Copy link
Copy Markdown
Contributor

Tick the box to add this pull request to the merge queue (same as @mergifyio queue). If it does not match the queue conditions yet, it enters the queue once it does.

  • Queue this pull request

…and aspect + mixins to set context on a resource and template
…ib core

The mixins-preview package is being phased out and the feature is stable,
so the Mixin ships directly in aws-cdk-lib alongside the MetadataContext
facade (review feedback).

- MetadataContextMixin now lives in core/lib/mixins/ and is exported flat
  from aws-cdk-lib (a top-level 'mixins' jsii submodule is not possible:
  JSII5011 name conflict with the Mixins class), with an awslint exclusion
  for the mixin-namespace rule.
- Unit test moved to core/test/mixins/, adapted to core's toCloudFormation
  convention.
- Integ test moved to @aws-cdk-testing/framework-integ test/core/test/
  with regenerated snapshot.
- aws-cdk-lib README documents the mixin inline; all mixins-preview
  changes reverted.
@mergify

mergify Bot commented Nov 13, 2026

Copy link
Copy Markdown
Contributor

Thank you for contributing! Your pull request will be updated from main and then merged automatically (do not update manually, and be sure to allow changes to be pushed to your fork).

@mergify

mergify Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

✅ Merged into main as 708bee9 at 17:12 UTC

37 min in the queue, 34 min of it CI.

So far

  • ✅ Entered the queue Fri 13 Nov, 16:35 · rule default-squash · triggered by rule automatic merge
  • ✅ Passed · in place
  • ✅ Merged 17:12 · 708bee9 · squash
3 merge conditions met
  • github-review-approved · required by GitHub branch protection
  • any of · required by GitHub branch protection:
    • check-success = validate-pr
    • check-neutral = validate-pr
    • check-skipped = validate-pr
  • any of · required by GitHub branch protection:
    • check-success = build
    • check-neutral = build
    • check-skipped = build

Times in UTC · dashboard · how the merge queue works

@mergify

mergify Bot commented Nov 13, 2026

Copy link
Copy Markdown
Contributor

Thank you for contributing! Your pull request will be updated from main and then merged automatically (do not update manually, and be sure to allow changes to be pushed to your fork).

@github-actions

Copy link
Copy Markdown
Contributor

Comments on closed issues and PRs are hard for our team to see.
If you need help, please open a new issue that references this one.

This branch was previously deployed

1 inactive deployment
automation — 87fc7749 Deployed Nov 13, 2026 by mergify[bot] via validate-pr #378922
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

beginning-contributor [Pilot] contributed between 0-2 PRs to the CDK p2 pr/community-review-timeout pr/needs-maintainer-review This PR needs a review from a Core Team Member

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants