Skip to content

Commit

Permalink
feat(core): cloudformation resource metadata (#9063)
Browse files Browse the repository at this point in the history
Exposes a mechanism to add metadata to CloudFormation resources by key name. This can be used for internal usage like setting the CDK metadata path, or for other metadata like CfnInit use cases.

This is a prerequisite of #8788, where it will be used to add CfnInit metadata.

----

*By submitting this pull request, I confirm that my contribution is made under the terms of the Apache-2.0 license*
  • Loading branch information
njlynch authored Jul 15, 2020
1 parent db9d29b commit b0f8729
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 3 deletions.
20 changes: 17 additions & 3 deletions packages/@aws-cdk/core/lib/cfn-resource.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,9 +93,7 @@ export class CfnResource extends CfnRefElement {
// path in the CloudFormation template, so it will be possible to trace
// back to the actual construct path.
if (this.node.tryGetContext(cxapi.PATH_METADATA_ENABLE_CONTEXT)) {
this.cfnOptions.metadata = {
[cxapi.PATH_METADATA_KEY]: this.node.path,
};
this.addMetadata(cxapi.PATH_METADATA_KEY, this.node.path);
}
}

Expand Down Expand Up @@ -238,6 +236,22 @@ export class CfnResource extends CfnRefElement {
addDependency(this, target, `"${this.node.path}" depends on "${target.node.path}"`);
}

/**
* Add a value to the CloudFormation Resource Metadata
* @see https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/metadata-section-structure.html
*
* Note that this is a different set of metadata from CDK node metadata; this
* metadata ends up in the stack template under the resource, whereas CDK
* node metadata ends up in the Cloud Assembly.
*/
public addMetadata(key: string, value: any) {
if (!this.cfnOptions.metadata) {
this.cfnOptions.metadata = {};
}

this.cfnOptions.metadata[key] = value;
}

/**
* @returns a string representation of this resource
*/
Expand Down
24 changes: 24 additions & 0 deletions packages/@aws-cdk/core/test/test.cfn-resource.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,4 +73,28 @@ export = nodeunit.testCase({

test.done();
},

'can add metadata'(test: nodeunit.Test) {
// GIVEN
const app = new core.App();
const stack = new core.Stack(app, 'TestStack');
const resource = new core.CfnResource(stack, 'DefaultResource', { type: 'Test::Resource::Fake' });

// WHEN
resource.addMetadata('Beep', 'Boop');

// THEN
test.deepEqual(app.synth().getStackByName(stack.stackName).template, {
Resources: {
DefaultResource: {
Type: 'Test::Resource::Fake',
Metadata: {
Beep: 'Boop',
},
},
},
});

test.done();
},
});

0 comments on commit b0f8729

Please sign in to comment.